简体   繁体   English

Laravel中间件工作异常

[英]Laravel middleware working oddly

Surprisingly $this->middleware('guest')->except(['create', 'store']) is not working while $this->middleware('auth')->except(['index', 'show']); 令人惊讶的是$ this-> middleware('guest')-> except(['create','store'])在$ this-> middleware('auth')-> except(['index','show ']); is working perfectly on PostsController. 在PostsController上运行完美。 Both means the same logically, so why the first one is not working? 两者在逻辑上含义相同,那么为什么第一个不起作用? Here is the PostsController: 这是PostsController:

<?php

namespace App\Http\Controllers;

use App\Post;

class PostsController extends Controller
{

    public function __construct() {
      $this->middleware('auth')->except(['index', 'show']);
    }

    public function index() {
      $posts = Post::latest()->get();
      return view('posts.index', compact('posts'));
    }

    public function show(Post $post) {
      return view('posts.show', compact('post'));
    }

    public function create() {
      return view('posts.create');
    }

    public function store() {

      $this->validate(request(), [
        'title' => 'required',
        'body' => 'required'
      ]);

      Post::create([
        'title' => request('title'),
        'body' => request('body'),
        'user_id' => auth()->id()
      ]);

      return redirect('/');
    }
}
$this->middleware('guest')->except(['create', 'store'])

and

$this->middleware('auth')->except(['index', 'show']);

don't mean the same logically. 在逻辑上一样。

The first code block means "Only guests can do all the requests in this controller, except for create and store so everyone can do these requests (as they're not limited to guests only). 第一个代码块的意思是“只有来宾可以在此控制器中执行所有请求,除了创建和存储之外,因此每个人都可以执行这些请求(因为它们不仅限于来宾 )。

The second code block means "Only authenticated users can do all the requests in this controller, except for index and show so everyone can do these requests (guests, authenticated users). 第二个代码块的意思是“只有经过身份验证的用户才能在此控制器中执行所有请求,但索引和显示除外,因此每个人 (访客,经过身份验证的用户) 可以执行这些请求。

This is because in Laravel, no middleware = no filter to anyone. 这是因为在Laravel中,没有中间件=没有针对任何人的过滤器。 except doesn't apply the opposite middleware filter to a route/method. except不会将相反的中间件过滤器应用于路由/方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM