Using local scope in eloquent

If there are repeating eloquent conditions in different methods and we can group and reuse those in different methods of project using local scopes.

Suppose if we have following two eloquent queries where a particular user id is 4 and we want to retrieve all the posts that are posted in July and August we can write this in following way without local scope.

$julPosts = Post::where( 'user_id', 4 )->whereMonth(07)->get();

$augPosts = Post::where( 'user_id', 4 )->whereMonth(08)->get();


From above we can see condition user_id -> 4 is getting repeated in multiple eloquent queries.

Hence, we can resuse this using local scope like below.

//In Post.php 

public function scopeUserIdOfList( $query ) {
  return $query->where( 'user_id', 4 );
}


Now in Controller we can modify our above eloquent queries like below

$julPosts = Post::userIdOfList()->whereMonth(07)->get();

$augPosts = Post::userIdOfList()->whereMonth(08)->get();


We can also give parameters to our local scope method like below.

//In Post.php 

public function scopeUserIdOfList( $query, $userId ) {
   return $query->where( 'user_id', $userId );
}


Then in controller, we can pass user id 4 to our local scope.

$julPosts = Post::userIdOfList(4)->whereMonth(07)->get();

$augPosts = Post::userIdOfList(4)->whereMonth(08)->get();

Related Posts


Using WhereIn

Updating multiple rows

Using Like

Using orWhere

What is Query Builder?

Using "with" in eloquent query

Getting last inserted id

Selecting last row of a table

Using parameters in find() method

Using global scope in eloquent