Alfie Mellor

Alfie Mellor

1570261528

How to create Laravel 6 multiple Authentication using Middleware

I written many tutorials about multi authentication in laravel. in this tutorial we will create multi auth very simple way using middleware with single table. if you want to create multiple authentication using guard than you can follow this tutorial: Laravel multi auth example using Auth guard from scratch

However, in this example, we will create very simple way and you can easily use with your Laravel 6 Application. so let’s follow this step.

Step 1: Install Laravel 6

first of all we need to get fresh Laravel 6 version application using bellow command, So open your terminal OR command prompt and run bellow command:

composer create-project --prefer-dist laravel/laravel blog

Step 2: Database Configuration

In second step, we will make database configuration for example database name, username, password etc for our crud application of laravel 6. So let’s open .env file and fill all details like as bellow:

.env

DB_CONNECTION=mysql

DB_HOST=127.0.0.1

DB_PORT=3306

DB_DATABASE=here your database name(blog)

DB_USERNAME=here database username(root)

DB_PASSWORD=here database password(root)

Step 3: Update Migration and Model

In this step, we need to add new row “is_admin” in users table and model. than we need to run migration. so let’s change that on both file.

database/migrations/000_create_users_table.php

<?php

   

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

   

class CreateUsersTable extends Migration

{

    /**

     * Run the migrations.

     *

     * @return void

     */

    public function up()

    {

        Schema::create('users', function (Blueprint $table) {

            $table->bigIncrements('id');

            $table->string('name');

            $table->string('email');

            $table->timestamp('email_verified_at')->nullable();

            $table->boolean('is_admin')->nullable();

            $table->string('password');

            $table->rememberToken();

            $table->timestamps();

        });

    }

  

    /**

     * Reverse the migrations.

     *

     * @return void

     */

    public function down()

    {

        Schema::dropIfExists('users');

    }

}

app/User.php

<?php

   

namespace App;

   

use Illuminate\Contracts\Auth\MustVerifyEmail;

use Illuminate\Foundation\Auth\User as Authenticatable;

use Illuminate\Notifications\Notifiable;

   

class User extends Authenticatable

{

    use Notifiable;

   

    /**

     * The attributes that are mass assignable.

     *

     * @var array

     */

    protected $fillable = [

        'name', 'email', 'password', 'is_admin'

    ];

   

    /**

     * The attributes that should be hidden for arrays.

     *

     * @var array

     */

    protected $hidden = [

        'password', 'remember_token',

    ];

   

    /**

     * The attributes that should be cast to native types.

     *

     * @var array

     */

    protected $casts = [

        'email_verified_at' => 'datetime',

    ];

}

php artisan migrate
so let’s run bellow command:

php artisan migrate

Step 4: Create Auth using scaffold

Now, in this step, we will create auth scaffold command to create login, register and dashboard. so run following commands:

Laravel 6 UI Package

composer require laravel/ui 

Generate auth

php artisan ui bootstrap --auth 
npm install
npm run dev

Step 5: Create IsAdmin Middleware

In this step, we require to create admin middleware that will allows only admin access users to that routes. so let’s create admin user with following steps.

php artisan make:middleware IsAdmin

app/Http/middleware/IsAdmin.php

<?php

  

namespace App\Http\Middleware;

  

use Closure;

   

class IsAdmin

{

    /**

     * Handle an incoming request.

     *

     * @param  \Illuminate\Http\Request  $request

     * @param  \Closure  $next

     * @return mixed

     */

    public function handle($request, Closure $next)

    {

        if(auth()->user()->is_admin == 1){

            return $next($request);

        }

   

        return redirect(‘home’)->with(‘error’,"You don't have admin access.");

    }

}

app/Http/Kernel.php

....

protected $routeMiddleware = [

    'auth' => \App\Http\Middleware\Authenticate::class,

    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,

    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,

    'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,

    'can' => \Illuminate\Auth\Middleware\Authorize::class,

    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,

    'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,

    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,

    'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,

    'is_admin' => \App\Http\Middleware\IsAdmin::class,

];

....

Step 6: Create Route

Here, we need to add one more route for admin user home page so let’s add that route in web.php file.

routes/web.php

Route::get('admin/home', 'HomeController@adminHome')->name('admin.home')->middleware('is_admin');

Step 7: Add Method on Controller

Here, we need add adminHome() method for admin route in HomeController. so let’s add like as bellow:

app/Http/Controllers/HomeController.php

<?php

   

namespace App\Http\Controllers;

  

