How to create a laravel project to login and registration 🤓
Tags: laravel, backend, programming, beginners
Published: 2023-06-22 10:15:02

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
```

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:

```php
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();
    });
}
```

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

```
php artisan migrate
```

Step 7: Define permission levels
-------------------------------
Open the `config/auth.php` file and define the permission levels under the `providers` section. For example:

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

'permissions' => [
    'user' => 1, // Lowest permission level
    'admin' => 2, // Higher permission level
],
```

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
<?php

namespace App\Traits;

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

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

```php
<?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');
    }
}
```

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:

```html
<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>
```

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:

```php
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
    ]);
}
```

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:

```php
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
    ]);
}
```

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:

```php
if (Auth::user()->hasPermission('admin')) {
    // User has admin permission
} else {
    // User does not have admin permission
}
```

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.