UserResource Auth Null At Query Result For Unauthenticated User Request

I am working on a Laravel 11 API project with Nuxt front end. And also we are using Passport for authentication and authorization. I am having trouble with Users. So let’s say there are just 2 users like below :

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>[
[
'first_name' => 'John',
'last_name' => 'Doe',
'email' => '[email protected]',
'country_id' => 1,
'phone' => '1112222222',
'isAdmin' => true,
'password' => Hash::make(Str::password(32, true, true, true, false))
],
[
'first_name' => 'Bob',
'last_name' => 'Carlo',
'email' => '[email protected]',
'country_id' => 1,
'phone' => '111111111',
'isAdmin' => true,
'password' => Hash::make(Str::password(32, true, true, true, false)),
'email_send_at' => null,
'phone_send_at' => null
],
];
</code>
<code>[ [ 'first_name' => 'John', 'last_name' => 'Doe', 'email' => '[email protected]', 'country_id' => 1, 'phone' => '1112222222', 'isAdmin' => true, 'password' => Hash::make(Str::password(32, true, true, true, false)) ], [ 'first_name' => 'Bob', 'last_name' => 'Carlo', 'email' => '[email protected]', 'country_id' => 1, 'phone' => '111111111', 'isAdmin' => true, 'password' => Hash::make(Str::password(32, true, true, true, false)), 'email_send_at' => null, 'phone_send_at' => null ], ]; </code>
[
            [
                'first_name'    => 'John',
                'last_name'     => 'Doe',
                'email'         => '[email protected]',
                'country_id'    => 1,
                'phone'         => '1112222222',
                'isAdmin'       => true,
                'password'      => Hash::make(Str::password(32, true, true, true, false))
            ],
            [
                'first_name'    => 'Bob',
                'last_name'     => 'Carlo',
                'email'         => '[email protected]',
                'country_id'    => 1,
                'phone'         => '111111111',
                'isAdmin'       => true,
                'password'      => Hash::make(Str::password(32, true, true, true, false)),
                'email_send_at' => null,
                'phone_send_at' => null
            ],
        ];

Let’s say I am authenticated as Bob. I saved the Bearer token to Postman. And then lets say if i send a GET request to filter Users with lets say their full name with “Bob” query string I get the correct result which is just second user. And then let’s say i send another GET request with just “o” and both of them is returned which is also correct. But if a send a request with just “J” or any query string value that will return the other user i am not getting the result i wanted. Auth fails. It’s not just for FullName. Same problem exist for other fields. Lets say if i send a request with phone query string. if i send “1” the result must be both of them and it is. But if i send “2” it just not works as i wanted.

Firstly here is api.php routes :

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>// User Routes - Start
Route::prefix('user')->group(function ()
Route::group([
"middleware" => ["auth:api"]
], function () {
Route::post('/', [UserController::class, 'store'])->middleware('can:publish user');
Route::put('/{user}', [UserController::class, 'update'])->middleware('can:update user');
Route::delete('/{user}', [UserController::class, 'destroy'])->middleware('can:destroy user');
Route::delete('/', [UserController::class, 'destroyMultiple'])->middleware('can:destroy user');
});
Route::group([
"middleware" => ["client"]
], function () {
Route::get('/', [UserController::class, 'index']);
Route::get('/{user}', [UserController::class, 'show']);
});
});
// User Routes - End
</code>
<code>// User Routes - Start Route::prefix('user')->group(function () Route::group([ "middleware" => ["auth:api"] ], function () { Route::post('/', [UserController::class, 'store'])->middleware('can:publish user'); Route::put('/{user}', [UserController::class, 'update'])->middleware('can:update user'); Route::delete('/{user}', [UserController::class, 'destroy'])->middleware('can:destroy user'); Route::delete('/', [UserController::class, 'destroyMultiple'])->middleware('can:destroy user'); }); Route::group([ "middleware" => ["client"] ], function () { Route::get('/', [UserController::class, 'index']); Route::get('/{user}', [UserController::class, 'show']); }); }); // User Routes - End </code>
// User Routes - Start
Route::prefix('user')->group(function ()
    Route::group([
       "middleware" => ["auth:api"]
        ], function () {
            Route::post('/', [UserController::class, 'store'])->middleware('can:publish user');
            Route::put('/{user}', [UserController::class, 'update'])->middleware('can:update user');
            Route::delete('/{user}', [UserController::class, 'destroy'])->middleware('can:destroy user');
            Route::delete('/', [UserController::class, 'destroyMultiple'])->middleware('can:destroy user');
        });

        Route::group([
            "middleware" => ["client"]
        ], function () {
            Route::get('/', [UserController::class, 'index']);
            Route::get('/{user}', [UserController::class, 'show']);
        });

    });
    // User Routes - End

