Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Mikejs's avatar

trying to display tasks based on user role

I have a todo blade to display tasks from the todos table, the todos table has a filed use_id, i want to display all tasks to isAdmin and only the users to task to the user based on the user id and todos user_id In my appsController I have added

     public function todo()
{

    // Get the currently authenticated user
    $user = Auth::user();

    // Check if the user is an admin or super admin
    if ($user->isAdmin()) {
        // Allow access for admins and super admins
        return $next($request);
    }

    // For regular users, check if they are trying to access their own todo
    $todoId = $request->route('id');
    $todo = Todo::findOrFail($todoId);

    if ($todo->user_id === $user->id) {
        // Allow access if the todo belongs to the user
        return $next($request);
    }

    // Deny access for all other cases
    return abort(403, 'Unauthorized');

and in my user model I have

   /**
 * Local scope to exclude auth user
 * @param $query
 * @return mixed
 */
public function scopeWithoutAuthUser($query): mixed
{
    return $query->where('id', '!=', auth()->id());
}

/**
 * Local scope to exclude super admin
 * @param $query
 * @return mixed
 */
public function scopeWithoutSuperAdmin($query): mixed
{
    return $query->where('id', '!=', 1);
}

public function isAdmin(): bool
{
    $roles = $this->getRoleNames(); // Assuming you are using Spatie's laravel-permission
    \Illuminate\Support\Facades\Log::info('User roles: ' . json_encode($roles));
    return $this->hasRole(['admin', 'super_admin']);
}
0 likes
1 reply
s4muel's avatar

in your Controller

public function todo() {
    $tasks = Todo::visibleToCurrentUser()->get();

    dd($tasks->toArray());
}

in Todo Model class

public function scopevisibleToCurrentUser($query)
{
    if(auth()->user()->isAdmin()) {
        return $query->where('user_id', auth()->id());
    }

    return $query;
}

keep the isAdmin() method in the User model. not sure where do you use those two scopes (scopeWithoutAuthUser and scopeWithoutSuperAdmin) in User model (from example above) - those are unrelated here.

oh, and that that $next thing on your todo() seems to be from some Middleware example, which is unrelated in this case

Please or to participate in this conversation.