Courses

[NEW] Roles and Permissions in Laravel 11

Finally, we get to the actual point of this small application: Task management.

Compared to the Task Model in previous lessons of this course, we added a few more fields: assigned_to_user_id (clinic doctor/staff) and patient_id:

Tasks Migration:

$table->foreignId('assigned_to_user_id')->constrained('users');
$table->foreignId('patient_id')->constrained('users');

Then, I added them to the Model, too:

app/Models/Task.php

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Factories\HasFactory;
 
class Task extends Model
{
use HasFactory;
 
protected $fillable = [
'name',
'due_date',
'assigned_to_user_id',
'patient_id',
'team_id',
];
 
public function assignee(): BelongsTo
{
return $this->belongsTo(User::class, 'assigned_to_user_id');
}
 
public function patient(): BelongsTo
{
return $this->belongsTo(User::class, 'patient_id');
}
}

Then, we also changed the Factory with the new columns in mind.

database/factories/TaskFactory.php

use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
 
class TaskFactory extends Factory
{
public function definition(): array
{
$randomAssignee = collect([
User::factory()->doctor(),
User::factory()->staff(),
])->random();
 
return [
'name' => fake()->text(30),
'due_date' => now()->addDays(rand(1, 100)),
'assigned_to_user_id' => $randomAssignee,
'patient_id' => User::factory()->patient(),
];
}
}

Now, who can manage tasks? Traditionally, let's start with Policy:

app/Policies/TaskPolicy.php

use App\Enums\Role;
use App\Models\Task;
use App\Models\User;
use App\Enums\Permission;
 
class TaskPolicy
{
public function viewAny(User $user): bool
{
return $user->hasPermissionTo(Permission::LIST_TASK);
}
 
public function create(User $user): bool
{
return $user->hasPermissionTo(Permission::CREATE_TASK);
}
 
public function update(User $user, Task $task): bool
{
return $user->hasPermissionTo(Permission::EDIT_TASK);
}
 
public function delete(User $user, Task $task): bool
{
return $user->hasPermissionTo(Permission::DELETE_TASK);
}
}

You don't see the filter by team here, right? The approach we took here is to filter them on the Eloquent level, with global scope.

In fact, it's a 2-in-1 scope...

This lesson is only for Premium Members.
Want to access all lessons of this course?

You also get:

  • 64 courses (1141 lessons, 42 h 01 min total)
  • Premium tutorials
  • Access to repositories
  • Private Discord