Mrinal Raj

Mrinal Raj

1570696977

Laravel 6 Auth Redirection Using redirectTo

Most of the times, the authentication system provided by Laravel 6 is enough for adding login and registration to your web application.

The auth scaffolding which is now moved to a separate laravel/ui package provides out of the box routes and views for the LoginController, RegisterController, and ResetPasswordController which are included in your project and are responsible for providing the functionality of the auth system.

If you take a look at the app/Http/Controllers/Auth/LoginController.php file, for example, you would find the following code:

<?php

namespace App\Http\Controllers\Auth;

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

class LoginController extends Controller
{

    use AuthenticatesUsers;

    protected $redirectTo = '/home';

    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }
}

You can see that a $redirectTo variable exists and has the value of /home where users are redirected after they are logged in.

In the Laravel built-in authentication system, you can customize many sides such as the redirection route using the $redirectTo variable which exists in both the login and registration controllers.

If you want to redirect your users to different routes other than the default ones after they register or login, you simply need to change the value of $redirectTo.

Now, what if you want to redirect users to a route depending on some user criteria such as their role?

The Laravel auth system also covers that by providing a redirectTo() method that you can use instead of a $redirectTo variable.

Let’s take this example of the LoginController of our CRM application by adding the redirectTo() method to redirect the admin users to a different route other than the /home route:

<?php

namespace App\Http\Controllers\Auth;

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

class LoginController extends Controller
{
    use AuthenticatesUsers;

    protected $redirectTo = '/home';
    protected function redirectTo()
    {
        if (auth()->user()->role == 'admin') {
            return '/admin';
        }
        return '/home';
    }

    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }
}

We also need to do that in the registration controller. Open the app/Http/Controllers/Auth/RegisterController.php file and update it as follows:

<?php

namespace App\Http\Controllers\Auth;

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

class RegisterController extends Controller
{
    use RegistersUsers;

    protected $redirectTo = '/home';
    protected function redirectTo()
    {
        if (auth()->user()->role == 'admin') {
            return '/admin';
        }
        return '/home';
    }

    public function __construct()
    {
        $this->middleware('guest');
    }

    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'],
        ]);
    }

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

You can either remove the $redirectTo variable or leave it as it will be simply overridden by the redirectTo() method.

Now, all you need is to create an /admin route along with an AdminController. Head back to your terminal and run the following artisan command:

$ php artisan make:controller AdminController

Next, open the app/Http/Controllers/AdminController.php file and update it as follows:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class AdminController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        return "Hello, admin!";
    }
}

Next, open the routes/web.php file and add a route to the admin controller as follows:

Route::get('/admin', 'AdminController@index')->name('admin');

Conclusion

In this tutorial, we’ve implemented redirection in our Laravel 6 CRM app so admin users are redirected to a different route while the normal users are redirected to the home route. Redirection doesn’t enforce any security rules because the normal users will still be able to visit the /admin route. We need to prevent that using a middleware which is the subject of the next tutorial.

#laravel #security #php

What is GEEK

Buddha Community

Laravel 6 Auth Redirection Using redirectTo
Gordon  Taylor

Gordon Taylor

1614840465

How to Create User Authentication in Laravel 8 Using UI Auth Package

Laravel provides user authentication package to manage complete authentication like User Register, Login, Forgot Password, Email Verification. UI Auth…

You can create and manage authentication in Laravel 8 easily using inbuilt packages. User authentication is always the most important concern of any web application. If you want to handle the application functionalities and roles then it always requires a user module. On the basis of the user, you can manage the rights of access in the application. I already shared a post on one of the latest features of Laravel 8 for managing authentication using Jetstream and Livewire. In this post, I will show you how you can create authentication without using Jetstream. I will be going to use the Laravel UI package. Here, I will be starting with a new project in Laravel 8. So, let’s start.

#laravel 8 #auth package in laravel #laravel auth #ui auth in laravel #ui vue auth in laravel #user authentication in laravel

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

1597487833

Country State City Drop Down List using Ajax in Laravel

Here, i will show you how to create dynamic depedent country state city dropdown list using ajax in laravel.

Country State City Dropdown List using Ajax in php Laravel

Follow Below given steps to create dynamic dependent country state city dropdown list with jQuery ajax in laravel:

  • Step 1: Install Laravel App
  • Step 2: Add Database Details
  • Step 3: Create Country State City Migration and Model File
  • Step 4: Add Routes For Country State City
  • Step 5: Create Controller For Fetch Country State City
  • Step 6: Create Blade File For Show Dependent Country State City in Dropdown
  • Step 7: Run Development Server

https://www.tutsmake.com/ajax-country-state-city-dropdown-in-laravel/

