Có nghĩa là sao bạn có thể giải thích rõ hơn như thể tôi là học sinh lớp 10
 trong tài liệu 
# The new withAttributes method for relationships and scopes in Laravel


February 16, 2025
·[Laravel](https://www.amitmerchant.com/categories/#Laravel)

Scopes in Laravel are [a way to encapsulate common queries](https://www.amitmerchant.com/laravel-eloquent-global-local-scope/) 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.

- [The new `withAttributes` method](https://www.amitmerchant.com/with-attributes-scopes-laravel/#the-new-withattributes-method)
  - [Using it on scopes](https://www.amitmerchant.com/with-attributes-scopes-laravel/#using-it-on-scopes)
  - [Using it in relationships](https://www.amitmerchant.com/with-attributes-scopes-laravel/#using-it-in-relationships)
- [In closing](https://www.amitmerchant.com/with-attributes-scopes-laravel/#in-closing)

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.

```
<?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.

## The new `withAttributes` method

To make scopes more powerful, the newest release brings [a new method](https://github.com/laravel/framework/pull/53720) 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.

```
<?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**.

```
<?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.

```
<?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.

```
<?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.

```
<?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.

[**Previous:** Introducing ConsolePad — The missing Notepad in Chrome DevTools](https://www.amitmerchant.com/introducing-consolepad/) [**Next:** The attr() function in CSS now supports types](https://www.amitmerchant.com/attr-function-types-css/)

[![PHP 8 in a Nutshell book cover](https://www.amitmerchant.com/images/php-8-in-a-nutshell-large-banner.png)](https://amitmerchant.gumroad.com/l/php8-in-a-nutshell "A no-fluff guide to PHP 8")

[![PHP 8 in a Nutshell book cover](https://www.amitmerchant.com/images/php8-in-a-nutshell-cover.jpg)](https://amitmerchant.gumroad.com/l/php8-in-a-nutshell "A no-fluff guide to PHP 8")

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](https://amitmerchant.gumroad.com/l/php8-in-a-nutshell "A no-fluff guide to PHP 8").
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.


[Grab your copy now!](https://amitmerchant.gumroad.com/l/php8-in-a-nutshell)[Read a sample](https://www.amitmerchant.com/php-8-in-a-nutshell/sample.pdf)

» Share: [Twitter](https://twitter.com/share?text=The+new+withAttributes+method+for+relationships+and+scopes+in+Laravel%20by%20@amit_merchant&url=https://www.amitmerchant.com/with-attributes-scopes-laravel/),
[Facebook](https://www.facebook.com/sharer.php?u=https://www.amitmerchant.com/with-attributes-scopes-laravel/),
[Hacker News](https://news.ycombinator.com/submitlink?u=https://www.amitmerchant.com/with-attributes-scopes-laravel/&t=The%20new%20withAttributes%20method%20for%20relationships%20and%20scopes%20in%20Laravel)

Like this article?

[Buy me a coffee](https://buymeacoffee.com/amitmerchant)

[![Caricature of Amit Merchant sketched by a friend](https://www.amitmerchant.com/images/caricature.jpg)](https://twitter.com/amit_merchant "Follow me on Twitter")

👋 Hi there! I'm [Amit](https://twitter.com/amit_merchant). 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.


[Become a Sponsor](https://www.amitmerchant.com/become-a-sponsor "Support me via Paypal") [Join my newsletter](https://amitmerchant.substack.com/ "Join my newsletter")

## Comments?

utterances

# 0 Comments _\- powered by_ _[utteranc.es](https://utteranc.es/)_

![@anonymous](<Base64-Image-Removed>)

Nothing to preview


[The new withAttributes method for relationships and scopes in Laravel](https://www.amitmerchant.com/with-attributes-scopes-laravel/)

[Some open-source and free Laravel SaaS Starter Kits](https://www.amitmerchant.com/open-source-laravel-saas-starter-kits/)

[Using Laravel Tinker in Chrome DevTools](https://www.amitmerchant.com/laravel-tinker-chrome-devtools/)

[Manually setting the intended URL for routes in Laravel](https://www.amitmerchant.com/manually-setting-the-intended-url-for-routes-in-laravel/)