Laravel same route, different controller - php

I would like to have general home page
and a different homepage for logged-in users
I search a lot on google but I can't find what to put in my if statement
I tried something like this:
Route::get('/', array('as'=>'home', function(){
if (!Auth::check()) {
Route::get('/', array('uses'=>'homecontroller#index'));
}
else{
Route::get('/', array('uses'=>'usercontroller#home'));
}
}));
I also try with something like:
return Controller::call('homecontroller#index');
but it seems it's not for laravel 4
I tried a lot of other things so I think it's more a misconception problem
If you have any clue
thanks for your help

ok after discussions on this platform and other forums, I come back with a compact solution
Route::get('/', array('as'=>'home', 'uses'=> (Auth::check()) ? "usercontroller#home" : "homecontroller#index" ));

The most simple solution I can think of is:
<?php
$uses = 'HomeController#index';
if( ! Auth::check())
{
$uses = 'HomeController#home';
}
Route::get('/', array(
'as'=>'home'
,'uses'=> $uses
));
Or you can just route the url / to method index() and do the Auth::check() in there.

// routes.php
Route::get('/', 'homecontroller#index');
// homecontroller.php
class homecontroller extends BaseController
{
public function index()
{
if (!Auth:: check()) {
return $this->indexForGuestUser();
} else {
return $this->indexForLoggedUser();
}
}
private function indexForLoggedUser()
{
// do whatever you want
}
private function indexForGuestUser()
{
// do whatever you want
}
}

You should try something like:
Route::get('/', array('as'=>'home', function(){
if (!Auth::check()) {
Redirect::to('home/index'));
}
else{
Redirect::to('user/index'));
}
}));
So you are basically redirecting the user based on the Auth check instead of defining an additional route.
Or use route filters
Route::filter('authenticate', function()
{
if (!Auth::check())
{
return Redirect::to('home/index');
}
});
Route::get('home', array('before' => 'authenticate', function()
{
Redirect::to('user/index');
}));
http://laravel.com/docs/routing#route-filters

Related

Laravel routing with conditions

How does it(route:caching) work under hood and will it breake logic if I cached my routes.
I have a webhook which send me data to one single route. The data are difference only by objects fields. Will it correct to split it to different routes or I am need to make index method which will be redirect my logic by methods
Route::group(['namespace' => 'Webhook'], function () {
if (Request::has('message')) {
Route::post('/', 'WebhookController#message');
}
if (Request::has('callback_query')) {
Route::post('/', 'WebhookController#callback');
}
});
You can shorten the routes code to this:
Route::group(['namespace' => 'Webhook'], function () {
Route::post('/', 'WebhookController#handle');
});
And do the "heavy work" in the controller:
class WebhookController extends Controller
{
public function handle(Request $request)
{
if ($request->has('message')) {
return $this->message();
}
if ($request->has('callback_query')) {
return $this->callback();
}
}
public function message();
public function callback();
}
This is equivalent to:
Route::group(['namespace' => 'Webhook'], function () {
Route::post('/', function(Request $request) {
if ($request->has('message')) {
return (new WebhookController)->message();
}
if ($request->has('callback_query')) {
return (new WebhookController)->callback();
}
});
});
You can use middleware for such kind of logics.
Laravel Middleware

Laravel 5.4 Different routes pointing to different method but the response show the same page

