Chando
Chando

Reputation: 434

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']);
}

Upvotes: 2

Views: 4724

Answers (1)

user320487
user320487

Reputation:

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.

Upvotes: 1

Related Questions