Laravel Jetstream: Add CRUD with Spatie Permission

Tutorials

May 6th, 2022

Laravel Jetstream: Add CRUD with Spatie Permission

Laravel Jetstream is a starter kit that helps you not only with Auth scaffolding but with extra functionality like Teams or Two-Factor Authentication. But I see many people struggle with customizing Jetstream after installation, and with adding more functionality. So, in this article, let's add a simple CRUD with roles/permissions, on top of Jetstream.

Jetstream Installation

We will create a fresh Laravel project to manage a to-do list of tasks. There are multiple ways to install Laravel + Jetstream, I will use the Laravel installer.

You could do:

1laravel new project
2cd project
3composer require laravel/jetstream
4php artisan jetstream:install livewire

Notice: Jetstream comes with two options - Livewire and Inertia. In this article, I will use the Livewire stack, but it doesn't matter. Livewire/Inertia is used for scaffolding code, but after installing Jetstream, you could proceed with writing code without any of those extra tools, with pure Laravel + Blade MVC code.

So, the installation instructions are above, but here I will give you a tip for a shorter installation. Laravel installer allows you to do it all in just one command:

1laravel new project --jet --stack=livewire

After the scaffolding is done, we need to run these:

1cd project
2php artisan migrate
3npm install && npm run dev

If everything is successful, we should see the default homepage, with Login/Register links on the top-right.

When you click Register, you should land on the registration form.

After it's filled, the user is registered and lands on the dashboard.

If you see the same on your screen, congratulations, the installation part is completed successfully.


Tasks List: DB Structure and non-Jetstream Part

Next, we need to create the back-end structure for our DB table of tasks. Here's where we will get away from Jetstream at all, for a while. And that's one of the main things that developers should understand about Jetstream: you don't rely on the starter kit for your further code. You can write code as you would usually do without Jetstream, maybe just reusing some of its components.

So, what we need to do at this point:

  • Create a Task model
  • Create DB migrations
  • Create a Resource TaskController and fill CRUD operations
  • Add a Route to that new Controller
  • Create Form Request classes for validation

These are the actions needed irrelevant to the starter kit, whether it's Jetstream, Breeze, or any other.

Then, what we do need to incorporate in Jetstream, are these actions:

  • Add the "Tasks" menu item to Jetstream navigation
  • Create Blade Views for CRUD operations

So, these two things will depend on Jestream's front-end structure, we'll take a look at that below.

First, the non-Jestream part:

1php artisan make:model Task -mcrR

Those additional flags will generate related files:

  • -m will generate a migration class
  • -cr will generate a Controller with Resource methods: index, create, store, show, edit, update, destroy
  • -R will generate two Form Request classes: StoreTaskRequest and UpdateTaskRequest

Next, we fill in the migration with only one field, for this simple example.

database/migrations/2022_04_19_131435_create_tasks_table.php:

