search
HomePHP FrameworkLaravelGuardian of laravel world-middleware

Guardian of laravel world-middleware

Dec 06, 2021 pm 05:27 PM
laravelmiddleware

Guardian of laravel world-middleware

Middleware can filter requests. Here you can use middleware to verify whether the user is logged in. If the user is logged in, you can continue to perform the original operation. If you are not logged in, you will be redirected. Go to the login page and let the user log in first.

1. Define middleware

## Through

php artsian make:middleware Command to create middleware, file path: app\Http\Middleware\CheckToken.php

php artisan make:middleware CheckToken
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;

class CheckToken
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
       //在这里做一个判断,如果token不是 &#39;my-secret-token&#39;,则重定向
       if ($request->input(&#39;token&#39;) !== &#39;my-secret-token&#39;) {
            return redirect(&#39;home&#39;);
        }
        return $next($request);
    }
}

2. Classification of middleware

  • Pre-middleware

  • <?php
    namespace App\Http\Middleware;
    use Closure;
    class BeforeMiddleware
    {
        public function handle($request, Closure $next)
        {
             ...
            // 应用请求之前执行一些任务
            return $next($request);
        }
    }
  • ##Post-middleware


    <?php
    namespace App\Http\Middleware;
    use Closure;
    class AfterMiddleware
    {
        public function handle($request, Closure $next)
        {
            $response = $next($request);
            // 应用请求之后执行一些任务
            return $response;
        }
    }
