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']);
}