Joseph  Norton

Joseph Norton

1569810666

How to use multiple Authentication using guards in Laravel 6?

Prerequisites

PHP >= 7.1.3
OpenSSL PHP Extension
PDO PHP Extension
Mbstring PHP Extension
Tokenizer PHP Extension
XML PHP Extension
Ctype PHP Extension
JSON PHP Extension

Getting started

Check all Prerequisites are installed in your machine. then this tutorial is already looking for you, we will create 3 user class – admin, blogger, user and we will make guards for 3 user classes and restriction different parts of the application based on those guards.

Create the application

We need to run command to create Laravel 6 projects.

laravel new laravel_multi

After creating the app, now comes on the folder.

cd laravel_multi

Now configure database in .env file

Example:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_multi
DB_USERNAME=root
DB_PASSWORD=root@123

Now we will make migrations for admins and bloggers tables in laravel already have users migration.we can extend further specific needs.

Create migration for admins

Making the admin table, run these command.

php artisan make:migration create_admins_table

Now the database/migrations directory open the admins migrations file and replace up function.

public function up()
    {
        Schema::create('admins', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->boolean('is_super')->default(false);
            $table->rememberToken();
            $table->timestamps();
        });
    }

Now, create a migration for bloggers

Making the admin table, run these command.

php artisan make:migration create_bloggers_table

Now, open the bloggers migrations file and edit it as follows:

database/migrations/_create_bloggers_table.php

 public function up()
    {
        Schema::create('bloggers', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->boolean('is_editor')->default(false);
            $table->rememberToken();
            $table->timestamps();
        });
    }

Here we have created a simple migration and defined the columns.

Now, migrate the database

we have defined our tables, run migrate:

php artisan migrate

Now, we have 3 different tables users, admins, blogger to use these different tables to authenticate, we need to define 3 models for them. These models will be like the user model and extend the Authenticable class.

the user model and extends the Authenticable class.

Admin model
To make the model for the admins, run the following command:

php artisan make:model Admin

Open the Admin model in app/Admin.php and add the following:

<?php

    namespace App;

    use Illuminate\Notifications\Notifiable;
    use Illuminate\Foundation\Auth\User as Authenticatable;

    class Admin extends Authenticatable
    {
        use Notifiable;

        protected $guard = 'admin';

        protected $fillable = [
            'name', 'email', 'password',
        ];

        protected $hidden = [
            'password', 'remember_token',
        ];
    }

Bloggers model

To make the model for the blogger, run the following command:

php artisan make:model Blogger

Then open the Blogger model and replace with the following:

<?php

    namespace App;

    use Illuminate\Notifications\Notifiable;
    use Illuminate\Foundation\Auth\User as Authenticatable;

    class Blogger extends Authenticatable
    {
        use Notifiable;

        protected $guard = 'blogger';

        protected $fillable = [
            'name', 'email', 'password',
        ];

        protected $hidden = [
            'password', 'remember_token',
        ];
    }

Define the guards
Open config/auth.php and add the new guards edit as follows:

 'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],

        'admin' => [
            'driver' => 'session',
            'provider' => 'admins',
        ],

        'blogger' => [
            'driver' => 'session',
            'provider' => 'bloggers',
        ],
    ],

We added two new guards admin and blogger and set their providers. These providers tell Laravel what to use for authentication or validation when we try to use the guard.

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

        'admins' => [
            'driver' => 'eloquent',
            'model' => App\Admin::class,
        ],

        'bloggers' => [
            'driver' => 'eloquent',
            'model' => App\Blogger::class,
        ],

Modify LoginController

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Auth;

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');
            $this->middleware('guest:admin')->except('logout');
            $this->middleware('guest:blogger')->except('logout');
    }

     public function showAdminLoginForm()
    {
        return view('auth.login', ['url' => 'admin']);
    }

    public function adminLogin(Request $request)
    {
        $this->validate($request, [
            'email'   => 'required|email',
            'password' => 'required|min:6'
        ]);

        if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password], $request->get('remember'))) {

            return redirect()->intended('/admin');
        }
        return back()->withInput($request->only('email', 'remember'));
    }

     public function showBloggerLoginForm()
    {
        return view('auth.login', ['url' => 'blogger']);
    }

    public function bloggerLogin(Request $request)
    {
        $this->validate($request, [
            'email'   => 'required|email',
            'password' => 'required|min:6'
        ]);

        if (Auth::guard('blogger')->attempt(['email' => $request->email, 'password' => $request->password], $request->get('remember'))) {

            return redirect()->intended('/blogger');
        }
        return back()->withInput($request->only('email', 'remember'));
    }
}

