Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-mini-2024-07-18· OpenAIAi2 WildChat-4.8M (AI2)

Hãy cho tôi biết thông tin về từ khóa "withAttributes" trong tài liệu The new…

  1. User

    Hãy cho tôi biết thông tin về từ khóa "withAttributes" trong tài liệu

    The new withAttributes method for relationships and scopes in Laravel

    February 16, 2025 ·Laravel

    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.

    <?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 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 Next: The attr() function in CSS now supports types

    [image: PHP 8 in a Nutshell book cover] open

    [image: PHP 8 in a Nutshell book cover] open

    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.

    Grab your copy now!Read a sample

    » Share: Twitter, Facebook, Hacker News

    Like this article?

    Buy me a coffee

    [image: Caricature of Amit Merchant sketched by a friend] open

    👋 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.

    Become a Sponsor Join my newsletter

    Comments?

    utterances

    0 Comments - powered by utteranc.es

    [image: @anonymous]

    Nothing to preview

    The new withAttributes method for relationships and scopes in Laravel

    Some open-source and free Laravel SaaS Starter Kits

    Using Laravel Tinker in Chrome DevTools

    Manually setting the intended URL for routes in Laravel.

  2. Assistant

    Phương thức withAttributes mới trong Laravel là một tính năng mạnh mẽ giúp bạn dễ dàng áp dụng các điều kiện vào truy vấn cũng như các mối quan hệ và các phạm vi của mô hình. Dưới đây là một số thông tin chi tiết về phương thức này:

    Giới thiệu về withAttributes

    • withAttributes cho phép thêm một điều kiện where vào truy vấn với các ràng buộc thuộc tính cụ thể. Điều đặc biệt là nó không chỉ áp dụng cho truy vấn hiện tại mà còn tự động áp dụng cho bất kỳ mô hình nào được tạo thông qua mối quan hệ hoặc phạm vi đó.

    Cách sử dụng withAttributes trong phạm vi

    Khi tạo phạm vi (scope) trong mô hình, bạn có thể sử dụng withAttributes để thêm điều kiện ngay lập tức. Ví dụ:

    public function scopeFeatured($query)
    {
        return $query->withAttributes(['featured' => true]);
    }
    

    Với phạm vi này, khi bạn thực hiện truy vấn hoặc tạo một mô hình mới, thuộc tính featured sẽ tự động được thiết lập thành true.

    Cách sử dụng withAttributes trong các mối quan hệ

    withAttributes cũng có thể được sử dụng trong các mối quan hệ để xác định các mô hình liên quan:

    public function featuredPosts()
    {
        return $this->posts()->withAttributes(['featured' => true]);
    }
    

    Điều này cho phép bạn lấy tất cả các bài đăng được đánh dấu là "nổi bật" cho một người dùng nhất định.

    Ví dụ hoàn chỉnh

    Dưới đây là ví dụ hoàn chỉnh về cách sử dụng withAttributes:

    use App\User;
    
    $user = User::find(1);
    
    // Lấy tất cả các bài đăng nổi bật
    $posts = $user->featuredPosts()->get();
    
    // Tạo một bài đăng mới với thuộc tính `featured` được thiết lập là `true`
    $post = $user->featuredPosts()->create([
        'title' => 'My featured post'
    ]);
    
    $post->featured; // true
    

    Kết luận

    Tính năng withAttributes đơn giản hóa quy trình làm việc với Eloquent ORM của Laravel. Nó kết hợp một cách tiện lợi giữa việc truy vấn và tạo mô hình, giúp mã nguồn ngắn gọn hơn và dễ bảo trì hơn. Đây là một bổ sung hữu ích cho Laravel, mang lại sự linh hoạt và sức mạnh cho các nhà phát triển trong việc làm việc với dữ liệu.