#how to create dynamic dropdown list using laravel dynamic select box in laravel #laravel-country state city package #laravel country state city drop down #dynamic dropdown country city state list in laravel using ajax #country state city dropdown list using ajax in php laravel #country state city dropdown list using ajax in laravel demo

Gordon  Taylor

Gordon Taylor

1614859140

Create Authentication in Laravel 8 Using Laravel Breeze Auth Package

Laravel Breeze authentication provides a clean and quite simple auth scaffolding. The UI is managed by the Tailwind CSS. But, you can manage everything like.

User authentication is always a challenging part of any application. But, if you are using Laravel then no need to worry. There are lots of packages are available in Laravel for authentication. After releasing the Laravel 8, one most powerful feature has been added for authentication. The package is Jetstream. You can use Jetstream with Livewire and Jetstream with Inertia Js. Jetstream provides complete authentication for the user with lots of other functionalities. These are the advanced features added by the Laravel team inside the Jetstream. People did lots of comments regarding this awesome feature that they are not able to use all these functionalities in the same package. So, Taylor Otwell introduced the Laravel Breeze package for authentication. This is pretty clean and simple to use.

If you don’t want to use the Jetstream authentication then you can go with the Laravel Breeze. In this tutorial, I will be showing you the authentication using the Laravel Breeze auth package.

#laravel 8 #breeze auth scaffolding #laravel 8 auth scaffolding #laravel auth #user authentication in laravel

Seamus  Quitzon

Seamus Quitzon

1594682206

Laravel detect mobile device and redirect mobile website htaccess

In this article, i will let you know laravel detect mobile device and redirect mobile website. So let’s see how can we detect mobile device and redirect website to the mobile website.

A web application can be open on desktops, laptops, tablets and mobiles. But a large application should be optimized for all devices means if we open it on desktop, there might be heavy resources used that would be not compatible for mobile devices. So we can redirect this website to mobile website or mobile freindly website. We generally see that if we open a website on mobile device, it redirects to like http://m.domain.com.

Here, in this article we will see two seperate example to implement this. First one would be using .htaccess file and second one is using laravel route.

Example 1: Using .htaccess file

For detacting mobile device and redirect to the mobile website, we will need to create a .htaccess file on root directory of application. So create this .htaccess file and update the following lines of code.

RewriteEngine On
RewriteCond %{QUERY_STRING} !^desktop
RewriteCond %{HTTP_USER_AGENT} "android|blackberry|googlebot-mobile|iemobile|iphone|ipod|#opera mobile|palmos|webos" [NC]
RewriteCond %{HTTP_USER_AGENT} "acs|alav|alca|amoi|audi|aste|avan|benq|bird|blac|blaz|brew|cell|cldc|cmd-" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "dang|doco|eric|hipt|inno|ipaq|java|jigs|kddi|keji|leno|lg-c|lg-d|lg-g|lge-" [NC,OR]
RewriteCond %{HTTP_USER_AGENT}  "maui|maxo|midp|mits|mmef|mobi|mot-|moto|mwbp|nec-|newt|noki|opwv" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "palm|pana|pant|pdxg|phil|play|pluc|port|prox|qtek|qwap|sage|sams|sany" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "sch-|sec-|send|seri|sgh-|shar|sie-|siem|smal|smar|sony|sph-|symb|t-mo" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "teli|tim-|tosh|tsm-|upg1|upsi|vk-v|voda|w3cs|wap-|wapa|wapi" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "wapp|wapr|webc|winw|winw|xda|xda-" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "up.browser|up.link|windowssce|iemobile|mini|mmp" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "symbian|midp|wap|phone|pocket|mobile|pda|psp" [NC]
RewriteRule ^$ http://m.domain.com [L,R=302]

Example 2: Using Laravel Routes

After doing this through .htaccess, we can also detect mobile device and redirect to mobile site using laravel routes.

For doing this, we will need to create laravel routes and will need to add some lines of code to do this as written below.

function isMobile() {
    if(isset($_SERVER['HTTP_USER_AGENT'])) {
    $useragent=$_SERVER['HTTP_USER_AGENT'];
    if(preg_match('/(tablet|ipad|amazon|playbook)|(android(?!.*(mobi|opera mini)))/i', strtolower($useragent))) {
        return true ;
    } ;

    if(preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i',$useragent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i',substr($useragent,0,4))){
            return true ;
        }
    }
    return 0 ;
}
if(isMobile()) {
    include_once(app_path().'/routes/mobile_routes.php');
} else {
    require_once(app_path().'/routes/website_routes.php');
}

From both of the above methods, we can detect mobile device and redirect to their specific version of website. You can choose any of these two methods.

#laravel #detect devices in laravel #how to detect mobile device in laravel #how to redirect to a mobile device #laravel detect mobile device and redirect mobile website htaccess #laravel mobile redirection