I have an issue with my routes as some with different URLs and differents methods seems to use one method.
routes/web php :
Route::group(['middleware' => ['role:utilisateur,usage']], function()
{
Route::group(['prefix' => 'qcm'], function()
{
Route::get('/', 'ModuleController#index');
Route::get('{id?}', 'ModuleController#qcm');
Route::post('answer', 'ModuleController#putAnswer');
Route::get('result', 'ModuleController#getResult');
Route::get('get-question', 'ModuleController#getQuestion');
});
}
ModuleController.php
class ModuleController extends Controller
{
public function index()
{
return View::make('qcm.index')
}
public function qcm($id)
{
return View::make('qcm.qcm');
}
public function getQuestion()
{
return response()->json(['question' => 'test?']);
}
public function putAnswer(Request $request)
{
return response()->json(["result" => "next"], 200);
}
public function getResult()
{
return View::make('qcm.result');
}
}
When I call test.com/qcm/result or test.com/qcm/get-question, it seems to call test.com/qcm/{id} instead and returns its view and I don't know why as php artisan route:list shows that the routes are pointing to the good methods.
Does anyone knows why my code is producing such results ? Have I missed something ?
Thank you in advance for your help.
Put Route::get('{id?}', 'ModuleController#qcm'); to the end of your route list.
e.g:
Route::group(['middleware' => ['role:utilisateur,usage']], function()
{
Route::group(['prefix' => 'qcm'], function()
{
Route::get('/', 'ModuleController#index');
Route::post('answer', 'ModuleController#putAnswer');
Route::get('result', 'ModuleQCMController#getResult');
Route::get('get-question', 'ModuleController#getQuestion');
Route::get('{id?}', 'ModuleController#qcm');
});
}
Your
Route::get('result', 'ModuleQCMController#getResult');
Calls ModuleQCMController. Shouldn't it be calling ModuleController?
Like this :
Route::get('result', 'ModuleController#getResult');

laravel one route with multiple controllers based on user role

So i'm trying to achieve something, that seems is impossible. I want some routes in my application to use different controller based on user role. This is the approach i'm trying, but it doesn't work well. The user routes work, but admin routes return and Trying to get property on non object error in the VerifyCsrfToken.php file*
Route::group(array('middleware' => 'isAdmin'), function() {
Route::get('/', 'Admin\TestController#getIndex');
});
Route::group(array('middleware' => 'isUser'), function() {
Route::get('/', 'User\TestController#getIndex');
});
My middlewares
public function handle($request, Closure $next)
{
if(Auth::user()->isAdmin()) {
return $next($request);
}
}
public function handle($request, Closure $next)
{
if(Auth::user()->isUser()) {
return $next($request);
}
}
I've seen some handle this kind of situation, by just handling this in the controllers or even checking the use role inside the routes file, but I would rather use middlwares, so my routes file would be cleaner
You can do something like this:
Route::get('/', function () {
if (auth()->check()) {
if (auth()->user()->isAdmin()) {
return redirect()->route('');
} elseif (auth()->user()->isUser()) {
return redirect()->route();
} else {
return view('index');
}
}
return redirect()->to('login');
});
The error message has probably nothing to do with the code your show.
But using multiple controllers on one route is impossible, I asked the same question once.
But you could just use one controller and handle the authorization in that controller.
For example:
public function getIndex()
{
if(Auth::user()->isAdmin()) {
//Admin
return $this->getAdminIndex();
} else {
//No admin
return $this->getUserIndex();
}
}
protected function getAdminIndex()
{
return view('admin.index');
}
protected function getUserIndex()
{
return view('user.index');
}
But the cleanest way to do it is to just have 2 routes.

Redirecting user to a specific page

I'm using Laravel 5.3 and Auth by default with this roles package. How can i do the normal user redirection after the user login if i have similar roles and also pages for them. For example i have AdminRole and after the Login i want to redirect user to /admin/dashboard.
I have tried something like this in the LoginController but it doesn't make sense:
protected function redirectTo()
{
if (Auth::user()->isRole('admin'))
return redirect()->route('admin');
return redirect()->route('home');
}
Or maybe there is a better way to use middleware for redirecting?
Here is my routes (web.php):
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController#index');
Route::resource('company', 'CompanyController');
Route::group(['prefix' => 'admin'], function () {
Route::get('login', function () {
return view('admin.pages.admin-login');
});
Route::group(['middleware' => 'role:admin'], function () {
Route::get('/', function () {
return view('admin.admin-main');
});
});
});
use it like this way:
return Redirect::to('admin');
And note that:
route:Route::get('company', 'CompanyController#show');
controller:
this works fine:
function show(){
return Redirect::to('home');
}
but this not
function show(){
$this->redirectto();
}
function redirectto()
{
return Redirect::to('home');
}
route.php
Route::get('home', ['as' => 'admin_home', 'uses' => 'HomeController#index']);
Route::get('login'['as'=>'admin_login','uses'=>'LoginController#admin_login']);
LoginController.php
use Illuminate\Support\Facades\Redirect;
public function index(){
$User=new User();
if(isset(AUTH::user()->id)){
$User->id=AUTH::user()->id;
$auth_user_role=$User->auth_user_role();
$rl_title=$auth_user_role[0]->rl_title;
if(isset(Auth::user()->id) && isset($rl_title) && $rl_title == 'Admin'){
return view('home.admin',$this->param);
}
else if(isset(Auth::user()->id) && isset($rl_title) && $rl_title == 'Moderator'){
return view('home.moderator',$this->param);
}
else{
return Redirect::route('admin_login');
}
}else{
return Redirect::route('admin_login');
}
}
Views
-> views
-> home
-> admin.blade.php
-> member.blade.php
I needed to do something like this in Auth/LoginController:
protected function authenticated()
{
if(Auth::user()->isRole('admin')) {
return redirect()->intended('/admin');
}
return redirect()->intended('/home');
}

Laravel 5.1 page authentication using routes

I'm working on a site that needs an admin panel. I am currently trying to set up the authentication of that panel, though I can not find a way to deny access from any guest users (non-admins). I have a login page, of course, and after login, it routes to the admin page, though you can also go to /admin when you're not logged in.
routes.php :
Route::get('home', function(){
if (Auth::guest()) {
return Redirect::to('/');
} else {
return Redirect::to('admin');
}
});
Route::get('admin', function () {
return view('pages.admin.start');
});
MainController.php :
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
class MainController extends Controller {
public function getIndex() {
return view('pages.index');
}
public function getAbout() {
return view('pages.about');
}
public function getPortfolio() {
return view('pages.portfolio');
}
public function getShop() {
return view('pages.shop');
}
public function getContact() {
return view('pages.contact');
}
/*public function getAdmin() {
return view('pages.admin.start');
}*/
}
I could really use some help here, because I'm totaly stuck, and yes, I have read the documentation, though maybe I'm just missing something.
Assuming you have a line like this:
'auth' => 'App\Http\Middleware\Authenticate',
in your app/Http/Kernel.php file:
put all the routes you need "authenticated" inside the grouping, but keep the "guest" routes outside of them :
Route::get('home', function(){
if (Auth::guest()) {
return Redirect::to('/');
} else {
return Redirect::to('admin');
}
});
Route::group( ['middleware' => 'auth' ], function(){
Route::get('admin', function () {
return view('pages.admin.start');
});
Route::just-another-route()...;
Route::just-another-route()...;
});
Documentation: http://laravel.com/docs/5.1/routing#route-groups
You should use a Middleware to handle authentication of your users
1) First you have to create a middleware that will check if the user requiring the page is an admin, and if not you have to redirect; something like this:
class AdminMiddleware
{
public function handle(Request $request, Closure $next )
{
//if User is not admin
//redirect to no permess
return $next($request);
}
}
2) Then you have to bind the middleware to the routes you want to be accessible only from an admin user:
//bind the middleware to all the routes inside this group
Route::group( ['middleware' => 'adminmiddleware' ], function()
{
Route::get('admin', function () {
return view('pages.admin.start');
});
//other routes
});

Categories