Different view / method based on middleware using the same route in Laravel - laravel

I want to redirect logged in users to the '/' route (like example.com, without anything behind it)
This works:
Route::get('/', Home::class)->name('home');
class Home extends Controller
{
public function __invoke()
{
if(Auth::check()) {
return view('dashboard');
}
else {
return view('welcome');
}
}
}
But now I need to add middleware to this route / controller.
Documentation suggests adding $this->middleware(['auth', 'verified']) to the __constructor in my Home controller.
This doesn't work because it also affects the view for guests (return view('welcome');)
I also tried:
Route::get('/', [Home::class, 'index'])->name('home');
class Home extends Controller
{
public function __construct()
{
$this->middleware(['auth', 'verified'])->only('dashboard');
}
public function index()
{
if(Auth::check()) {
$this->dashboard();
}
else {
$this->welcome();
}
}
public function welcome()
{
return view('welcome');
}
public function dashboard()
{
return view('dashboard');
}
}
But this doesn't work either. Any ideas?

I found this question when Googling for something similar, so I'm writing this for such people, sorry.
This looks like a very old version of Laravel that I'm not familiar with (and it's probably no longer supported), so I'll give my answer for Laravel 9.
To return different views, depending on whether they're logged in, use
// routes/web.php
Route::get('/home', function() {
if (Auth::check()) {
return view('dashboard');
} else {
return view('welcome');
}
});
If you have to use the result of some other policy and call controller methods, use
// routes/web.php
use App\Http\Controllers;
use Illuminate\Support\Facades\Gate;
Route::get('/settings', function () {
if (Gate::allows('manageSystem')) {
return (new Controllers\SettingsController)->index();
} else {
return (new Controllers\UserController)->settings();
}
});
I haven't had a change to test this, but I hope this helps someone

Related

Laravel - how can I return view from another function

Route:
Route::controller(PublicController::class)->group(function () {
Route::get('/index', 'index')->name('public.index');
});
View:
index.blade.php
wrong_browser.blade.php
In controller, this way is ok:
class PublicController extends Controller
{
public function index(Request $request)
{
if(is_wrong_browser)
return view(public.wrong_browser);
return view('public.index');
}
}
But how can I return view from another function, like this, without making a new route:
class PublicController extends Controller
{
public function index(Request $request)
{
$this->CheckBrowser();
return view('public.index');
}
public function CheckBrowser()
{
if(is_wrong_browser)
return view(public.wrong_browser);
}
}
You can use the method redirect.
return redirect()->route('index');
You could use middleware which you either define globally, or on specific routes.
class CheckUserActive
{
public function handle($request, Closure $next)
{
// determine value of $is_wrong_browser
$is_wrong_browser = true;
if ($is_wrong_browser) {
return redirect()->route('is-wrong-browser-route');
}
return $next($request);
}
}
It is bad practice to return a view from middleware instead redirect your user to another route.
Alternatively, you could have a base Controller that your Controllers extend which has the checkBrowser function defined on it and the extending Controllers therefore have access to:
class WrongBrowserController extends \App\Http\Controllers\Controller
{
public function checkBrowser()
{
// determine value of $is_wrong_browser
$is_wrong_browser = true;
if ($is_wrong_browser)
{
return view('wrong-browser-view');
}
}
}
class PublicController extends WrongBrowserController
{
public function index(Request $request)
{
$this->checkBrowser();
return view('index');
}
}

Beginner in Laravel not working my routes inside middleware guest, and middleware auth all routes working well