3. Use of middleware

  • Use middleware globally

    //在app\Http\Kernel.php中的$middleware内添加
     protected $middleware = [
            // \App\Http\Middleware\TrustHosts::class,
            ....
            ....
            \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
            //这是之前定义的
            \App\Http\Middleware\CheckToken::class,
        ];
  • Using middleware groups

    //在app\Http\Kernel.php中的$middlewareGroups内添加
      protected $middlewareGroups = [
          &#39;web&#39; => [
               ....
            ],
    
            &#39;api&#39; => [
               ....
            ],
            &#39;diy&#39; =>[
              //可以在web组和api组中添加,也可以自己diy一个
            ]
        ];
    //路由中使用,RouteServiceProvider 默认将 web 和 api 中间件组自动应用到 routes/web.php 和 routes/api.php
    Route::get(&#39;/u&#39;, function () {
    
    })->middleware(&#39;diy&#39;);
  • Using middleware individually

        protected $routeMiddleware = [
             ...,
             &#39;myself&#39;=> \App\Http\Middleware\CheckToken::class,
            ];
    Route::get(&#39;/user&#39;, function () {
        //
    })->middleware(&#39;myself&#39;);
  • Related video tutorial recommendations:
Laravel

Video tutorial

The above is the detailed content of Guardian of laravel world-middleware. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Attaching/Detaching models in Laravel many-to-many relationships.Attaching/Detaching models in Laravel many-to-many relationships.Jul 21, 2025 am 03:54 AM

InLaravel,attachingaddsamany-to-manyrelationshipconnectioninthepivottablewhiledetachingremovesit.1.Attachingusestheattach()methodtocreateapivottableentry,optionallywithextradata.2.Detachingusesdetach()toremoveaconnection,eitherforspecificIDsorall.3.P

How to optimize Laravel performance?How to optimize Laravel performance?Jul 21, 2025 am 03:52 AM

The core of optimizing Laravel performance is to reduce resource consumption, improve response speed, rational use of cache and optimize database queries. 1. Optimize database query: Use with() to preload associated data to avoid executing queries in loops, use select() to specify fields, and enable query log debugging. 2. Reasonable use of cache: cache the entire API response or database results, select a suitable cache driver such as Redis, and set a reasonable cache time. 3. Optimize the code structure and request process: streamline middleware, delay loading service providers, reduce the number of event listeners executions, and avoid writing complex logic in the controller. 4. Use queues to process time-consuming tasks: push tasks to queues, use Redis as queue drivers, and configure multiple ws

What are accessors and mutators in Laravel?What are accessors and mutators in Laravel?Jul 21, 2025 am 03:49 AM

In Laravel, accessors and modifiers are used to format or process model properties when they are acquired or set. 1. Accessors are used to modify the get value of attributes, such as formatting date or merge names, named as get{AttributeName}Attribute; 2. Modifiers are used to modify the stored value of attributes, such as hash password or formatting input, named as set{AttributeName}Attribute; 3. They are suitable for data formatting and simple conversion, but are not suitable for complex business logic; 4. When using it, they should follow naming specifications and pay attention to the consistency of data type processing and output.

Explain different Laravel Caching drivers.Explain different Laravel Caching drivers.Jul 21, 2025 am 03:49 AM

Laravel supports a variety of cache drivers, suitable for different scenarios and performance requirements. 1.File driver is suitable for small applications, with simple configuration but low efficiency, and is not suitable for production environments; 2.Database driver realizes data persistence and sharing, with low performance, and is suitable for scenarios with low performance requirements; 3.Redis driver has high performance, supports distributed architecture and a complete expiration mechanism, and is the first choice for high performance; 4.Memcached driver is lightweight and efficient, suitable for page or object cache, but does not support complex data types; 5.Array driver is used for testing, and is only valid during the request life cycle and does not persist data. Just select the appropriate driver according to the project size and deployment situation.

Deploying a Laravel Application.Deploying a Laravel Application.Jul 21, 2025 am 03:48 AM

When deploying Laravel applications, you need to pay attention to environment configuration, code upload, database settings and task configuration. 1. Prepare the server environment, install PHP (8.0), Composer, Nginx/Apache and MySQL/MariaDB, and configure necessary extensions and services; 2. Upload the project and install dependencies, use FTP or Git to upload code, run composerinstall and generate optimization commands; 3. Configure database information, create database and set permissions, perform migration and seeder, adjust storage/and bootstrap/cache/ permissions; 4. If you use queue or timing tasks, start worker or add Cron entries to

How to use named routes in Laravel?How to use named routes in Laravel?Jul 21, 2025 am 03:45 AM

The core role of named routing in Laravel is to improve maintainability. It allows developers to generate URLs or redirects through names rather than hardcoded paths, and when the path changes, you only need to modify the name binding at the route definition. Use the name() method to name the route. It is recommended to use dot-delimited naming methods such as user.profile to enhance structural clarity. In a Blade template or controller, you can reference a named route through the route() function and pass in an array of parameters to generate a link or redirect it. Notes include avoiding name conflicts, matching parameters by name, and viewing all named routes through phpartisanroute:list.

What is Laravel Livewire?What is Laravel Livewire?Jul 21, 2025 am 03:30 AM

The Livewire component is the basic unit for implementing dynamic front-end interactions in Laravel, which consists of PHP classes and Blade views. 1. PHP class processing logic, such as responding to events or updating data; 2. The Blade view is responsible for rendering HTML and binding interactive behavior. For example, when clicking the "Load More" button, you only need to define the corresponding method in the component to automatically complete AJAX requests and content updates. Common scenarios include: 3. Form verification and submission; 4. Real-time search suggestions; 5. Pagination or loading more; 6. Interactive actions such as likes and collections. The quick steps to get started are: 7. Install the livewire/livewire package through Composer; 8. Run phpartisanlivew

What are service providers in Laravel?What are service providers in Laravel?Jul 21, 2025 am 03:24 AM

Laravel service providers are used to register and configure core services for applications and third-party packages. 1. The main tasks include binding the class to the service container for automatic parsing; 2. Trigger setting logic such as registration event listening, loading configuration, etc.; 3. Applicable to when building packages, binding multiple related services or global settings; 4. The register() method is used to bind services, and the boot() method is used to perform initialization operations. Understanding its role can better organize the structure of the Laravel project.

See all articles

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software