User Roles and Permissions using Laravel 8 – Part 2

by stackdeveloping
53 comments 265 views
User Roles and permissions Part 2

Contents

Step 8 – Create Authentication Kit

There are several Packets to use for Authentication, such as Laravel UI that its related with LaravelCollective, also there is Breeze that works at same way, using only HTML and more modern way is Jetstream that works with Vue templates, and its followed by two Sub Packets like LiveWire and Inertia.
In this tutorial we have to go with laravel/ui. So import it as below:
composer require laravel/ui
After this we need to generate the authentication scaffolding using PHP Artisan:

php artisan ui bootstrap --auth
After that we have to install all NPM extensions
npm install

And then we have to deploy UI in development mode:
npm run dev
If we want to deploy the UI in Production Mode we have to run
npm run build
and all the HTML files or CSS files or Js files will convert into minified format.

Step 9 – Create Routes

 

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\HomeController;
use App\Http\Controllers\RoleController;
use App\Http\Controllers\UserController;
use App\Http\Controllers\ProductController;

Route::get('/', function () {
    return view('welcome');
});
  
Auth::routes();
  
Route::get('/home', [HomeController::class, 'index'])->name('home');
  
Route::group(['middleware' => ['auth']], function() {
    Route::resource('roles', RoleController::class);
    Route::resource('users', UserController::class);
    Route::resource('products', ProductController::class);
});

Step 10 – Create Controllers UserController, ProductController and RoleController

Controller by default we can create by the command of PHP Artisan as below:

php artisan make:controller name-of-controller
But we want to deploy also defaults methods, such as index(), store(), show(), edit(), update() and destroy() we need to run the command as below:
php artisan make:controller name-of-controller --resource So lets create for each case php artisan make:controller UserController --resource

php artisan make:controller ProductController --resource
php artisan make:controller RoleController --resource
All the files are located to app/http/Controllers/name-of-controller.php

app/Http/Controllers/UserController.php

<?php
    
namespace App\Http\Controllers;
    
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\User;
use Spatie\Permission\Models\Role;
use DB;
use Hash;
use Illuminate\Support\Arr;
    
class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = User::orderBy('id','DESC')->paginate(5);
        return view('users.index',compact('data'))
            ->with('i', ($request->input('page', 1) - 1) * 5);
    }
    
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $roles = Role::pluck('name','name')->all();
        return view('users.create',compact('roles'));
    }
    
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|same:confirm-password',
            'roles' => 'required'
        ]);
    
        $input = $request->all();
        $input['password'] = Hash::make($input['password']);
    
        $user = User::create($input);
        $user->assignRole($request->input('roles'));
    
        return redirect()->route('users.index')
                        ->with('success','User created successfully');
    }
    
    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $user = User::find($id);
        return view('users.show',compact('user'));
    }
    
    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $user = User::find($id);
        $roles = Role::pluck('name','name')->all();
        $userRole = $user->roles->pluck('name','name')->all();
    
        return view('users.edit',compact('user','roles','userRole'));
    }
    
    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'name' => 'required',
            'email' => 'required|email|unique:users,email,'.$id,
            'password' => 'same:confirm-password',
            'roles' => 'required'
        ]);
    
        $input = $request->all();
        if(!empty($input['password'])){ 
            $input['password'] = Hash::make($input['password']);
        }else{
            $input = Arr::except($input,array('password'));    
        }
    
        $user = User::find($id);
        $user->update($input);
        DB::table('model_has_roles')->where('model_id',$id)->delete();
    
        $user->assignRole($request->input('roles'));
    
        return redirect()->route('users.index')
                        ->with('success','User updated successfully');
    }
    
    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        User::find($id)->delete();
        return redirect()->route('users.index')
                        ->with('success','User deleted successfully');
    }
}

app/Http/Controllers/ProductController.php

<?php
    
namespace App\Http\Controllers;
    
use App\Models\Product;
use Illuminate\Http\Request;
    
class ProductController extends Controller
{ 
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    function __construct()
    {
         $this->middleware('permission:product-list|product-create|product-edit|product-delete', ['only' => ['index','show']]);
         $this->middleware('permission:product-create', ['only' => ['create','store']]);
         $this->middleware('permission:product-edit', ['only' => ['edit','update']]);
         $this->middleware('permission:product-delete', ['only' => ['destroy']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $products = Product::latest()->paginate(5);
        return view('products.index',compact('products'))
            ->with('i', (request()->input('page', 1) - 1) * 5);
    }
    
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('products.create');
    }
    
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        request()->validate([
            'name' => 'required',
            'detail' => 'required',
        ]);
    
        Product::create($request->all());
    
        return redirect()->route('products.index')
                        ->with('success','Product created successfully.');
    }
    