use Illuminate\Http\Request;

   

class HomeController extends Controller

{

    /**

     * Create a new controller instance.

     *

     * @return void

     */

    public function __construct()

    {

        $this->middleware('auth');

    }

  

    /**

     * Show the application dashboard.

     *

     * @return \Illuminate\Contracts\Support\Renderable

     */

    public function index()

    {

        return view('home');

    }

  

    /**

     * Show the application dashboard.

     *

     * @return \Illuminate\Contracts\Support\Renderable

     */

    public function adminHome()

    {

        return view('adminHome');

    }

    

}

Step 8: Create Blade file

In this step, we need to create new blade file for admin and update for user blade file. so let’s change it.

resources/views/home.blade.php

@extends('layouts.app')

   

@section('content')

<div class="container">

    <div class="row justify-content-center">

        <div class="col-md-8">

            <div class="card">

                <div class="card-header">Dashboard</div>

                <div class="card-body">

                    You are normal user.

                </div>

            </div>

        </div>

    </div>

</div>

@endsection

resources/views/adminHome.blade.php

@extends('layouts.app')

   

@section('content')

<div class="container">

    <div class="row justify-content-center">

        <div class="col-md-8">

            <div class="card">

                <div class="card-header">Dashboard</div>

                <div class="card-body">

                    You are Admin.

                </div>

            </div>

        </div>

    </div>

</div>

@endsection

Step 9: Update on LoginController

In this step, we will change on LoginController, when user will login than we redirect according to user access. if normal user than we will redirect to home route and if admin user than we redirect to admin route. so let’s change.

app/Http/Controllers/Auth/LoginController.php

<?php

  

namespace App\Http\Controllers\Auth;

   

use App\Http\Controllers\Controller;

use Illuminate\Foundation\Auth\AuthenticatesUsers;

use Illuminate\Http\Request;

   

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 = '/home';

   

    /**

     * Create a new controller instance.

     *

     * @return void

     */

    public function __construct()

    {

        $this->middleware('guest')->except('logout');

    }

   

    public function login(Request $request)

    {   

        $input = $request->all();

   

        $this->validate($request, [

            'email' => 'required|email',

            'password' => 'required',

        ]);

   

        if(auth()->attempt(array('email' => $input['email'], 'password' => $input['password'])))

        {

            if (auth()->user()->is_admin == 1) {

                return redirect()->route('admin.home');

            }else{

                return redirect()->route('home');

            }

        }else{

            return redirect()->route('login')

                ->with('error','Email-Address And Password Are Wrong.');

        }

          

    }

}

Step 10: Create Seeder

We will create seeder for create new admin and normal user. so let’s create seeder using following command:

php artisan make:seeder CreateUsersSeeder

database/seeds/CreateUsersSeeder.php

<?php

  

use Illuminate\Database\Seeder;

use App\User;

   

class CreateUsersSeeder extends Seeder

{

    /**

     * Run the database seeds.

     *

     * @return void

     */

    public function run()

    {

        $user = [

            [

               'name'=>'Admin',

               'email'=>'admin@itsolutionstuff.com',

                'is_admin'=>'1',

               'password'=> bcrypt('123456'),

            ],

            [

               'name'=>'User',

               'email'=>'user@itsolutionstuff.com',

                'is_admin'=>'0',

               'password'=> bcrypt('123456'),

            ],

        ];

  

        foreach ($user as $key => $value) {

            User::create($value);

        }

    }

}

Now let’s run seeder:

php artisan db:seed --class=CreateUsersSeeder

Ok, now we are ready to run.

So let’s run project using this command:

php artisan serve

Admin User

Email: admin@itsolutionstuff.com

Password: 123456

How to create Laravel 6 multiple Authentication using Middleware

Normal User

Email: user@itsolutionstuff.com

Password: 123456

How to create Laravel 6 multiple Authentication using Middleware

I hope it can help you…

#laravel #php #web-development

What is GEEK

Buddha Community

How to create Laravel 6 multiple Authentication using Middleware
Seamus  Quitzon

Seamus Quitzon

1595201363

Php how to delete multiple rows through checkbox using ajax in laravel

First thing, we will need a table and i am creating products table for this example. So run the following query to create table.

