DEV Community

Cover image for How to create a laravel project to login and registration 🤓
Roshdi Raed
Roshdi Raed

Posted on • Edited on

How to create a laravel project to login and registration 🤓

To implement login and registration functionality with permissions in a Laravel project, you can follow these steps:

Step 1: Create a new Laravel project

Follow the instructions mentioned in Step 2 from the previous response to create a new Laravel project.

Step 2: Set up the database

Follow the instructions mentioned in Step 3 from the previous response to set up the database for your Laravel project.

Step 3: Generate authentication scaffolding

Follow the instructions mentioned in Step 4 from the previous response to generate the authentication scaffolding.

Step 4: Generate a User model and migration

Run the following command to generate a User model and migration:

php artisan make:model User -m
Enter fullscreen mode Exit fullscreen mode

This command will create a User model and a migration file to create the "users" table.

Step 5: Update the User migration file

Open the migration file for the "users" table (located in the database/migrations directory) and update the up method to include additional fields for permissions. Here's an example:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->string('permissions')->default('user'); // Add permissions column
        $table->rememberToken();
        $table->timestamps();
    });
}
Enter fullscreen mode Exit fullscreen mode

Step 6: Run the migrations

Run the following command to apply the migrations and create the "users" table:

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

Step 7: Define permission levels

Open the config/auth.php file and define the permission levels under the providers section. For example:

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\Models\User::class,
    ],
],

'permissions' => [
    'user' => 1, // Lowest permission level
    'admin' => 2, // Higher permission level
],
Enter fullscreen mode Exit fullscreen mode

Step 8: Add permissions trait to User model

Open the User model (app/Models/User.php) and add the HasPermissions trait. You can create a new file called HasPermissions.php under the app/Traits directory with the following content:

<?php

namespace App\Traits;

trait HasPermissions
{
    public function hasPermission($permission)
    {
        return $this->permissions >= config('auth.permissions.' . $permission);
    }
}
Enter fullscreen mode Exit fullscreen mode

Then, in the User model, use the HasPermissions trait and define a few helper methods. Here's an example:

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use App\Traits\HasPermissions;

class User extends Authenticatable implements MustVerifyEmail
{
    use Notifiable, HasPermissions;

    // ...

    public function isAdmin()
    {
        return $this->hasPermission('admin');
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 9: Update the authentication views

Open the views for login and registration (resources/views/auth/login.blade.php and resources/views/auth/register.blade.php). Add an input field for the "permissions" column to the registration form. For example:

<div class="form-group row">
    <label for="permissions" class="col-md-4 col-form-label text-md-right">{{ __('

Permissions') }}</label>

    <div class="col-md-6">
        <input id="permissions" type="text" class="form-control @error('permissions') is-invalid @enderror" name="permissions" value="{{ old('permissions') }}" required autocomplete="permissions" autofocus>

        @error('permissions')
            <span class="invalid-feedback" role="alert">
                <strong>{{ $message }}</strong>
            </span>
        @enderror
    </div>
</div>
Enter fullscreen mode Exit fullscreen mode

Step 10: Update the registration validation

Open the app/Http/Controllers/Auth/RegisterController.php file and update the validator method to include the "permissions" field. Add the following line:

protected function validator(array $data)
{
    return Validator::make($data, [
        'name' => ['required', 'string', 'max:255'],
        'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
        'password' => ['required', 'string', 'min:8', 'confirmed'],
        'permissions' => ['required', 'string'], // Add this line
    ]);
}
Enter fullscreen mode Exit fullscreen mode

Step 11: Update the registration process

Open the app/Http/Controllers/Auth/RegisterController.php file and update the create method to save the "permissions" field. Add the following line:

protected function create(array $data)
{
    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
        'permissions' => $data['permissions'], // Add this line
    ]);
}
Enter fullscreen mode Exit fullscreen mode

Step 12: Use permissions in your application

You can now use the hasPermission method in your application to check the user's permissions. Here's an example:

if (Auth::user()->hasPermission('admin')) {
    // User has admin permission
} else {
    // User does not have admin permission
}
Enter fullscreen mode Exit fullscreen mode

That's it! You have implemented login and registration functionality with permissions in your Laravel project. You can now customize and expand upon this foundation to meet your specific requirements.

Top comments (0)