Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5: Redirecting woes

Tags:

laravel

This line works in routes.php:

Route::get('faq', 'HomeController@faq');

So I comment it out and try this: Doesn't work when the user is logged in. It will not redirect into the controller action that works in the aforementioned code:

Route::get('faq', function()
{
    if (Auth::check())
    {
        return redirect()->action('HomeController@faq');
    }
    else
    {
        return Redirect::to('/');
    }
});

Error:

New exception in xxxx.xx
InvalidArgumentException · GET /faq
Action App\Http\Controllers\HomeController@faq not defined.

But the controller and method are clearly there. Obviously I'm doing something wrong.

like image 847
JasonGenX Avatar asked Jun 16 '15 17:06

JasonGenX


1 Answers

You are trying to route something within a route definition itself. That is not how it works.

There are a few ways you could do what you want to achieve. There are pros/cons to each - but they would all work.

Generally the best way is to use some Auth middleware on your route. Laravel 5 includes this out of the box:

Route::group(['middleware' => 'auth'], function () {
    Route::get('faq', 'HomeController@faq');
});

So the user must be logged in to access the FAQ.

Another option is to do Controller Middleware:

Route::get('faq', 'HomeController@faq');

then in your HomeController:

class HomeController extends Controller
{
    public function __construct()
    {   
        $this->middleware('auth', ['only' => ['faq']]);
    }

    public function faq()
    {    
        // Only logged in users can see this
    }
}
like image 53
Laurence Avatar answered Oct 14 '22 15:10

Laurence