Now, Modify RegisterController

Open RegisterController and add these code:

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use App\Admin;
use App\Blogger;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\Request;

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

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

    /**
     * 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:6|confirmed',
        ]);
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showAdminRegisterForm()
    {
        return view('auth.register', ['url' => 'admin']);
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showBloggerRegisterForm()
    {
        return view('auth.register', ['url' => 'blogger']);
    }

    /**
     * @param array $data
     *
     * @return mixed
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);
    }

    /**
     * @param Request $request
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    protected function createAdmin(Request $request)
    {
        $this->validator($request->all())->validate();
        Admin::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);
        return redirect()->intended('login/admin');
    }

    /**
     * @param Request $request
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    protected function createBlogger(Request $request)
    {
        $this->validator($request->all())->validate();
        Blogger::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);
        return redirect()->intended('login/blogger');
    }
}

Next, let us define methods for creating a blogger:

registration is complete.

Set up authentication pages

Laravel’s laravel/ui package provides a quick way to scaffold all of the routes and views you need for authentication using a few simple commands:

composer require laravel/ui --dev

php artisan ui vue --auth

npm install && npm run dev

Open the login.blade.php file and edit as follows:

// resources/views/auth/login.blade.php

<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header"> {{ isset($url) ? ucwords($url) : ""}} {{ __('Login') }}</div>

                <div class="card-body">
                    @isset($url)
                    <form method="POST" action='{{ url("login/$url") }}' aria-label="{{ __('Login') }}">
                    @else
                    <form method="POST" action="{{ route('login') }}" aria-label="{{ __('Login') }}">
                    @endisset
                        @csrf

</div>

We are checking if we passed a URL parameter to the page when we called it. If we did, we modify the forms action to use the URL parameter. We also modified the header of the form so that it shows the type of user based on their login parameter.

Open the register.blade.php file and edit as follows:

// resources/views/auth/register.blade.php

<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header"> {{ isset($url) ? ucwords($url) : ""}} {{ __('Register') }}</div>

                <div class="card-body">
                    @isset($url)
                    <form method="POST" action='{{ url("register/$url") }}' aria-label="{{ __('Register') }}">
                    @else
                    <form method="POST" action="{{ route('register') }}" aria-label="{{ __('Register') }}">
                    @endisset
                        @csrf

</div>

We replicated what we did for login page here.

Create the pages authenticated users will access
Now that we are done setting up the login and register page, let us make the pages the admin and bloggers will see when they are authenticated. Open the terminal and run the following commands to create new files. Next, we will insert the corresponding code snippets to the files.

touch resources/views/layouts/auth.blade.php
touch resources/views/admin.blade.php
touch resources/views/blogger.blade.php
touch resources/views/home.blade.php

Insert this code block into the auth.blade.php file:
// resources/views/layouts/auth.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}" defer></script>

    <!-- Fonts -->
    <link rel="dns-prefetch" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css?family=Raleway:300,400,600" rel="stylesheet" type="text/css">

    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
    <div id="app">
        <nav class="navbar navbar-expand-md navbar-light navbar-laravel">
            <div class="container">
                <a class="navbar-brand" href="{{ url('/') }}">
                    {{ config('app.name', 'Laravel') }}
                </a>
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}">
                    <span class="navbar-toggler-icon"></span>
                </button>

                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                    <!-- Left Side Of Navbar -->
                    <ul class="navbar-nav mr-auto">

                    </ul>

                    <!-- Right Side Of Navbar -->
                    <ul class="navbar-nav ml-auto">
                        <!-- Authentication Links -->
                       <li class="nav-item dropdown">
                            <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
                                Hi There <span class="caret"></span>
                            </a>

                            <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown">
                                <a class="dropdown-item" href="{{ route('logout') }}"
                                   onclick="event.preventDefault();
                                                 document.getElementById('logout-form').submit();">
                                    {{ __('Logout') }}
                                </a>

                                <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
                                    @csrf
                                </form>
                            </div>
                        </li>
                    </ul>
                </div>
            </div>
        </nav>

        <main class="py-4">
            @yield('content')
        </main>
    </div>
</body>
</html>

Next, insert this code block into the admin.blade.php file:

// resources/views/admin.blade.php

@extends('layouts.auth')

@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">
                    Hi boss!
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Open the blogger.blade.php file and edit as follows:

// resources/views/blogger.blade.php

@extends('layouts.auth')

@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">
                    Hi there, awesome blogger
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Finally, open the home.blade.php file and replace with the following:

// resources/views/home.blade.php

@extends('layouts.auth')

@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">
                     Hi there, regular user
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Set up the routes

Our application is almost ready. Let us define the routes to access all the pages we have created so far. Open the routes/web.php file and replace with the following:

/ routes/web.php

<?php
Route::view('/', 'welcome');
Auth::routes();

Route::get('/login/admin', 'Auth\LoginController@showAdminLoginForm');
Route::get('/login/blogger', 'Auth\LoginController@showBloggerLoginForm');
Route::get('/register/admin', 'Auth\RegisterController@showAdminRegisterForm');
Route::get('/register/blogger', 'Auth\RegisterController@showBloggerRegisterForm');

Route::post('/login/admin', 'Auth\LoginController@adminLogin');
Route::post('/login/blogger', 'Auth\LoginController@bloggerLogin');
Route::post('/register/admin', 'Auth\RegisterController@createAdmin');
Route::post('/register/blogger', 'Auth\RegisterController@createBlogger');

Route::view('/home', 'home')->middleware('auth');
Route::view('/admin', 'admin');
Route::view('/blogger', 'blogger');

So, to solve that, open the app/Http/Controllers/Middleware/RedirectIfAuthenticated.php file and replace with this:

// app/Http/Controllers/Middleware/RedirectIfAuthenticated.php


<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class RedirectIfAuthenticated
{
    public function handle($request, Closure $next, $guard = null)
    {
        if ($guard == "admin" && Auth::guard($guard)->check()) {
            return redirect('/admin');
        }
        if ($guard == "blogger" && Auth::guard($guard)->check()) {
            return redirect('/blogger');
        }
        if (Auth::guard($guard)->check()) {
            return redirect('/home');
        }

        return $next($request);
    }
}

The RedirectIfAuthenticated middleware receives the auth guard as a parameter. This middleware is triggered when we try to visit any page meant for authenticated users. We can then determine the type of authentication the user has and redirect them accordingly.

Modify authentication exception handler
There is a little annoying thing that would happen when a user is redirected. You would expect that if a user tries to access say /blogger but is not authenticated, the user is redirected to /login/blogger, yes? Well, they don’t. They get redirected to /login which is not what we want.

To ensure that when a user tries to visit /blogger they are redirected to /login/blogger or the same for /admin, we have to modify the exception handler. Open the handler file in app/Exceptions and add the following:

// app/Exceptions/Handler.php


<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Auth\AuthenticationException;
use Auth;
class Handler extends ExceptionHandler
{
    protected function unauthenticated($request, AuthenticationException $exception)
    {
        if ($request->expectsJson()) {
            return response()->json(['error' => 'Unauthenticated.'], 401);
        }
        if ($request->is('admin') || $request->is('admin/*')) {
            return redirect()->guest('/login/admin');
        }
        if ($request->is('blogger') || $request->is('blogger/*')) {
            return redirect()->guest('/login/blogger');
        }
        return redirect()->guest(route('login'));
    }
}

The unauthenticated method we just added resolves this issue we have. It receives an AuthenticationExpection exception by default which carries that guard information. Sadly, we cannot access that, because it is protected (hopefully, Laravel 6.0 will come with a way to access it).

Run the application
Now that our application is ready, run the following command to get it up:

php artisan key:generate
php artisan serve

It should typically be available on http://localhost:8000.

Remember to visit http://localhost:8000/register/blogger and http://localhost:8000/register/admin to register bloggers and admins respectively. Then visit http://localhost:8000/login/blogger and http://localhost:8000/login/admin to log in the bloggers and admins respectively.

#laravel #php #security #web-development

What is GEEK

Buddha Community

How to use multiple Authentication using guards in Laravel 6?
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