Courses

Creating a Quiz System with Laravel 10 + Livewire 3: Step-by-Step

Admin User with Middleware

Now let's create a simple adminpanel to create or edit your questions or quizzes. We will not build a separate area for that, just will restrict some routes. So let's quickly create Middleware that will be used on such routes.

First, we need to is_admin column in the User table.

php artisan make:migration "add is admin to users table"

database/migrations/xxxx_add_is_admin_to_users_table.php:

return new class extends Migration
{
public function up(): void
{
Schema::table('users', function (Blueprint $table) {
$table->boolean('is_admin')->default(false)->after('password');
});
}
};

Fillable fields:

app/Models/User.php:

class User extends Authenticatable
{
// ...
protected $fillable = [
'name',
'email',
'password',
'is_admin',
'facebook_id',
'google_id',
'github_id',
];
// ...
}

And let's create the middleware.

php artisan make:middleware isAdmin

app/Http/Middleware/isAdmin.php:

class isAdmin
{
public function handle(Request $request, Closure $next): Response
{
if (auth()->user() && auth()->user()->is_admin) {
return $next($request);
}
 
abort(403);
}
}

Register it:

app/Http/Kernel.php:

class Kernel extends HttpKernel
{
// ...
protected $middlewareAliases = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \App\Http\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'isAdmin' => \App\Http\Middleware\isAdmin::class
];
}

Now for every route that needs to be protected, we will be able to use isAdmin middleware.

Let's add one other thing for reuse ability, custom blade if statement. In the app/Providers/AppServiceProvider.php:

use Illuminate\Support\Facades\Blade;
 
class AppServiceProvider extends ServiceProvider
{
// ...
public function boot(): void
{
Blade::if('admin', function () {
return auth()->user()?->is_admin;
});
}
}

This way, we will be able to use @admin in blade files to show content only for the admin user.

@admin
Content only for admin!
@endadmin
avatar

Do you have a github available I get a lot of confusement by classes that are not imported. I can't get past this section 3. And I believe it would be easier to follow allong with the full code in stead of only the changed methods or classes. Would love to see some git hub repository because I can't get past this section

avatar

Link to the repo is in the last lesson

avatar

Let's add one other thing for reuse ability, custom blade if statement. In the app/Providers/AppServiceProvider.php:

You should also import the Blade class on top right?

use Illuminate\Support\Facades\Blade;

👍 1
avatar

Page cannot be accessed after middleware creation or just to say after this stage. Any thing wrong? I get forbidden

avatar

If you would show some code (don't forget to format it!) maybe then someone would be able to help.

avatar

I just did step by step as the tutorial suggested. After the local:8000 page displays, the login and register shows page cannot be displayed error 403. I will post the web routes so you can check where the mistake is. I am using laravel 10

Route::get('/', function () { return view('welcome'); });

Route::get('/dashboard', function () { return view('dashboard'); })->middleware(['auth', 'verified'])->name('dashboard');

Route::middleware('auth')->group(function () { Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit'); Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update'); Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy'); });

require DIR.'/auth.php';

avatar

After going through the following steps:

app/Models/User.php:

app/Http/Middleware/isAdmin.php:

app/Http/Kernel.php:

AppServiceProvider.php:

The page cannot display I get:

403 Forbidden

avatar

Where did you add the middleware in the kernel? And please please format the code with markdown....

avatar

I placed it in "protected middeware". But now after your answer I moved it to "protected $middlewareGroups" and now the page is displaying. Thanks a lot for the help