user10233596
user10233596

Reputation:

Get data from pivot table eloquent

I am trying to fetch data from pivot table, but it says "Trying to get property 'tags' of non-object". Also find(1) in controller doesn't return anything, even though the table has some data.

My models:

class Videos extends Model
{
    protected $table = 'videos';
    function tags(){
        return $this->belongsToMany('App\Models\Videos\Tags','tag_video','video_id','tag_id');

    }


class Tags extends Model
{

    function videos(){
        return $this->belongsToMany('App\Models\Videos\Videos','tag_video', 'tag_id','video_id');
    }
}

My controller:

 public function fetch(){
        $videos_from_supercategories =
        $videos_with_tags = Videos::find(1);
        $tags = $videos_with_tags->tags->first();

      $data['tags']=$tags;

        return $data;
    }

Can anyone help please?

Upvotes: 0

Views: 150

Answers (1)

Thijs
Thijs

Reputation: 1012

Videos::find(1) is trying to find video with id = 1, if this isnt presented it return nothing and you get the exception, you can use findOrFail(1).

The findOrFail will throw model not found exception, you want this to happen because otherwise you are trying to access properties on a non-object.

In you relation you have to specify what columns you want to include:

public function fetch()
{
    return Videos::findOrFail(1)->tags->first()->pivot->column1;
}

class Videos extends Model
{
    protected $table = 'videos';
    function tags()
    {
        return $this->belongsToMany('App\Models\Videos\Tags','tag_video','video_id','tag_id')->withPivot('column1', 'column2');
    }
}

Upvotes: 1

Related Questions