1return new class extends Migration
2{
3 public function up()
4 {
5 Schema::create('tasks', function (Blueprint $table) {
6 $table->id();
7 $table->string('name');
8 $table->timestamps();
9 });
10 }

I deliberately don't show the down() method, cause I don't create that method since 2017, when Taylor Otwell approved it.

Let's also run php artisan migrate, so this table would be created.

Then, in Model, I add one fillable field:

app/Models/Task.php

1class Task extends Model
2{
3 protected $fillable = ['name'];
4}

Then, the CRUD code for the Controller.

app/Http/Controllers/TaskController.php:

1use App\Http\Requests\StoreTaskRequest;
2use App\Http\Requests\UpdateTaskRequest;
3use App\Models\Task;
4 
5class TaskController extends Controller
6{
7 public function index()
8 {
9 $tasks = Task::all();
10 
11 return view('tasks.index', compact('tasks'));
12 }
13 
14 public function create()
15 {
16 return view('tasks.create');
17 }
18 
19 public function store(StoreTaskRequest $request)
20 {
21 Task::create($request->validated());
22 
23 return redirect()->route('tasks.index');
24 }
25 
26 public function edit(Task $task)
27 {
28 return view('tasks.edit', compact('task'));
29 }
30 
31 public function update(UpdateTaskRequest $request, Task $task)
32 {
33 $task->update($request->validated());
34 
35 return redirect()->route('tasks.index');
36 }
37 
38 public function destroy(Task $task)
39 {
40 $task->delete();
41 
42 return redirect()->route('tasks.index');
43 }
44}

Finally, we assign that controller to the route, with auth middleware.

routes/web.php:

1Route::get('/', function () {
2 return view('welcome');
3});
4 
5Route::middleware([
6 'auth:sanctum',
7 config('jetstream.auth_session'),
8 'verified'
9])->group(function () {
10 Route::get('/dashboard', function () {
11 return view('dashboard');
12 })->name('dashboard');
13 
14 // This is our new line
15 Route::resource('tasks', \App\Http\Controllers\TaskController::class);
16});

This is the first time we see something from Jetstream: the generated dashboard route with default middlewares like auth:sanctum and others. Our task here is just to add our route to that group.


Tasks List: New Page with Jetstream Layout

Ok, so we have a Controller but we don't have a View, yet. We specified it to be resources/views/tasks/index.blade.php, so let's create that exact file.

If you want it to have the same Jetstream design, you can use the existing Dashboard file and just replace the internal part of it.

resources/views/dashboard.blade.php:

1<x-app-layout>
2 <x-slot name="header">
3 <h2 class="font-semibold text-xl text-gray-800 leading-tight">
4 {{ __('Dashboard') }}
5 </h2>
6 </x-slot>
7 
8 <div class="py-12">
9 <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
10 <div class="bg-white overflow-hidden shadow-xl sm:rounded-lg">
11 <x-jet-welcome />
12 </div>
13 </div>
14 </div>
15</x-app-layout>

So, we do File -> Save as... in our IDE, and put it as resources/views/tasks/index.blade.php, then replace the header with "Tasks list" and <x-jet-welcome /> with just a static text "Coming soon", for now.

resources/views/tasks/index.blade.php:

1<x-app-layout>
2 <x-slot name="header">
3 <h2 class="font-semibold text-xl text-gray-800 leading-tight">
4 {{ __('Tasks list') }}
5 </h2>
6 </x-slot>
7 
8 <div class="py-12">
9 <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
10 <div class="bg-white overflow-hidden shadow-xl sm:rounded-lg">
11 Coming soon.
12 </div>
13 </div>
14 </div>
15</x-app-layout>

Now, if we launch the /tasks URL in the browser, this is what we should see:

If you are not familiar with the syntax like x-app-layout or x-slot, read about layouts using Blade components.

If you are not familiar with the __() method, read about translations in Laravel.

Finally, we add the menu on top, in two places, with Jetstream components x-jet-nav-link and x-jet-responsive-nav-link. We just copy-paste the Dashboard link and change the text/routes.

resources/views/navigation-menu.blade.php:

1<x-jet-nav-link href="{{ route('dashboard') }}" :active="request()->routeIs('dashboard')">
2 {{ __('Dashboard') }}
3</x-jet-nav-link>
4<x-jet-nav-link href="{{ route('tasks.index') }}" :active="request()->routeIs('tasks.*')">
5 {{ __('Tasks') }}
6</x-jet-nav-link>
7 
8<x-jet-responsive-nav-link href="{{ route('dashboard') }}" :active="request()->routeIs('dashboard')">
9 {{ __('Dashboard') }}
10</x-jet-responsive-nav-link>
11<x-jet-responsive-nav-link href="{{ route('tasks.index') }}" :active="request()->routeIs('tasks.*')">
12 {{ __('Tasks') }}
13</x-jet-responsive-nav-link>

Tasks List: Jetstream Table with Tailwind CSS

Now, let's replace our "Coming soon" text with the actual table.

Laravel Jetstream visual design is based on Tailwind CSS framework, so we should continue using it for other custom pages we would create.

There are various sources where you can get a component for a Tailwind-based table, I've chosen a free version of Flowbite here. So I will copy-paste the code from there and fill in the details with the @forelse loop of the tasks list.

resources/views/tasks/index.blade.php:

1<x-app-layout>
2 <x-slot name="header">
3 <h2 class="font-semibold text-xl text-gray-800 leading-tight">
4 {{ __('Tasks list') }}
5 </h2>
6 </x-slot>
7 
8 <div class="py-12">
9 <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
10 <div class="bg-white overflow-hidden shadow-xl sm:rounded-lg">
11 <div class="relative overflow-x-auto shadow-md sm:rounded-lg">
12 <table class="w-full text-sm text-left text-gray-500 dark:text-gray-400">
13 <thead class="text-xs text-gray-700 uppercase bg-gray-50 dark:bg-gray-700 dark:text-gray-400">
14 <tr>
15 <th scope="col" class="px-6 py-3">
16 Task name
17 </th>
18 <th scope="col" class="px-6 py-3">
19 
20 </th>
21 </tr>
22 </thead>
23 <tbody>
24 @forelse ($tasks as $task)
25 <tr class="bg-white border-b dark:bg-gray-800 dark:border-gray-700">
26 <td class="px-6 py-4 font-medium text-gray-900 dark:text-white whitespace-nowrap">
27 {{ $task->name }}
28 </td>
29 <td class="px-6 py-4">
30 <a href="{{ route('tasks.edit', $task) }}"
31 class="font-medium text-blue-600 dark:text-blue-500 hover:underline">Edit</a>
32 </td>
33 </tr>
34 @empty
35 <tr class="bg-white border-b dark:bg-gray-800 dark:border-gray-700">
36 <td colspan="2"
37 class="px-6 py-4 font-medium text-gray-900 dark:text-white whitespace-nowrap">
38 {{ __('No tasks found') }}
39 </td>
40 </tr>
41 @endforelse
42 </tbody>
43 </table>
44 </div>
45 </div>
46 </div>
47 </div>
48</x-app-layout>

If I create some random tasks manually in the database, it should look like this:


Full CRUD: Buttons and Forms

Above the table, let's place a button to add a new record. Jetstream has a set of Blade components for various UI elements, including buttons. To publish them, we need to run:

1php artisan vendor:publish --tag=jetstream-views

Then, we will have a lot of elements inside of resources/views/vendor/jetstream/components, and they are automatically enabled via service providers of Jetstream.

If we open resources/views/vendor/jetstream/components/button.blade.php, we see this:

1<button {{ $attributes->merge(['type' => 'submit', 'class' => 'inline-flex items-center ...']) }}>
2 {{ $slot }}
3</button>

A lot of other Tailwind classes are listed after items-center, and this is exactly what we need, but just in the form of a link, not a button. So I just copy-paste all those classes into the new component I will create:

resources/views/components/link.blade.php:

1<a {{ $attributes->merge(['class' => 'inline-flex items-center ...']) }}>
2 {{ $slot }}
3</a>

Then, in the resources/views/tasks/index.blade we can do this:

1<div class="relative ...">
2 <x-link href="{{ route('tasks.create') }}" class="m-4">Add new task</x-link>
3 
4 <table class="...">

So, we've added <x-link> with styling it as a button, adding the m-4 class for a margin.

Notice that you need to run npm run dev again, or have npm run watch in the background, so Tailwind would re-compile all the classes that are used in Blade files, like m-4 in our case.

This is the visual result:

When we click that link, we land on the URL /tasks/create, which corresponds to the Controller method TaskController@create and loads the view of tasks/create.blade.php.

For that form, I will re-use the HTML code and classes from the registration page in Jetstream, which is in resources/views/auth/register.blade.php. After some copy-pasting, here's our new form in the newly created file.

resources/views/tasks/create.blade.php:

1<x-app-layout>
2 <x-slot name="header">
3 <h2 class="font-semibold text-xl text-gray-800 leading-tight">
4 {{ __('Add New Task') }}
5 </h2>
6 </x-slot>
7 
8 <div class="py-12">
9 <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
10 <div class="bg-white overflow-hidden shadow-xl sm:rounded-lg">
11 <div class="relative overflow-x-auto shadow-md sm:rounded-lg px-4 py-4">
12 <x-jet-validation-errors class="mb-4" />
13 
14 <form method="POST" action="{{ route('tasks.store') }}">
15 @csrf
16 
17 <div>
18 <x-jet-label for="name" value="{{ __('Name') }}" />
19 <x-jet-input id="name" class="block mt-1 w-full" type="text" name="name" :value="old('name')" required autofocus autocomplete="name" />
20 </div>
21 
22 <div class="flex mt-4">
23 <x-jet-button>
24 {{ __('Save Task') }}
25 </x-jet-button>
26 </div>
27 </div>
28 </div>
29 </div>
30 </div>
31</x-app-layout>

As you can see, we use the same layout, and just added a few px-4 py-4 CSS classes for the padding.

Also, important to notice two Jetstream components:

  • x-jet-validation-errors will list all the form validation errors from the session
  • x-jet-button is the same submit button that you have seen before, as an "inspiration" for our x-link component

The visual result is this:

Saving data should work because we've created the Controller code for this, remember? Just one more thing we need to add there is the validation rule.

app/Http/Requests/StoreTaskRequest.php:

1class StoreTaskRequest extends FormRequest
2{
3 public function authorize()
4 {
5 // default is "false", we need to change to "true"
6 return true;
7 }
8 
9 public function rules()
10 {
11 return [
12 'name' => 'required'
13 ];
14 }
15}

We also generated the Form Request class for the update form, so in app/Http/Requests/UpdateTaskRequest.php we need to add the same code for the authorize() and rules() methods there. It's debatable whether to use separate Form Request classes, especially if the rules are the same, but my personal preference is to avoid the same class because you never know when the rules would start to differ.

Now, the Edit form is almost identical to the Create form. So, we can open the create.blade.php, do File -> Save as... and save it with minimal changes:

resources/views/tasks/edit.blade.php

1<x-app-layout>
2 <x-slot name="header">
3 <h2 class="font-semibold text-xl text-gray-800 leading-tight">
4 {{ __('Edit Task') }}
5 </h2>
6 </x-slot>
7 
8 <div class="py-12">
9 <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
10 <div class="bg-white overflow-hidden shadow-xl sm:rounded-lg">
11 <div class="relative overflow-x-auto shadow-md sm:rounded-lg px-4 py-4">
12 <x-jet-validation-errors class="mb-4" />
13 
14 <form method="POST" action="{{ route('tasks.update', $task) }}">
15 @csrf
16 @method('PUT')
17 
18 <div>
19 <x-jet-label for="name" value="{{ __('Name') }}" />
20 <x-jet-input id="name" class="block mt-1 w-full" type="text" name="name" :value="$task->name" required autofocus autocomplete="name" />
21 </div>
22 
23 <div class="flex mt-4">
24 <x-jet-button>
25 {{ __('Save Task') }}
26 </x-jet-button>
27 </div>
28 </div>
29 </div>
30 </div>
31 </div>
32</x-app-layout>

Finally, we need to build the Delete button. We'll use a new Jetstream component called x-jet-danger-button. With that, let's also replace the "Edit" link to look more like a button.

resources/views/tasks/index.blade.php:

1<td class="px-6 py-4 font-medium text-gray-900 dark:text-white whitespace-nowrap">
2 {{ $task->name }}
3</td>
4<td class="px-6 py-4">
5 <x-link href="{{ route('tasks.edit', $task) }}">Edit</x-link>
6 <form method="POST" action="{{ route('tasks.destroy', $task) }}" class="inline-block">
7 @csrf
8 @method('DELETE')
9 <x-jet-danger-button
10 type="submit"
11 onclick="return confirm('Are you sure?')">Delete</x-jet-danger-button>
12 </form>
13</td>

Visual result:


Roles and Permissions

For that part, we will use a well-known popular package called Laravel Permission by Spatie.

As you'll see, the usage is independent of Jetstream, it's the same as you would use it in any other Laravel project. In other words, Jetstream gives you the basic auth with login/register forms and profile management, but whatever you add on top, mostly doesn't "care" about Jetstream.

For a simple example, let's allow any user to view the tasks, but only the administrator user will be allowed to add/edit/delete tasks.

So, as the documentation of the package says, we run:

1composer require spatie/laravel-permission
2php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"
3php artisan migrate

Then, we need to enable the permissions in the User model.

app/Models/User.php:

1use Spatie\Permission\Traits\HasRoles;
2 
3class User extends Authenticatable
4{
5 use HasRoles;

By default, any registered user will not have any roles or permissions. We will create a separate seeder class, to create the administrator with permissions.

1php artisan make:seeder AdminUserSeeder

database/seeders/AdminUserSeeder.php:

1use App\Models\User;
2use Illuminate\Database\Seeder;
3use Spatie\Permission\Models\Permission;
4use Spatie\Permission\Models\Role;
5 
6class AdminUserSeeder extends Seeder
7{
8 public function run()
9 {
10 $adminRole = Role::create(['name' => 'Administrator']);
11 $permission = Permission::create(['name' => 'manage tasks']);
12 $permission->assignRole($adminRole);
13 
14 $adminUser = User::factory()->create([
15 'email' => 'admin@admin.com',
16 'password' => bcrypt('SecurePassword')
17 ]);
18 $adminUser->assignRole('Administrator');
19 }
20}

And now, we need to check who has permission to manage tasks. You can check it by permission name or by role name, it's your personal preference.

First, in the Blade file, see three @can ... @endcan blocks.

resources/views/tasks/index.blade.php:

1@can('manage tasks')
2 <x-link href="{{ route('tasks.create') }}" class="m-4">Add new task</x-link>
3@endcan
4<table class="w-full text-sm text-left text-gray-500 dark:text-gray-400">
5 <thead class="text-xs text-gray-700 uppercase bg-gray-50 dark:bg-gray-700 dark:text-gray-400">
6 <tr>
7 <th scope="col" class="px-6 py-3">
8 Task name
9 </th>
10 @can('manage tasks')
11 <th scope="col" class="px-6 py-3">
12 
13 </th>
14 @endcan
15 </tr>
16 </thead>
17 <tbody>
18 @forelse ($tasks as $task)
19 <tr class="bg-white border-b dark:bg-gray-800 dark:border-gray-700">
20 <td class="px-6 py-4 font-medium text-gray-900 dark:text-white whitespace-nowrap">
21 {{ $task->name }}
22 </td>
23 @can('manage tasks')
24 <td class="px-6 py-4">
25 <x-link href="{{ route('tasks.edit', $task) }}">Edit</x-link>
26 <form method="POST" action="{{ route('tasks.destroy', $task) }}" class="inline-block">
27 @csrf
28 @method('DELETE')
29 <x-jet-danger-button
30 type="submit"
31 onclick="return confirm('Are you sure?')">Delete</x-jet-danger-button>
32 </form>
33 </td>
34 @endcan
35 </tr>
36 @empty
37 <tr class="bg-white border-b dark:bg-gray-800 dark:border-gray-700">
38 <td colspan="2"
39 class="px-6 py-4 font-medium text-gray-900 dark:text-white whitespace-nowrap">
40 {{ __('No tasks found') }}
41 </td>
42 </tr>
43 @endforelse
44 </tbody>
45</table>

And then, we also need to secure the back-end, so see the $this->authorize() checks in the Controller.

app/Http/Controllers/TaskController.php:

1class TaskController extends Controller
2{
3 public function index()
4 {
5 $tasks = Task::all();
6 
7 return view('tasks.index', compact('tasks'));
8 }
9 
10 public function create()
11 {
12 $this->authorize('manage tasks');
13 
14 return view('tasks.create');
15 }
16 
17 public function store(StoreTaskRequest $request)
18 {
19 $this->authorize('manage tasks');
20 
21 Task::create($request->validated());
22 
23 return redirect()->route('tasks.index');
24 }
25 
26 public function edit(Task $task)
27 {
28 $this->authorize('manage tasks');
29 
30 return view('tasks.edit', compact('task'));
31 }
32 
33 public function update(UpdateTaskRequest $request, Task $task)
34 {
35 $this->authorize('manage tasks');
36 
37 $task->update($request->validated());
38 
39 return redirect()->route('tasks.index');
40 }
41 
42 public function destroy(Task $task)
43 {
44 $this->authorize('manage tasks');
45 
46 $task->delete();
47 
48 return redirect()->route('tasks.index');
49 }
50}

Conclusion

That's it, we've built our CRUD with roles/permissions, on top of Jetstream. My overall goal was to show you that Jetstream is just the starter kit, but then you can write whatever custom code you want, mostly ignoring Jetstream.

That said, there are useful Blade components you can re-use, for UI elements like buttons, links, and others.

You can read more about Jetstream in the official documentation.

Code repository for this demo project is public here.

Filed in:

PovilasKorop

A web-developer with 15+ years experience, founder of Laravel QuickAdminPanel generator.

Sharing Laravel lessons on Youtube with channel Laravel Daily.