简体   繁体   中英

laravel how to make middleware redirect

I have create form for user to comment in my post but I want need check Auth has Login before submit the form. How can i do that ?

For me I have use middleware to protect it, But If use not login it redirect to Login Form when user has been login it is not redirect back to posts route /show-posts/{post} ,It redirect to back to route /comments . How can i solve this ?

URL Show Single Post

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

URL form Comments form

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

CommentsController

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

You can create a middleware class and redirect like so:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class RedirectToComments
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $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);
    }
}

That is the general form of redirection through middleware, simply modify which route to redirect to or add more conditional logic as needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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