Curso App para Pizzerías

Auth y Roles de Usuario: Admin y Cliente

Implementación de Roles de Usuario con el Paquete Spatie Permission para asignar las tareas de cada usuario en la Tabla User

Lección 3 del Curso App para Pizzerías

DESCRIPCIÓN DE LA LECCIÓN

Implementación de Roles de Usuario con el Paquete Spatie Permission para asignar las tareas de cada usuario en la Tabla User

Modelo, Migración, controlador y vistas para gestionar la tabla categorías donde asignaremos dos: Pizzas y Bebidas.

Intalacion de Spatie Permission ejecutar Artisan

 composer require spatie/laravel-permission

 

config/app.php

'providers' => [
    // ...
    Spatie\Permission\PermissionServiceProvider::class,
];

 

Ejecutar artisan

php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"

 

en  kernel.php

protected $routeMiddleware = [
        ....
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
        'role' => \Spatie\Permission\Middlewares\RoleMiddleware::class,
    ];

 

 

Modelo User

<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable,HasRoles;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'celular',
        'direccion',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}



 

LoginController

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::HOME;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    public function redirectPath(){
        if(auth()->user()->hasRole("admin")){
            return "admin/categoria";
        }
        return "/";
    }
}

 

RegisterController

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\Models\User;
use Spatie\Permission\Models\Role;

use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::HOME;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    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'],
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\Models\User
     */
    protected function create(array $data)
    {
        $user   =  User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'celular' => $data['celular'],
            'direccion' => $data['direccion'],
            'password' => Hash::make($data['password']),
        ]);
        $user->assignRole("cliente");
        return $user;
    }
    protected function redirectTo(){
        if(auth()->user()->hasRole("admin")){
            return "/admin/categoria";
        }
        return "/";
    }
}

web.php

<?php

use Illuminate\Support\Facades\Route;
/*
use Spatie\Permission\Models\Role;
$role = Role::create(['name' => 'admin']);
$role = Role::create(['name' => 'cliente']);
*/

Route::get('/', function () {    return view('welcome');});
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');



Route::group(['prefix' => 'admin', 	'middleware' => ['auth','role:admin']], function() {
    // rutas para el administrador
    Route::resource('categoria', App\Http\Controllers\Admin\CategoriaController::class,["as"=>"admin"]);
});

Route::group(['prefix' => 'cliente', 	'middleware' => ['auth','role:cliente']], function() {
    // rutas exclusivas para el cliente
});

POR LA COMPRA DEL CURSO COMPLETO

  • MIRA TODOS LOS VIDEOS SIN RESTRICCIÓN
  • TEN ACCESO AL CURSO
  • DESCARGA TODO CÓDIGO FUENTE DEL PROYECTO
  • ACCESO A CURSOS Y RECURSOS GRATIS

App para Pizzerías

Auth y Roles de Usuario: Admin y Cliente

77 visitas

Lecciones del curso

4. Implementación del CRUD de Categorías 44
5. Implementación CRUD Productos 48
6. Implementación CRUD Precios 27
7. Implementación CRUD Pedidos 51
8. Implementación CRUD Clientes 25
9. Diseño de la Portada con productos 26
10. Diseño e implementación del Catálogo 36
11. Diseño Detalle del Producto 47
VER MÁS CURSOS
Codea App

Codea App FullStack

Perú, México, Colombia, España, Venezuela, Argentina, Bolivia

You Fb Tik Pin

© Todos los derechos reservados Codea App FullStack | Cursos de programación avanzados | 2020 - 2021