Scopes in Laravel are a way to encapsulate common queries that you may need to run against a model. They allow you to define a query you can use in multiple places in your application.
This minimizes the code while writing the query and is an easy way to ensure every query for a given model receives certain constraints.
Here’s an example of a local scope in Laravel for instance.
code
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
/**
* Scope a query to only include the most starred posts.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeStarred($query)
{
return $query->where('starred', '>', 30);
}
}
// this will return all the
// posts that have more than 30 stars
$posts = Post::starred()->get();
Copy
As you can tell, the starred scope is a local scope that returns all the posts that have more than 30 stars. The same goes for global scopes as well.
Assistant
Laravel là một framework PHP mạnh mẽ và phổ biến dùng để phát triển các ứng dụng web. Trong Laravel, có một số khái niệm quan trọng như "scope" và "relationships", và bài viết này giới thiệu một phương thức mới gọi là , giúp hỗ trợ tốt hơn cho những khái niệm này.
The new withAttributes method
To make scopes more powerful, the newest release brings a new method called withAttributes that allows you to add a where clause to the query with the given attribute constraints, and also applies the attributes to any model that are created via the relationship or scope.
This means that not only will the query be constrained by the attributes, but any models that are created via the relationship or scope will also have the attributes applied automatically.
Using it on scopes
Here’s an example of how you can use the withAttributes method on a scope.
code
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
/**
* Scope a query to only include the most starred posts.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeFeatured($query)
{
return $query->withAttributes(['featured' => true]);
}
}
Copy
Here’s how you can use this for both, creating a model and querying the model.
code
<?php
use App\Post;
// this will create a new post with
// the `featured` attribute set to `true`
$post = Post::featured()->create([\
'title' => 'My featured post'\
]);
$post->featured; // true
// this will return all the posts that
// have the `featured` attribute set to `true`
$posts = Post::featured()->get();
Copy
Using it in relationships
You can also use the withAttributes method on relationships. Here’s an example.
code
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function posts()
{
return $this->hasMany(Post::class);
}
public function featuredPosts()
{
return $this->posts()->withAttributes(['featured' => true]);
}
}
Copy
Here’s how you can use it to retrieve all the featured posts for a user.
code
<?php
use App\User;
$user = User::find(1);
// this will return all the posts
// that have the `featured` attribute set to `true`
$posts = $user->featuredPosts()->get();
Copy
Similarly, you can also set the attributes while creating a new model via the relationship.
code
<?php
use App\User;
$user = User::find(1);
// this will create a new post with
// the `featured` attribute set to `true`
$post = $user->featuredPosts()->create([\
'title' => 'My featured post'\
]);
$post->featured; // true
Copy
In closing
I think this feature is pretty neat and it essentially combines two scenarios into one conveniently. It’s a nice addition to Laravel’s Eloquent ORM and I’m sure it will be useful in many instances.
Learn the fundamentals of PHP 8 (including 8.1, 8.2, 8.3, and 8.4), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell.
It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8.
So, if you're looking for a quick and easy way to PHP 8, this is the book for you.
👋 Hi there! I'm Amit. I write articles about all things web development.
You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.
Scope là một cách để nhóm lại các truy vấn (query) thường dùng vào trong một hàm, giúp bạn dễ dàng sử dụng lại chúng ở nhiều nơi khác nhau trong ứng dụng của bạn. Ví dụ, nếu bạn muốn lấy tất cả các bài viết có hơn 30 sao, bạn có thể định nghĩa một scope như sau:
php
public function scopeStarred($query)
{
return $query->where('starred', '>', 30);
}
Khi bạn gọi Post::starred()->get(), Laravel sẽ tự động áp dụng điều kiện này và chỉ trả về các bài viết đáp ứng yêu cầu.
2. Phương thức mới withAttributes
Phương thức withAttributes cho phép bạn thêm điều kiện (where clause) vào truy vấn dựa trên các thuộc tính (attributes) cụ thể. Điều đặc biệt là khi bạn sử dụng withAttributes, nó không chỉ áp dụng cho truy vấn mà còn cho bất kỳ model nào được tạo ra thông qua relationship hoặc scope đó.
Ví dụ sử dụng withAttributes trong scope
Giả sử bạn có một scope gọi là featured:
php
public function scopeFeatured($query)
{
return $query->withAttributes(['featured' => true]);
}
Khi bạn gọi Post::featured()->create([...]), bài viết được tạo sẽ tự động có thuộc tính featured là true. Tương tự, nếu bạn lấy danh sách bài viết, tất cả bài viết sẽ có thuộc tính này.
3. Sử dụng withAttributes trong quan hệ (relationships)
Bạn cũng có thể sử dụng withAttributes trong các mối quan hệ. Giả sử bạn có một User có nhiều Post, bạn có thể tạo một phương thức để lấy tất cả bài viết nổi bật như sau:
php
public function featuredPosts()
{
return $this->posts()->withAttributes(['featured' => true]);
}
Khi bạn gọi $user->featuredPosts()->get(), bạn sẽ nhận được tất cả các bài viết của người dùng có thuộc tính featured là true.
4. Kết luận
Phương thức withAttributes giúp giảm bớt mã lệnh cần viết khi tạo các truy vấn phức tạp và đảm bảo rằng các thuộc tính được áp dụng nhất quán trong các mô hình. Với các tính năng như vậy, Laravel trở thành một lựa chọn tuyệt vời cho việc phát triển ứng dụng web.
Hy vọng giải thích này giúp bạn hiểu rõ hơn về các khái niệm trong Laravel! Nếu bạn có câu hỏi cụ thể nào, đừng ngần ngại hỏi nhé!