We are using Global Scope to apply search and filters to models. Here is User model :

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class User extends Authenticatable
{
use HasFactory, Notifiable, HasRoles, HasApiTokens;
protected static function boot()
{
parent::boot();
static::addGlobalScope(new FilterBy('AppServicesV1UserUserFilters', request()->all()));
}
//......
</code>
<code>class User extends Authenticatable { use HasFactory, Notifiable, HasRoles, HasApiTokens; protected static function boot() { parent::boot(); static::addGlobalScope(new FilterBy('AppServicesV1UserUserFilters', request()->all())); } //...... </code>
class User extends Authenticatable
{
    use HasFactory, Notifiable, HasRoles, HasApiTokens;

    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope(new FilterBy('AppServicesV1UserUserFilters', request()->all()));
    }

//......

Here is FilterBy Scope :

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class FilterBy implements Scope
{
protected $namespace;
protected $filters;
public function __construct($namespace, $filters)
{
$this->namespace = $namespace;
$this->filters = $filters;
}
/**
* Apply the scope to a given Eloquent query builder.
*/
public function apply(Builder $builder, Model $model): void
{
if (request()->method() !== 'GET' || empty($this->filters)) {
return;
}
$filter = new FilterBuilder($builder, $this->filters, $this->namespace);
$builder = $filter->apply();
}
}
</code>
<code>class FilterBy implements Scope { protected $namespace; protected $filters; public function __construct($namespace, $filters) { $this->namespace = $namespace; $this->filters = $filters; } /** * Apply the scope to a given Eloquent query builder. */ public function apply(Builder $builder, Model $model): void { if (request()->method() !== 'GET' || empty($this->filters)) { return; } $filter = new FilterBuilder($builder, $this->filters, $this->namespace); $builder = $filter->apply(); } } </code>
class FilterBy implements Scope
{

    protected $namespace;
    protected $filters;

    public function __construct($namespace, $filters)
    {
        $this->namespace = $namespace;
        $this->filters = $filters;
    }
    /**
     * Apply the scope to a given Eloquent query builder.
     */
    public function apply(Builder $builder, Model $model): void
    {
        if (request()->method() !== 'GET' || empty($this->filters)) {
            return;
        }

        $filter = new FilterBuilder($builder, $this->filters, $this->namespace);
        $builder = $filter->apply();
    }
}

And also FilterBuilder class :

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class FilterBy implements Scope
{
protected $namespace;
protected $filters;
public function __construct($namespace, $filters)
{
$this->namespace = $namespace;
$this->filters = $filters;
}
/**
* Apply the scope to a given Eloquent query builder.
*/
public function apply(Builder $builder, Model $model): void
{
if (request()->method() !== 'GET' || empty($this->filters)) {
return;
}
$filter = new FilterBuilder($builder, $this->filters, $this->namespace);
$builder = $filter->apply();
}
}
</code>
<code>class FilterBy implements Scope { protected $namespace; protected $filters; public function __construct($namespace, $filters) { $this->namespace = $namespace; $this->filters = $filters; } /** * Apply the scope to a given Eloquent query builder. */ public function apply(Builder $builder, Model $model): void { if (request()->method() !== 'GET' || empty($this->filters)) { return; } $filter = new FilterBuilder($builder, $this->filters, $this->namespace); $builder = $filter->apply(); } } </code>
class FilterBy implements Scope
{

    protected $namespace;
    protected $filters;

    public function __construct($namespace, $filters)
    {
        $this->namespace = $namespace;
        $this->filters = $filters;
    }
    /**
     * Apply the scope to a given Eloquent query builder.
     */
    public function apply(Builder $builder, Model $model): void
    {
        if (request()->method() !== 'GET' || empty($this->filters)) {
            return;
        }

        $filter = new FilterBuilder($builder, $this->filters, $this->namespace);
        $builder = $filter->apply();
    }
}

So basically I have a User directory with the classes that are actually adding filters to query. For example here is FullName.php :

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class FullName extends QueryFilter implements FilterContract
{
protected $query;
public function __construct($query)
{
$this->query = $query;
}
public function handle($value = ""): void
{
$this->query->where(DB::raw("CONCAT(first_name, ' ', last_name)"), 'ilike', '%' . $value . '%');
}
}
</code>
<code>class FullName extends QueryFilter implements FilterContract { protected $query; public function __construct($query) { $this->query = $query; } public function handle($value = ""): void { $this->query->where(DB::raw("CONCAT(first_name, ' ', last_name)"), 'ilike', '%' . $value . '%'); } } </code>
class FullName extends QueryFilter implements FilterContract
{
    protected $query;

    public function __construct($query)
    {
        $this->query = $query;
    }

    public function handle($value = ""): void
    {
        $this->query->where(DB::raw("CONCAT(first_name, ' ', last_name)"), 'ilike', '%' . $value . '%');
    }
}

Here is Controller method :

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>public function index(Request $request)
{
return new UserCollection(User::paginate($request->get('perPage', 15)));
}
</code>
<code>public function index(Request $request) { return new UserCollection(User::paginate($request->get('perPage', 15))); } </code>
public function index(Request $request)
    {
        return new UserCollection(User::paginate($request->get('perPage', 15)));
    }

Also here is the UserCollection and UserResource :

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class UserCollection extends ResourceCollection
{
public function __construct($resource)
{
parent::__construct($resource);
$this->preserveAllQueryParameters = true;
}
public function toArray(Request $request): array
{
return parent::toArray($request);
}
}
</code>
<code>class UserCollection extends ResourceCollection { public function __construct($resource) { parent::__construct($resource); $this->preserveAllQueryParameters = true; } public function toArray(Request $request): array { return parent::toArray($request); } } </code>
class UserCollection extends ResourceCollection
{
    public function __construct($resource)
    {
        parent::__construct($resource);

        $this->preserveAllQueryParameters = true;
    }

    public function toArray(Request $request): array
    {
        return parent::toArray($request);
    }
}
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class UserResource extends JsonResource
{
public function toArray(Request $request): array
{
if (Auth::check() && Auth::user()->isAdmin && Auth::user()->can('show user')) {
return [
'id' => $this->id,
'first_name' => $this->first_name,
'last_name' => $this->last_name,
'email' => $this->email,
'country_id' => $this->country_id,
'phone' => $this->phone,
'isAdmin' => $this->isAdmin,
];
}
return [
'first_name' => $this->first_name,
'last_name' => $this->last_name,
'country_id' => $this->country_id,
];
}
}
</code>
<code>class UserResource extends JsonResource { public function toArray(Request $request): array { if (Auth::check() && Auth::user()->isAdmin && Auth::user()->can('show user')) { return [ 'id' => $this->id, 'first_name' => $this->first_name, 'last_name' => $this->last_name, 'email' => $this->email, 'country_id' => $this->country_id, 'phone' => $this->phone, 'isAdmin' => $this->isAdmin, ]; } return [ 'first_name' => $this->first_name, 'last_name' => $this->last_name, 'country_id' => $this->country_id, ]; } } </code>
class UserResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        if (Auth::check() && Auth::user()->isAdmin && Auth::user()->can('show user')) {
            return [
                'id' => $this->id,
                'first_name' => $this->first_name,
                'last_name' => $this->last_name,
                'email' => $this->email,
                'country_id' => $this->country_id,
                'phone' => $this->phone,
                'isAdmin' => $this->isAdmin,
            ];
        }

        return [
            'first_name' => $this->first_name,
            'last_name' => $this->last_name,
            'country_id' => $this->country_id,
        ];
    }
}

So as i mentioned if i send a request with query string that will return JUST one user which is not currently authenticated user it returns with just first name, last name and country id. I used dd(Auth::user()) at UserController index method. If i send a request that will cause the problem i mentioned it is ‘null’ if i send a request that will return both users it is not null.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật