Laravel Eloquent hasOne returns empty

I have two tables named "works" and "slides", and two classes that extend Eloquent named "Work" and "Slide". In my "works" table, I have an "id" column, a "title" column, a "description" column and an "image" column and inside my "slides" table. I have a composite key using a two-column foreign key named 'id' and 'work_id'.

This is how my database connection looks like: Database relationship

This is the code for my slide class:

class Slide extends Eloquent {

    public $timestamps = false;

    public function workId() {
        return $this->hasOne('work', 'work_id', 'id');



And this is the code for my Work class:

class Work extends Eloquent {

    public $timestamps = false;



Inside my index page, I am trying to get the Work object by calling the 'workId () method on my Slide object, but it returns empty with this code:

$slides = Slide::all();
$works = new \Illuminate\Database\Eloquent\Collection;
foreach ($slides as $slide) {


However, if I replace the call to '$ slide-> workId ()' with:



then it will find the string with no problem.

What should I do to get the function to return a Work object instead of calling Work :: find ()?


source to share

1 answer

The slide belongs to the work because the foreign key works inside the slide table. You are also using the wrong name for the relationship function and the wrong syntax for hasOne.

You need to use:

class Slide extends Eloquent {

    public $timestamps = false;

    public function work() {
        return $this->belongsTo('Work');
        //or return $this->belongsTo('Work', 'work_id', 'id');



To get a Work that belongs to a slide: $slide->work

Note: you are using association () for belongsTo, not push ()



All Articles