Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use Laravel Guards

Shulou Source: shulou.com Published: 2022-06-02 07:32:46 09月17日 Update

This article mainly explains "how to use Laravel Guards". Friends who are interested might as well take a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn how to use Laravel Guards.

One of the most common features of Laravel is to authenticate persistent users, in which case these functions are stored in any supported database (MySQL, SQLite, etc.), which is amazing when you consider that you can set up a web application in minutes and authenticate users with forgotten passwords and all adjustments. What happens when you need something more complicated?

For example, what if you need multiple user types with your own authentication portal? These different types of users can be customers, vendors, and administrators. Such a mechanism may soon become very chaotic, I know, because I have experienced it before. We usually plan the structure of the database in advance, but do not build what our authentication processes and mechanisms look like.

What is Guards?

Guards in Laravel is a mechanism through which your application can know whether someone or even something has been authenticated. When we look at the default installation of Laravel, we usually see a guard, web. When a visitor authenticates with this guard, any use of auth middleware will allow the user to view the page, because the default protection is always web out of the box. If a person is browsing and is not authenticated at any time, they are called visitors in the guard.

Typically, when additional protection is added to a Web application, it provides different authentication mechanisms for API, such as user tokens. However, this default guard does not have to be the only Web guard in your application. In fact, we can set a Guard for different user types, even those who do not authenticate with traditional usernames and passwords.

How do I create a new Authenticatable for the Eloquent provider?

To demonstrate how to create a new Authenticatable, we will use an example of a page through which customers of orders can authenticate. Customers can only use the signed URL to authenticate the application, and once authenticated, they can perform other actions, such as canceling the order.

First, let's create a new model:

Php artisan make:model Order

Now we need to modify the Order model in app/Models/Order.php to add some interfaces and traits. This satisfies that the Order model can be used for guardians and Eloquent provider types.

Order.php

Tags: Authentication identity middleware orders customers users programs passwords applications methods models applications configurations kernels parameters routing parts mechanisms protection differences Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology Linux Docker macOS OPPO Reno