Reputation: 8482
I want to add a functionality on my web app where users visit the same URL and get different pages depending if they are logged in or not. The way I'm doing this now is using a middleware to redirect logged in users to /home. But, I want to do something like facebook does..
When someone types http://facebook.com, it analyzes if the person is logged in, if they are, it shows their home, if they are not, it shows the registration page on the same URL (you can see that the address in the bar does not change)
I'm trying to use this code on my route:
Route::get('/', array('as'=>'home', 'uses'=> (Auth::check()) ? "usercontroller@home" : "homecontroller@index" ));
Found Here: https://stackoverflow.com/a/18896113/2724978
But it just shows the second controller method ("homecontroller@index") no matter if the user is logged in or not.
Upvotes: 1
Views: 3466
Reputation: 77
here is exactly what you want:
Route::get('/', function() {
$guest = Auth::guest();
if($guest)
{
$controller = $this->app->make('App\Http\Controllers\TaskController');
return $controller->callAction('guest', $parameters = array());
}
else
{
$controller = $this->app->make('App\Http\Controllers\TaskController');
return $controller->callAction('user', $parameters = array());
}
});
Just replace the names with yours. Tested on: Laravel Framework version 5.1.35 (LTS).
Should be improved further by looking at the namespacing. Did came up with a better solution using middleware - but didn't save it and can't recreate it now.
Answer derived from/based on: Laravel single route point to different controller depending on slugs http://laravel.io/forum/10-16-2014-l5-controller-does-not-exist
Upvotes: 1
Reputation: 11494
Is it just me or can't you just do as @AJReading has suggested and use an ordinary controller method to handle this?
Set up like so:
In your HomeController.php
:
class HomeController extends Controller
{
/**
* Show a different view depending on whether or not the user is logged-in.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
if (Auth::check()) {
// logged-in
return view('home.index.authorised')->with('user', Auth::user());
} else {
// not logged-in
return view('home.index.guest');
}
}
}
Then create your alternate views e.g. resources/views/home/guest.blade.php
Upvotes: 2