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
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
Link to the repo is in the last lesson