Thắc mắc trong việc dùng Scope Local

Mình đang học Laravel, có thắc mắc 1 điểm như sau khi dùng Scope Local:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Scope a query to only include popular users.
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopePopular($query)
    {
        return $query->where('votes', '>', 100);
    }

    /**
     * Scope a query to only include active users.
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeActive($query)
    {
        return $query->where('active', 1);
    }
}

Dùng Scope để truy vấn:

$users = App\User::popular()->active()->orderBy('created_at')->get();

Cho mình hỏi tại sao ở method scopePopular() có parameter $query mà khi truy vấn ở dưới thì lại không có ?

Mình cám ơn.


Tại sao đặt tên method là public function scopePopular($query) mà ko phải là public static function popular() ?
Bạn tìm hiểu về magic methods, __callStatic(), __call(), … nói chung là nghiên cứu hết sẽ thấy công dụng của nó.

1 Like

Cám ơn bạn rất nhiều, mình hiểu rồi :smile:

83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?