Laravel - new guard issue - laravel

I am using Laravel/Fortify to manage my authentication. I have created a new guard to allow employees to log in.
Employee credentials now work but whenever I tried and retrieve the authenticated employees details via {{ Auth::user() }} it returns null.
Any ideas?

composer require laravel/fortify
php artisan vendor:publish --provider="Laravel\\Fortify\\FortifyServiceProvider"
php artisan migrate
Open config/app.php and register Fortify service provider:
App\Providers\FortifyServiceProvider::class,
Next, open config/fortify.php and update your features array as follow:
'features' => [
Features::registration(),
Features::resetPasswords(),
],
Now we need to tell Fortify where is our auth views.
Open app/Providers/FortifyServiceProvider.php and in the boot method add:
Fortify::loginView(function () {
return view('auth.login');
});
Fortify::registerView(function () {
return view('auth.register');
});
Fortify::requestPasswordResetLinkView(function () {
return view('auth.forgot-password');
});
Fortify::resetPasswordView(function () {
return view('auth.reset-password');
});
Protect your pages
Now we need to protect our routes, open routes/web.php and use auth middleware, like:
Route::get('/', function () {
return view('welcome');
})->middleware(['auth']);

Related

Laravel auth middleware returns route not defined

I'm new to laravel and I'm trying to secure some routes wherein only authenticated users can access it.
I've followed instructions on grouping my web routes on an auth middle ware, so I did my routes/web.php it like this...
Route::group(['middleware' => 'auth'], function () {
Route::get('/feed', [FeedController::class, 'feed']);
Route::get('/profile', [ProfileController::class, 'profile']);
});
Route::get('/', [LandingController::class, 'landing']);
and my App/Http/Middleware/Authenticate.php like this....
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('/');
}
}
but when I access these guarded routes unauthenticated, it gives me error saying
Symfony\Component\Routing\Exception\RouteNotFoundException
Route [/] not defined.
Can someone point me on the right way here?

Laravel 6: disable all routes for guest except home and login

I need to disable all routes for guests in Laravel except '/' and 'login' pages.
Does that possible to implement it routes/web.php ?
Yes. In your routes/web.php file, make sure to define your protected routes under the auth middleware group.
routes/web.php
Route::get('/', function() {
// / route
});
Route::get('/login', function() {
// login page
});
Route::middleware(['auth'])->group(function () {
// define your routes here
// they'll be protected
});
Official documentation
Since Laravel 7.7 you can use excluded_middleware property eg:
Route::group([
'excluded_middleware' => ['auth'],
], function () {
Route::get('/', 'HomeController#index');
...
});

Why Auth::user() return null in routes of a custom Service Provider?

I'm making a new Service called Factures in App\Services\Factures.
I created the \App\Services\Factures\FacturesServiceProvider:
public function register() {
$this->app->bind('factures', function ($app) {
return new Facture;
});
}
public function boot() {
// laod Routes
$this->loadRoutesFrom(__DIR__ .'/Http/routes.php');
// load Views
$this->loadViewsFrom(__DIR__ . '/views', 'factures');
}
I registered my provider everything works fine expect the Auth::user() in returns me  null in the views and the routes.php.
How can I get access to the Auth() in custom service?
This post resolved my problem: User Auth not persisting within Laravel package
I figure out that Laravel  apply to the default routes/web.php file a middleware called 'web' And doesn't apply this group to external package routes loaded via service provider's.
So my routes in the custom file should be in web middleware:
Route::group(['middleware' => ['web']], function () {
Route::get('testing-services', function(){
dd(Auth::user());
// output is valid
});
});

How to set Laravel 5 Middleware auth?

