monterico
monterico

Reputation: 380

laravel route callback return controller

hello i'm new to laravel and maybe this is silly for you guys out here. in laravel 8 routing web.php i've created a route like this:

Route::get('/', function () {
    return view('login');
});

Route::post('/auth', 'App\Http\Controllers\SiteController@auth');

Route::get('/home', function () {
    if (session()->has('username')) return view('home');
    else return redirect('/');
});

Route::post('/editprofile', 'App\Http\Controllers\SiteController@edit_profile');

what i want to ask is, can we return the controller from callback like view as well? let's say i want to check the session when user edit his profile. so in route /editprofile, the second parameter isn't 'App\Http\Controllers\SiteController@edit_profile', but a callback function like route '/home'. like this:

Route::post('/home', function () {
    if (session()->has('username')) return controller('App\Http\Controllers\SiteController@edit_profile');
    else return redirect('/');
});

but it returns error haha. let's say i don't want to use the __construct method to check session. is it possible? thanks in advance

Upvotes: 0

Views: 4471

Answers (1)

Michael Mano
Michael Mano

Reputation: 3440

First things first,

Since you are returning from an if statement, no else is required

This

Route::get('/home', function () {
    if (session()->has('username')) return view('home');
    else return redirect('/');
});

Should look like this;

Route::get('/home', function () {
    if (session()->has('username')) {
        return view('home');
    }

    return redirect('/');
});

Second, dont worry about all that if else inside of the route and just pass it to your controller, throw a route middleware on it. Below is the basic auth middleware but you can also create your own

use App\Http\Controllers\UserController;

Route::get('/home', [HomeController::class, 'index'])->middleware('auth');

You can read up more on middlewares here https://laravel.com/docs/8.x/middleware

Upvotes: 0

Related Questions