How to use session data (auth) in the Laravel routes page - php

We have a large website with many pages. Almost all of them require the user to log in. Instead of specifying "Auth" on every single page, or on every single controller, I would like to set the routes based on if the user is logged in, like this:
// in web.php
if (Auth::isLoggedIn()) {
Route::get('/', function () { return view('pages/dashboard'); });
... lots more
}
The reason I can't do this is because Auth uses sessions, and sessions are not yet initialized in web.php, since it is done as middleware which is not run yet at this point.
I'm using Laravel 8, I believe.
Thanks.

you can group the route that need the user to be logged in, then use auth middleware
for the grouped routes:
Route::middleware(['auth'])->group(function () {
Route::get('/', function () {
//
});
Route::get('/', function () { return view('pages/dashboard'); });
});

Try using Laravel's Route middleware. Route middleware can be used to only allow authenticated users to access a given route.

Related

get current username in laravel route file without passing from controller

Hello i want to know that how can i access the current username in my laravel route file? i want to add current user name as prefix in my url but i don't want to pass username as parameter for every route call because project is already completed so its is a complex and time consuming task. so please suggest how can I get current username.
Here is my code:
Route::prefix(/Auth::user()->name)->group(function () {
Route::get('/test', 'HomeController#test')->name('test');
});
<a href="{{route('test')}}">
Thanks in advance.
Note:- I don't want to pass username from templates or controller because its complex and time consuming as project is already done.
You can not pass Auth user from routes/web.php , you need to pass paramter in your route .
Route::group(['middleware'=>'auth','prefix'=>'/'],function () {
Route::get({username}, 'HomeController#test');
});
in your controller :
public function test(Request $request,$username){
$user=User::where('name',$username)->first();
if($user){
return response()->json((array('status'=>'success','user'=>$user));
}else{
return response()->json(array('status'=>'error','message'=>'user not found'));
}
}
Routes are registered before Session is initialized. So you can't access the authenticated user in the routes file.
So you have to register new routes with a dummy username prefix as,
Route::prefix('{username}')->group(function () {
Route::get('/test', 'HomeController#index');
});
Just add a param {username} & no need it use anywahere. Keep this route group at the end of the routes file.
Re-generate your routes as,
<a href="{{ url(auth()->user()->name . '/test') }}">

Laravel 5.2 session not persisting

Lately I've been working on a project in Laravel 5.2 and now I'm having problems with sessions not persisting. I've read most of the questions already asked regarding this but everyone has the same answer that I have already tried - applying web middleware.
I've read that there was a new L5.2 update where the web middleware group is already applied by default. I checked my routes with php artisan route:list and I can see that every route has only 1 web middleware applied.
I'm creating session with $request->session()->put('key', 'value') but as soon as I comment that line the session is nowhere to be seen anymore.
Edit
I want to set the session inside a controller when I visit a news page, but I tried it on a simple test route as well. Route where I set this is news/{id} and I want to use it on the front page which is in /
I wish to store recently visited pages in session so I can then show it to the user on the front page.
Session config file I left untouched. So it's using file driver
Here is a tested routes to use for your projects
Please use a middleware instead of the function in the routes file
routes.php
// Only as a demo
// Use a middleware instead
function addToSession ($routeName) {
$visited = session()->get('visited', []);
array_push($visited, $routeName);
session()->put('visited', $visited);
}
Route::get('/', function () {
addToSession('/');
return view('welcome');
});
Route::get('/second', function () {
addToSession('/second');
return view('welcome');
});
Route::get('/third', function () {
addToSession('/third');
return view('welcome');
});
Route::get('/history', function() {
return session()->get('visited');
});
The /history route will return a JSON having the history.

Auth not persisting in Laravel 5.2

I have my auth doing this on login.
if (Auth::attempt($userdata)) {
dd(Auth::user()); //this shows the user just fine,
//which proves that the auth driver is working.
return redirect()->intended('dashboard');
}
However, after redirecting to the dashboard. It appears the auth isn't persisted. If I do dd(Auth::user()) or even just Auth::check() it returns null.
Here's the route:
Route::group(['middleware' => ['web']], function () {
Route::get('test',function(){
dd(Auth::user()); //returns null
echo Auth::user()->name; // returns Trying to get property of non-object
});
});
What am I doing wrong?
The weird thing about this is that last night it was working. It kinda just magically stopped working.
The solution to this is not an obvious one, specially coming from older versions of laravel.
Thanks to this link.
Auth Session killed in Laravel 5.2
I was able to solve it, so I'll post the answer to help others who encounter the same issue.
Originally I just had this in my routes.
Route::post('app/login', 'Auth\AuthController#doLogin');
Route::group(['middleware' => ['web','auth']], function () {
Route::get('test',function(){
dd(Auth::user());// was always returning null
});
});
But, to get the login to persist, I had to do this
Route::group(['middleware' =>[ 'web']], function () {
Route::post('app/login', 'Auth\AuthController#doLogin');
});
Route::group(['middleware' => ['web','auth']], function () {
Route::get('test',function(){
echo Auth::user()->name;
});
});
Apparently any route thats going to call or register a session needs to employ the 'web' middleware.
Just add the "auth" middleware to your "test" route and try accessing it while logged in. It shouldn't give you any errors that way. If you try to access it without logging in, it should redirect you to whatever route is defined in the "auth" middleware.
By using "auth" middleware, you are basically ensuring that Auth::user() will always return a proper User instance.
Now, if this works then you can be sure that Laravel Auth is indeed persisting the user and the issue is somewhere else in your code.
I haven't noticed any issues with the Auth class in Laravel.

How to ensure user is authenticated before he publishes an article in Laravel in the below scenario?

I am developing a simple web blogging application in Laravel 5.1. The application contains two controllers, a UsersController and an ArticlesController.
The authenticate() and check() functions that validate whether the user is authorized to carry out the operation are in the UsersController, and the store(), update() etc. features related to articles are in the ArticlesController.
How am I supposed to call the authenticate() or check() function from ArticlesController before say, store()ing an article to the database?
Laravel uses middleware, in your controller you need to put this
public function __construct(){
$this->middleware('auth'); //Requires auth
}
and in your routes you need to add the code for use middleware in your needed controllers like this
Route::group(['middleware' => 'auth'], function () {
Route::get('/', function () {
// Uses Auth Middleware
});
Route::get('user/profile', function () {
// Uses Auth Middleware
});
});
Read the documentation of Laravel about Middleware you can create more middleware http://laravel.com/docs/master/middleware
You're question is not very clear, but I suppose that you want check if an user is authenticated before storing an article. There are many ways to do it:
Set a middleware in the routing rules of your ArticleController.
Check the authentication in the store method using the "standard" Auth class.
Example:
function store()
{
if (Auth::check())
{
// The user is logged in...
}
}

Laravel 5 multiple "dashboard" route for admins and managers

(I have asked this question before, and did find a way around which worked for a while, but soon got out of hand. So now I am looking for a perfect solution to achieve this, the Laravel way.)
The problem is pretty simple, when admin goes to http://example.com/dashboard they should see the admin dashboard and when manager goes to the same link he should see the managers dashboard.
The way around that I used before was to call the pagecontroller and then depending on the user role call the relevant admin's or manager's dashboard controller.
// ROUTES.php
Route::group(['middleware' => 'auth'], function () {
Route::get('dashboard', 'PagesController#dashboard');
Route::get('users', 'PagesController#manageUsers');
});
// PagesController
public function dashboard(){
if($this->user->isAdmin()){
return $controller = app()->make('App\Http\Controllers\Admin\dashboard')->index();
}
if($this->user->isManager()){
return $controller = app()->make('App\Http\Controllers\Manager\dashboard')->index();
}
}
Now the problem with this approach is that I can no longer call the middleware on the dashboard controller because the process doesn't involve calling the kernel.
I am pretty sure there must be a way to achieve such a basic feature, I would be really grateful if someone can sort this out.
I think the reason this isn't a Laravel default feature because it kinda goes counter to what routes are supposed to represent. In other words, this isn't the Laravel Way. Why not redirect the user depending on their role?
// ROUTES.php
Route::group(['middleware' => 'auth'], function () {
Route::get('dashboard', function() {
if($this->user->isAdmin())
return redirect('/dashboard/admin');
if($this->user->isManager())
return redirect('/dashboard/manager');
return redirect('/home');
});
Route::get('dashboard/admin', 'Admin\dashboard#index');
Route::get('dashboard/manage', 'Manager\dashboard#index');
Route::get('users', 'PagesController#manageUsers');
});

Categories