CREATE TABLE `products` (
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
 `description` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
 `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
 `updated_at` datetime DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

Next, we will need to insert some dummy records in this table that will be deleted.

INSERT INTO `products` (`name`, `description`) VALUES

('Test product 1', 'Product description example1'),

('Test product 2', 'Product description example2'),

('Test product 3', 'Product description example3'),

('Test product 4', 'Product description example4'),

('Test product 5', 'Product description example5');

Now we are redy to create a model corresponding to this products table. Here we will create Product model. So let’s create a model file Product.php file under app directory and put the code below.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = [
        'name','description'
    ];
}

Step 2: Create Route

Now, in this second step we will create some routes to handle the request for this example. So opeen routes/web.php file and copy the routes as given below.

routes/web.php

Route::get('product', 'ProductController@index');
Route::delete('product/{id}', ['as'=>'product.destroy','uses'=>'ProductController@destroy']);
Route::delete('delete-multiple-product', ['as'=>'product.multiple-delete','uses'=>'ProductController@deleteMultiple']);

#laravel #delete multiple rows in laravel using ajax #laravel ajax delete #laravel ajax multiple checkbox delete #laravel delete multiple rows #laravel delete records using ajax #laravel multiple checkbox delete rows #laravel multiple delete

I am Developer

1597559012

Multiple File Upload in Laravel 7, 6

in this post, i will show you easy steps for multiple file upload in laravel 7, 6.

As well as how to validate file type, size before uploading to database in laravel.

Laravel 7/6 Multiple File Upload

You can easily upload multiple file with validation in laravel application using the following steps:

  1. Download Laravel Fresh New Setup
  2. Setup Database Credentials
  3. Generate Migration & Model For File
  4. Make Route For File uploading
  5. Create File Controller & Methods
  6. Create Multiple File Blade View
  7. Run Development Server

https://www.tutsmake.com/laravel-6-multiple-file-upload-with-validation-example/

#laravel multiple file upload validation #multiple file upload in laravel 7 #multiple file upload in laravel 6 #upload multiple files laravel 7 #upload multiple files in laravel 6 #upload multiple files php laravel

I am Developer

1597470037

Laravel 7 Multiple Image Upload with Preview

Here, i will show you how to upload multiple image with preview using ajax in laravel.

Laravel 7 Ajax Multiple Image Upload with Preview

Just follow the below steps and upload multiple images using ajax with showing preview in laravel applications:

  • Install Laravel Fresh Setup
  • Setup Database Credentials
  • Create Route
  • Generate Controller By Command
  • Create the blade view
  • Start Development Server

https://www.tutsmake.com/laravel-7-6-ajax-multiple-image-upload-with-preview-e-g/

#laravel multiple image upload with preview #laravel multiple image validation #display multiple images in laravel #laravel multiple file upload #multiple image upload in laravel 6 #ajax image upload and preview with laravel

I am Developer

1597559901

Laravel 7.x/6 Multiple Image Upload Ajax

Here, i will share with you how to multiple image upload in laravel 7, 6 using ajax. And display preview of multiple images before upload in laravel.

Multiple Image Upload With Preview in Laravel 7/6 using Ajax

Upload multiple images using ajax with preview in laravel 7/6 by following the below steps:

  1. Install Laravel Fresh Setup
  2. Setup Database Credentials
  3. Create Multiple Image Upload Route
  4. Generate Image Controller By Command
  5. Create Multiple Image Upload Preview blade view
  6. Start Development Server

https://www.tutsmake.com/laravel-7-6-ajax-multiple-image-upload-with-preview-e-g/

#ajax multiple image upload and preview with laravel #multiple image upload in laravel 6 #laravel multiple image upload with preview #upload multiple images ajax jquery laravel #laravel multiple image validation

I am Developer

1597499549

Ajax Multiple Image Upload with Progress bar with jQuery in Laravel

In this post, i will show you, how you can upload multiple file with progress bar in laravel using jQuery ajax.

So follow below given steps to create ajax multiple image upload with progress bar with jquery and laravel php.

Multiple File Upload with Progress bar Using jQuery and Laravel PHP

Now follow the below given simple and easy step to upload multiple file with progress bar in laravel using jQuery ajax:

  • Step 1: Download Laravel App
  • Step 2: Add Database Details
  • Step 3: Create Migration & Model
  • Step 4: Add Routes For Multiple File Upload
  • Step 5: Create Controller by Artisan
  • Step 6: Create Blade View
  • Step 7: Run Development Server

https://www.tutsmake.com/laravel-7-multiple-file-upload-with-progress-bar/

#multiple file upload with progress bar using jquery and laravel #laravel multiple file upload ajax with progress bar #how to upload multiple images with progress bar in laravel #laravel 7 multiple image upload example #image upload with progress bar laravel #laravel multiple image upload ajax