拉拉维尔如何使中间件重定向



我已经创建了表单供用户在我的帖子中发表评论,但我想在提交表单之前检查身份验证是否登录。我该怎么做?

对我来说,我使用中间件来保护它,但是如果使用不登录它会在用户登录时重定向到登录表单,它不会重定向回帖子路由/show-posts/{post},它会重定向回路由/comments。我该如何解决这个问题?

网址显示单个帖子

Route::get( '/show-post/{post}', 'HomePageController@single_show')
     ->name('home.post.show' );

网址表单 注释表单

Route::resource('/comments', 'CommentsController');

注释控制器

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

您可以创建一个中间件类并像这样重定向:

<?php
namespace AppHttpMiddleware;
use Closure;
use IlluminateSupportFacadesAuth;
class RedirectToComments
{
    /**
     * Handle an incoming request.
     *
     * @param  IlluminateHttpRequest  $request
     * @param  Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::check()) {
            return redirect()->route('comments');
        }
        return $next($request);
    }
}

这是通过中间件重定向的一般形式,只需根据需要修改要重定向到的路由或添加更多条件逻辑即可。

最新更新