This is all my routes inside web.php
Route::get('/', function(){
return view('welcome-body');
});
Auth::routes();
Route::get('/dashboard', 'HomeController#index')->name('userdashboard')->middleware('auth');
// Route::post('logout', 'Auth\LoginController#logout')->name('logout');
// Route::get('logout', 'Auth\LoginController#logout');
Route::get('logout','Auth\LoginController#logout');
Route::group(['middleware' => ['guest']], function ()
{
// About dropdown pages route
Route::get('/office-mayor', 'WebController#officemayor_about_page');
Route::get('/organizational-chart', 'WebController#organizationalchartpage');
Route::get('/directory', 'WebController#directorypage');
Route::get('/barangays', 'WebController#barangayspage');
Route::get('/barangays-detail', 'WebController#barangays_detail_page');
Route::get('/history', 'WebController#historypage');
// Stories & News dropdown pages route
Route::get('/stories', 'WebController#storiespage');
Route::get('/stories-detail', 'WebController#storiesdetailspage');
Route::get('/news', 'WebController#newspage');
Route::get('/news-detail', 'WebController#newsdetailspage');
Route::get('/gallery', 'WebController#gallerypage');
Route::get('/videos', 'WebController#videospage');
Route::get('/bids-and-awards', 'WebController#bidsandawardspage');
// Transparency route
Route::get('/transparency', 'WebController#transparencypage');
// Covid-19 update route
Route::get('/covid-updates', 'WebController#covidupdatespage');
});
Route::group(['middleware' => ['auth']], function ()
{
Route::get('authors/table', 'AllSystemController#indexauthorsdata')->name('authors.table');
Route::get('/authors/add', 'AllSystemController#createviewauthors')->name('create.authors');
Route::post('/authors/authorsdata/submit', 'AllSystemController#submitauthors')->name('submit.authors.data');
Route::get('/authors/view/{id}', 'AllSystemController#showviewauthors')->name('view.authors.data');
Route::get('/authors/edit/{id}', 'AllSystemController#editviewauthors')->name('edit.authors');
Route::patch('/authors/{id}', 'AllSystemController#updateauthordata')->name('update.authors.data');
Route::get('stories/table', 'AllSystemController#indexstoriesdata')->name('stories.table');
Route::get('/stories/add', 'AllSystemController#createviewstories')->name('create.stories');
Route::post('/stories/storiesdata/submit', 'AllSystemController#submitstories')->name('submit.stories.data');
Route::get('/stories/view/{id}', 'AllSystemController#showviewstories')->name('view.story.data');
Route::get('/stories/edit/{id}', 'AllSystemController#editviewstories')->name('edit.stories');
Route::patch('/stories/{id}', 'AllSystemController#updatestorydata')->name('update.story.data');
Route::get('activities/table', 'AllSystemController#indexactivitiesdata')->name('activities.table');
Route::get('/activities/add', 'AllSystemController#createviewactivities')->name('create.activities');
Route::post('/activities/activitiesdata/submit', 'AllSystemController#submitactivities')->name('submit.activities.data');
Route::get('/activities/view/{id}', 'AllSystemController#showviewactivities')->name('view.activity.data');
Route::get('/activities/edit/{id}', 'AllSystemController#editviewactivities')->name('edit.activities');
Route::patch('/activities/{id}', 'AllSystemController#updateactivitydata')->name('update.activity.data');
Route::get('blogs/table', 'AllSystemController#indexblogsdata')->name('blogs.table');
Route::get('/blogs/add', 'AllSystemController#createviewblogs')->name('create.blogs');
Route::post('/blogs/blogsdata/submit', 'AllSystemController#submitblogs')->name('submit.blogs.data');
Route::get('/blogs/view/{id}', 'AllSystemController#showviewblogs')->name('view.blog.data');
Route::get('/blogs/edit/{id}', 'AllSystemController#editviewblogs')->name('edit.blogs');
Route::patch('/blogs/{id}', 'AllSystemController#updateblogdata')->name('update.blog.data');
Route::get('news/table', 'AllSystemController#indexnewsdata')->name('news.table');
Route::get('/news/add', 'AllSystemController#createviewnews')->name('create.news');
Route::post('/news/newsdata/submit', 'AllSystemController#submitnews')->name('submit.news.data');
Route::get('/news/view/{id}', 'AllSystemController#showviewnews')->name('view.new.data');
Route::get('/news/edit/{id}', 'AllSystemController#editviewnews')->name('edit.news');
Route::patch('/news/{id}', 'AllSystemController#updatenewdata')->name('update.new.data');
Route::post('/storiesgallery/submit', 'AllSystemController#submitstoriesgallery')->name('add.stories.galleries');
Route::post('/activitiesgallery/submit', 'AllSystemController#submitactivitiesgallery')->name('add.activities.galleries');
Route::post('/blogsgallery/submit', 'AllSystemController#submitblogsgallery')->name('add.blogs.galleries');
Route::post('/newsgallery/submit', 'AllSystemController#submitnewsgallery')->name('add.news.galleries');
Route::get('contact_us', 'AllSystemController#indexcontactus')->name('sending.mail');
Route::post('contact_us/submit', 'AllSystemController#submitcontactus')->name('sending.mail');
});
and this is my Controller WebController
public function __contruct()
{
$this->middleware('guest');
}
// TOP BAR PAGES
public function officemayor_about_page()
{
return view('web-routes.about.office-mayor');
}
public function organizationalchartpage()
{
return view('web-routes.organizational.organizational-chart');
}
public function directorypage()
{
return view('web-routes.about.directory');
}
public function barangayspage()
{
return view('web-routes.about.barangays');
}
public function barangays_detail_page()
{
return view('web-routes.about.barangays-detail');
}
public function historypage()
{
return view('web-routes.about.history');
}
public function storiespage()
{
return view('web-routes.stories.stories');
}
public function storiesdetailspage()
{
return view('web-routes.stories.stories-detail');
}
public function newspage()
{
return view('web-routes.news.news');
}
public function newsdetailspage()
{
return view('web-routes.news.news-detail');
}
public function gallerypage()
{
return view('web-routes.gallery.gallery');
}
public function videospage()
{
return view('web-routes.video.videos');
}
public function bidsandawardspage()
{
return view('web-routes.bids_awards.bids-and-awards');
}
public function officemayorpage()
{
return view('web-routes.office-mayor.office-mayor');
}
public function covidupdatespage()
{
return view('web-routes.covid-updates.covid-updates');
}
public function transparencypage()
{
return view('web-routes.transparency.transparency');
}
if i want to go in the page example /office-mayor its return like this
error:
This page isn’t working right now localhost can't currently handle this request.
HTTP ERROR 500
I already use config:cache, route:cache and dump-autoload but doesn`t work it
How can i fix this...
I think this is happening because you have misspelled constructor it should be like public function __construct() and you don't have to define middleware in your constructor because you have already used it in routes.

How to get route parameter on difference function on laravel?

I have a problem in my project laravel, I want to get route parameter 'id_project' on route 'project' to use in route 'modulproject'. This route in one view.
This is my Route:
Route::get('project/{id_project}','ProjectDetailController#project');
Route::get('modulproject','ProjectDetailController#modulproject');
This is my Controller:
public function project($id_project)
{
$project=Project::where('id','=',$id_project);
return($project);
}
public function modulproject($id_project)
{
$modulproject=Modul::where('id_project','=',$id_project);
return($modulproject);
}
You can used Session to get that id_project.
use Session;
public function project($id_project)
{
Session::put('id_project',$id_project);
$project=Project::where('id','=',$id_project);
return($project);
}
public function modulproject()
{
if(Session::has('id_project')){
$modulproject=Modul::where('id_project','=',Session::get('id_project'));
Session::forget('id_project');
return($modulproject);
}
else{
return 'redirect to other page.. (custom)';
}
}

if esle condition not working inside constructor for middleware in laravel 5.4

I can use only one middleware at a time..inside a constructor..I want to use if else condition inside constructor or two middleware.
I can use only only middleware inside constructor & if else condition also not working
Example are follows
If else
class HRJob extends Controller
{
public function __construct()
{
if(Auth::guard('admin'))
{
$this->middleware('auth:admin');
}
else
{
$this->middleware('auth');
}
}
public function userdetails()
{
dd(Auth::user());
}
}
Two middleware
class HRJob extends Controller
{
public function __construct()
$this->middleware('auth:admin');
$this->middleware('auth');
}
public function userdetails()
{
dd(Auth::user());
}
}
in your case, there is no need for two middleware.
public function __construct()
{
$this->middleware('auth');
}
is equivalent to whatever you are trying to do since 'auth' is still valid for 'auth:admin'.
but you can still put your middleware in the Routes files (web.php/api.php) like this
Route::group(['middleware'=>'auth:admin'],function (){
Route::get('/', 'HRJob#userdetailsAdmin');
});
Route::group(['middleware'=>'auth'],function (){
Route::get('/', 'HRJob#userdetails');
});
hope this helps.
---edit---
in your case, with two different table for auth and without creating a custom middleware for a "any auth", you are just missing the check() method:
if (Auth::guard('admin')->check()) {
$this->middleware('auth:admin');
} else {
$this->middleware('auth');
}
wich is equivalent to
if (!Auth::guard('admin')->check()) {
$this->middleware('auth');
}

Laravel return Redirect::to not working outside action

I got a weird redirect not working if I put the redirect outside the action. for example :
below code is working
Route::get('/', 'HomeController#index');
public function index()
{
if (Auth::check())
{
$this->user_id = Auth::id();
}
else
{
return Redirect::to('/');
}
// code after check
}
but if I take it out like below, the redirect won't work. It doesn't redirect at all.
Route::get('/', 'HomeController#index');
public function index()
{
$this->authorize();
// code after check
}
private function authorize()
{
if (Auth::check())
{
$this->user_id = Auth::id();
}
else
{
return Redirect::to('/');
}
}
Now if I have to keep using if statement in every action, it will be troublesome. Instead, I will need to call just $this->authorize();
Any idea why it wouldn't work?
You are not returning the result of "return Redirect::to('/');"
Try this:
public function index()
{
return $this->authorize();
}
Just an extra. It seems to be a bad way if I am using the idea of my question. Laravel actually provide routes protection. So, now I change my code with following step :
in app/filter.php change the redirect to which routes you want.
Route::filter('auth', function()
{
if (Auth::guest()) return Redirect::guest('/');
});
In your route protect use following code :
Route::get('/', 'HomeController#index');
Route::group(array('before' => 'auth'), function()
{
// The list of routes you want to protect with authentication
Route::get('blabla', 'BlablaController#index');
}
Remove the authorize function on BlablaController
On index function change it as follow :
public function index()
{
$this->user_id = Auth::id();
// code after check
}
Now it will automatically redirect to '/' if its not authenticated
Yes. The auth filter is the best way to implement authentication.
Also, you can make your routes.php easier to read if you use the 'Route:when' to set your filters, like this:
Route::when('path/*', 'auth');
With this, you can minimize writing array('before' => 'auth') on your Route statements.

Resources