    /**
     * Display the specified resource.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function show(Product $product)
    {
        return view('products.show',compact('product'));
    }
    
    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function edit(Product $product)
    {
        return view('products.edit',compact('product'));
    }
    
    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Product $product)
    {
         request()->validate([
            'name' => 'required',
            'detail' => 'required',
        ]);
    
        $product->update($request->all());
    
        return redirect()->route('products.index')
                        ->with('success','Product updated successfully');
    }
    
    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function destroy(Product $product)
    {
        $product->delete();
    
        return redirect()->route('products.index')
                        ->with('success','Product deleted successfully');
    }
}

app/Http/Controllers/RoleController.php

<?php
    
namespace App\Http\Controllers;


use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use DB;
    
class RoleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    function __construct()
    {
         $this->middleware('permission:role-list|role-create|role-edit|role-delete', ['only' => ['index','store']]);
         $this->middleware('permission:role-create', ['only' => ['create','store']]);
         $this->middleware('permission:role-edit', ['only' => ['edit','update']]);
         $this->middleware('permission:role-delete', ['only' => ['destroy']]);
    }
    
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $roles = Role::orderBy('id','DESC')->paginate(5);
        return view('roles.index',compact('roles'))
            ->with('i', ($request->input('page', 1) - 1) * 5);
    }
    
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $permission = Permission::get();
        return view('roles.create',compact('permission'));
    }
    
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|unique:roles,name',
            'permission' => 'required',
        ]);
    
        $role = Role::create(['name' => $request->input('name')]);
        $role->syncPermissions($request->input('permission'));
    
        return redirect()->route('roles.index')
                        ->with('success','Role created successfully');
    }
    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $role = Role::find($id);
        $rolePermissions = Permission::join("role_has_permissions","role_has_permissions.permission_id","=","permissions.id")
            ->where("role_has_permissions.role_id",$id)
            ->get();
    
        return view('roles.show',compact('role','rolePermissions'));
    }
    
    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $role = Role::find($id);
        $permission = Permission::get();
        $rolePermissions = DB::table("role_has_permissions")->where("role_has_permissions.role_id",$id)
            ->pluck('role_has_permissions.permission_id','role_has_permissions.permission_id')
            ->all();
    
        return view('roles.edit',compact('role','permission','rolePermissions'));
    }
    
    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'name' => 'required',
            'permission' => 'required',
        ]);
    
        $role = Role::find($id);
        $role->name = $request->input('name');
        $role->save();
    
        $role->syncPermissions($request->input('permission'));
    
        return redirect()->route('roles.index')
                        ->with('success','Role updated successfully');
    }
    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        DB::table("roles")->where('id',$id)->delete();
        return redirect()->route('roles.index')
                        ->with('success','Role deleted successfully');
    }
}

You may also like

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.

53 comments

Swift OpenAPI Generator Aims at Streamlining HTTP Client/Server Communication - Stack Code Info June 15, 2023 - 4:19 pm

[…] that must exist in the target source directory along with the OpenAPI document in JSON or YAML format. Using this configuration file, you can specify whether to generate only the client […]

Reply
seksi siteler December 22, 2023 - 8:37 am

daxktilogibigibi.NBQk5ma7O2TB

Reply
Kmtckcleri December 25, 2023 - 11:36 am Reply
intuition December 29, 2023 - 8:04 pm

xyandanxvurulmus.bnGMgbzh8nAf

Reply
biostatic December 29, 2023 - 9:24 pm

xbunedirloooo.rva8rLWowXEK

Reply
bildungsromane December 30, 2023 - 8:25 am

bildungsromane xyandanxvurulmus.XVC8m9E1XaRV

Reply
motey December 31, 2023 - 4:16 pm

motey xyandanxvurulmus.mJL3M47LusYg

Reply
Vefjkatte January 6, 2024 - 6:16 am Reply
Knrhdcleri January 6, 2024 - 8:33 am Reply
VBtkjkatte January 7, 2024 - 11:40 pm Reply
Kppkddcleri January 8, 2024 - 1:55 am Reply
VBtqkjkatte January 9, 2024 - 5:07 am Reply
Kppkrncleri January 9, 2024 - 7:31 am Reply
VBsgckatte January 10, 2024 - 10:11 am Reply
Kpbdfcleri January 10, 2024 - 12:27 pm Reply
Ctrnfkatte January 24, 2024 - 6:58 am Reply
Knttncleri January 24, 2024 - 10:09 am Reply
Cnrvkatte January 26, 2024 - 4:35 pm Reply
Kymccleri January 26, 2024 - 6:38 pm Reply
ZbRjeAEip February 1, 2024 - 6:02 pm

OhsSmNHYwx

Reply
eskort siteleri February 2, 2024 - 11:31 am

sektor benim zaten amin evladi pompadirha.oHZciDAgzf5W

Reply
sexx February 2, 2024 - 11:47 am

porn sex asillartaklitler.GmYbQajaBvCr

Reply
watch porn video February 2, 2024 - 4:30 pm

seks siteleri hephupx.KkE7eHYGPPuY

Reply
fuck google February 3, 2024 - 12:03 pm

bahis siteleri porn hepxhupx.4HsEHZbvrWcv

Reply
porno February 3, 2024 - 12:58 pm

am siteleri juljulfbi.k3xVMOpV8NtF

Reply
fuck google February 5, 2024 - 6:59 am

escort siteleri bjluajszz.PeKDnNUkbVk2

Reply
am siteleri February 5, 2024 - 7:18 am

fuck google bxjluajsxzz.9P89czzhsrpM

Reply
bahis siteleri incest category February 5, 2024 - 7:38 am

escort 0qbxjluaxcxjsxzz.JGTyczqPXnlq

Reply
viagra February 21, 2024 - 7:51 am

fuck footballxx.x1mJF7bb6UIb

Reply
porno February 21, 2024 - 7:56 am

anal sikis siteleri mobileidn.3Dvk6fFS0um6

Reply
craft porn February 21, 2024 - 8:01 am

craft porn bingoxx.6zDNlT5GUmHv

Reply
porn siteleri February 21, 2024 - 8:17 am

watch porn video 250tldenemebonusuxx.U3RmmWfyGSyH

Reply
eski rahatiniz olmayacak February 21, 2024 - 10:25 am

bahis porno eyeconartxx.gXCe0qgtVzgs

Reply
Ctnkatte February 22, 2024 - 10:29 am Reply
BİZİ SİK BİZ BUNU HAK EDİYORUZ February 22, 2024 - 4:40 pm

pornhub bahis siteleri vvsetohimalxxvc.0AACEmeIxcrM

Reply
Syhkphept February 22, 2024 - 8:54 pm Reply
XthfCalge February 22, 2024 - 11:48 pm Reply
Kthcleri February 23, 2024 - 3:29 pm Reply
bahis siteleri porn February 23, 2024 - 8:49 pm

watch porn video tthighereduhryyy.FltHXmQ5CxX

Reply
Ctjkatte February 24, 2024 - 2:30 pm Reply
Shephept February 24, 2024 - 11:41 pm Reply
XjeCalge February 25, 2024 - 2:36 am Reply
porno izle February 25, 2024 - 12:42 pm

User Roles and Permissions using Laravel 8 – Part 2 – Stack Developing

https://www.bdconsultingltd.com/what-does-indeed-all-of-our-paper-evaluation-assistance-accomplish/

Reply
porn February 25, 2024 - 12:43 pm

User Roles and Permissions using Laravel 8 – Part 2 – Stack Developing

https://www.vasahalsoklinik.se/2021/01/19/hello-world/

Reply
child porn February 25, 2024 - 7:52 pm

User Roles and Permissions using Laravel 8 – Part 2 – Stack Developing

https://kinima21.com/2023/05/16/διακαναλική-κίνημα-21/

Reply
Ktbcleri February 26, 2024 - 10:53 am Reply
porn February 26, 2024 - 3:43 pm

User Roles and Permissions using Laravel 8 – Part 2 – Stack Developing

https://weonekeralaonline.com/സന്നിധാനത്ത്-ഒരുക്കങ്ങള/

Reply
Cnntkatte February 26, 2024 - 9:21 pm Reply
Smgphept February 26, 2024 - 9:45 pm Reply
XjjeCalge February 27, 2024 - 12:46 am Reply
Kethcleri February 28, 2024 - 3:43 am Reply
Crmmkatte February 28, 2024 - 6:04 pm Reply
Snduphept February 28, 2024 - 7:53 pm Reply

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More