I am using Larave 5 for my project. In my project i am using laravel default auth which use this command php artisan make:auth. And i set middleware in my route.php as shown
Route::group(['middleware' => 'web'], function () {
// Authentication Routes...
Route::auth();
Route::get('/', 'Auth\AuthController#getLogin');
Route::post('auth/login', 'Auth\AuthController#postLogin');
Route::get('auth/logout', 'Auth\AuthController#getLogout');
// Admin Roles Routes...
Route::get('admin/roles', 'AdminController#showRoles');
});
Now my question is if i user is logout and click on browser back button user login and user can access like add, edit, delete view after logout. So how can i handle this situation. Please help i think some code i miss out.
First of all, your Route::auth() does already has login and logout functions, if you run 'php artisan route:list' in your terminal you can see which routes are available etc..
Second of all you can create a group like shown below for your admin stuff:
Route::group(['middleware' => 'web'], function () {
// Authentication Routes...
Route::auth();
// Admin Roles Routes...
Route::group(['prefix'=>'admin', 'middleware'=>'auth'], function() {
Route::get('roles', 'AdminController#showRoles');
});
});
I hope this works for you ;)
Btw, the Laravel docs tell you a lot..., so make sure you watch them first ;)
First thing is you don't need to apply web middleware as it already applied to your routes by RouteServiceProvider, see https://laravel.com/docs/5.2/middleware#registering-middleware
Secondly, when use Route:auth() it is a shortcut for:
$this->get('login', 'Auth\AuthController#showLoginForm');
$this->post('login', 'Auth\AuthController#login');
$this->get('logout', 'Auth\AuthController#logout');
$this->get('register', 'Auth\AuthController#showRegistrationForm');
$this->post('register', 'Auth\AuthController#register');
$this->get('password/reset/{token?}', 'Auth\PasswordController#showResetForm');
$this->post('password/email', 'Auth\PasswordController#sendResetLinkEmail');
$this->post('password/reset', 'Auth\PasswordController#reset');
So you don't need to define these routes:
Route::post('auth/login', 'Auth\AuthController#postLogin');
Route::get('auth/logout', 'Auth\AuthController#getLogout');
Lastly, why you put login on your home page?
Route::get('/', 'Auth\AuthController#getLogin');
This example should be work:
Route::group(['middleware' => 'auth'], function () {
Route::get('/', function () {
return 'Hello! You are logged in.';
});
// Admin Roles Routes...
Route::get('admin/roles', 'AdminController#showRoles');
});
Route::auth();
With the routes above when unauthenticated user trying to access your home page http://yoursite.com and http://yoursite.com/admin/roles, user will be redirected to http://yoursite.com/login since those pages are protected by auth middleware.
An addition to #Rick answer.
You can also manually set a middleware inside the __construct() function of your controller.
Example:
// SomeController.php
public function __construct()
{
$this->middleware('auth');
}
Documentation

Redirect to Login if user not logged in Laravel

i am new to laravel,
i have code in my controller's __construct like
if(Auth::check())
{
return View::make('view_page');
}
return Redirect::route('login')->withInput()->with('errmessage', 'Please Login to access restricted area.');
its working fine, but what i wants is. its really annoying to put these coding in each and every controller, so i wish to put this Verify Auth and redirect to login page in one place, may be in router.php or filters.php.
I have read some posts in forum as well as in stackoverflow, and added code in filters.php like below but that's too not working.
Route::filter('auth', function() {
if (Auth::guest())
return Redirect::guest('login');
});
Please help me to resolve this issue.
Laravel 5.4
Use the built in auth middleware.
Route::group(['middleware' => ['auth']], function() {
// your routes
});
For a single route:
Route::get('profile', function () {
// Only authenticated users may enter...
})->middleware('auth');
Laravel docs
Laravel 4 (original answer)
That's already built in to laravel. See the auth filter in filters.php. Just add the before filter to your routes. Preferably use a group and wrap that around your protected routes:
Route::group(array('before' => 'auth'), function(){
// your routes
Route::get('/', 'HomeController#index');
});
Or for a single route:
Route::get('/', array('before' => 'auth', 'uses' => 'HomeController#index'));
To change the redirect URL or send messages along, simply edit the filter in filters.php to your liking.
To avoid code repetition, You can use it in middleware. If you are using the Laravel build in Auth, You can directly use the auth middleware as given,
Route::group(['middleware' => ['auth']], function() {
// define your route, route groups here
});
or, for a single route,
Route::get('profile', function () {
})->middleware('auth');
If you are building your own, custom Authentication system. You should use the middleware which will check the user is authenticated or not. To create custom middleware, run php artisan make:middleware Middelware_Name_Here and register the newly created middleware.
It's absolutely correct what other people have replied.
This solution is for Laravel 5.4
But just in case, if you have more than one middleware applying to routes, make sure 'auth' middleware comes in the end and not at the start.
Like this:
Route::prefix('/admin')->group(function () {
Route::group(['middleware' => 'CheckUser', 'middleware' => 'auth'], function(){
});
});
Route::middleware(['auth'])->group(function () {
Route::get('dashboard','BackendController#dashboard')->name('dashboard');
});
This entry in the web.php route will take the user [who is not logged in] to the login page if (s)he tries to access a 'protected' URL, "dashboard" in this case.

Resources