Search code examples
phplaravel-5.3

Error using laravel's eloquent relationships


I am having issues trying to use data from eloquent relationships. I have defined a relationship in my post model.

class post extends Model
{
    //
    protected $fillable = ['title', 'contents', 'user_id', 'status'];

    public function users(){
        return $this->belongsTo('App\User');
    }

}

I am trying to access this relationship from my controller like so:

public function showBlog(){
        $post = post ::where('status', 1)
            ->users()
            ->orderBy('id', 'desc')
            ->paginate(3);
     return  view ('blog')
            ->with('posts', $post);
    }

But am getting this error: Call to undefined method Illuminate\Database\Query\Builder::users()

Please how do I solve this? I am using laravel 5.3


Solution

  • Because relationship is behavior of a model and what you are getting is a query builder instance as you are just building a query. The framework still building the query and not certain about the outcomes or model it will exactly get from it which is necessary in order to build a relationship.

    You need to first generate the instance of the model Post before accessing relations.

    Try like this:

    post ::where('status', 1)->first()
                ->users()
                ->orderBy('id', 'desc')
                ->paginate(3);
    

    Here the method first() will first run the query post ::where('status', 1) for Post and get the first result model for you and then rest of the query will be performed on this model instance.

    But, this query will result only users for the first post of results. If you like to get all posts with users relation try using with like:

    post::where('status', 1)->with('users')
                ->orderBy('id', 'desc')
                ->paginate(3); 
    

    This will result in pagination results for posts having their users.

    Hope it would help.