How to Override the Default Guard in Laravel Using config()

Hòa Nguyễn Coder

Published in Web Developer · Đã đăng vào tháng 2 10, 2025 5:10 PM

Đây là cách chúng ta có thể ghi đề Guard trong Laravel, thông thường chúng ta hay viết Laravel Permission  và config auth cho guard ="web". Vậy khi chúng ta sử dụng API để request , sau đó check permission, nó sẽ báo lỗi ,vì mặt định ta đang dùng guard = "web".  Mà trong khi request API thì Guard nó nhận là Guard = "api".  Gặp lỗi này là do chúng ta có 2 phương thức đăng nhập khác nhau: (1 auth từ form & auth từ api jwt). 


 'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],


    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'jwt',
            'provider' => 'users',
        ],
    ],

Okay chúng ta cứ việc ghi đè nó thôi

Khi bạn Auth bằng API, nó nhận Guard "api", gây ảnh hưởng đến vấn đề check permission  , nên ta có thể ghi đề nó từ Guard "api" về Guard "web"


<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Repositories\Interfaces\PostRepositoryInterface;
use App\Http\Resources\PostCollection;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Facades\JWTAuth;
class PostController extends Controller
{
    public $postRepo;
    public function __construct(
         PostRepositoryInterface $postRepo)
    {

       // $this->middleware('auth:api');
        $this->postRepo = $postRepo;
    }
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        // Ghi đề guard 'api' thay với 'web', để check Laravel Permission
        config(['auth.defaults.guard' => 'web']);

        // Lấy user hiện tại từ guard 'api'
        $user = Auth::guard('api')->user();

        if (!$user || !$user->can('admin.posts.index')) {
            return response()->json(['message' => 'Unauthorized'], 401);
        }

        $posts = $this->postRepo->getAll();
        return new PostCollection($posts);
    }
}

Trong đoạn code trên các bạn để ý là mình sử dụng config để ghi đè :


// Ghi đề guard 'api' thay với 'web', để check Laravel Permission
config(['auth.defaults.guard' => 'web']);

Sẽ có các cách khác để xử lý, nhưng đầy là cách mẹo nhỏ, ae có thể thử nha

Nếu bạn thấy đem lại kiến thức bổ ích, hãy Click xem quảng cáo trên trang website của mình nhé! 🚀