If you are working on a Laravel web application. And you do not know about query scope, how query scope is made, and how to use it. So today you will learn this here. So, In this tutorial, you will learn how to create and use query scopes, with laravel eloquent model, relationship, and join.
Query scopes are defined as methods within an Eloquent model class and are typically prefixed with the word “scope”. By convention, Laravel automatically recognizes these methods as query scopes and applies them when chaining methods on a query builder instance.
How to Create and Use Query Scope in Laravel Eloquent
Do you know that the query scope is created in Laravel. It can also use query scope with models, relationships and joins. you can see below
- Create and Use Basic Query Scope in Model
- Laravel 10 Create Dynamic Scope in Model
- Laravel 10 Apply Scope with Relationship
Create and Use Basic Query Scope in Model
Now, you will learn how to create and use scope in your laravel model. You could do like:
Go to app/Post.php and create a scope here:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Post extends Model { public $table = "posts"; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'id', 'title', 'body', 'status' ]; /** * Scope a query to only include popular users. * * @param \Illuminate\Database\Eloquent\Builder $query * @return \Illuminate\Database\Eloquent\Builder */ public function scopeStatus($query) { return $query->where('status', 1); } }
Use Basic Query Scope on Controller:
You could use model query scope in your laravel web application controllers, like following:
Post::status()->get(['id','title']);
In this example, the “active” query scope is applied to the Post
model, resulting in a query that fetches only active users.
Laravel 10 Create Dynamic Scope in Model
Next, You will learn how to create and use dynamic query scope in laravel web application.
You can create dynamic query scopes in laravel model:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Post extends Model { public $table = "posts"; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'id', 'title', 'body', 'status' ]; /** * Scope a query to only include popular users. * * @param \Illuminate\Database\Eloquent\Builder $query * @return \Illuminate\Database\Eloquent\Builder */ public function scopeStatus($query, $type) { return $query->where('status', $type); } }
Dynamic Scope Query On Controller
You could use dynamic model query scope in your laravel web application controllers like:
Post::status(1)->get(['id',title']);
Here, the “status” query scope allows you to retrieve posts with a specific status, such as “1.”
Laravel 10 Apply Scope with Relationship
Let’s use the following example for how to use query scopes with laravel relationships.
Let’s say you have two tables, categories
and posts
, and they are related through a one-to-many relationship where a category can have multiple posts. Here’s an example of how you can define a query scope in the Category
model to retrieve categories along with their related posts:
class Category extends Model { public function scopeWithPosts($query) { return $query->with('posts'); } }
In the above code, to define a query scope named “withPosts” that uses the with()
method to eager load the related posts
for each category.
To use this query scope, you can chain it onto a query builder instance when querying the Category
model:
$categories = Category::withPosts()->get();
This code will retrieve all categories along with their related posts.
You can access the posts for a specific category like this:
$category = Category::withPosts()->find($categoryId); $posts = $category->posts;
In this example, to find a category by its ID and eager load its related posts. Then, =access the posts
relationship to retrieve the associated posts for that category.
Conclusion
In conclusion, Laravel query scopes are a powerful feature that allows you to define reusable query constraints within your model classes. By encapsulating common query logic into methods prefixed with “scope,” you can easily apply these constraints to query builder instances. Query scopes enhance code reusability, readability, and maintainability by centralizing query logic and making it more accessible throughout your application. They are a valuable tool for building expressive and efficient database queries in Laravel.