Skip to content

Laravel eloquent complex queries on relationships

Last updated on February 17, 2018

Very Laravel developer should know this little trick, using this trick you can define complex conditions on the eloquent relationships. This method chaining helps you to add custom where/filter conditions for relation columns.

Sometimes the simple belongsTo() and hasOne() functions can not quite manifest the complex relationship function you did like to use. Fortunately , Laravel lets you adjust the relationship query. Let’s jump right in with the model we will be looking at.

class User extends Eloquent {
  public function filmProjects()
  {
    // we can add ->where(), ->with(), or any other function from
    return $this->belongsTo('Project')->where('type','=','film');
  }
  public function projects() // unfiltered version of projects
  {
    return $this->belongsTo('Project');
  }
 }
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments