session value not displayed on blade page
adminController
use Session;
Session::put('adminusername', "test");
echo Session::get('adminusername'); //it prints here fine
mater.blade.php
Welcome:{!! Session::get('adminusername') !!}
need to define route in middleware
Route::group(['middleware' => ['web']], function () {
Route::group(array('prefix'=>'admin'),function(){
Route::get('login', 'admin\AdminHomeController#showLogin');
Route::post('check', 'admin\AdminHomeController#login_check');
Route::get('dashboard', 'admin\AdminHomeController#showDashboard');
}
use Session;
public function showsession()
{
Session::put('adminusername', 'test');
return View::make("folder/page.php")->with('adminusername',Session::get('adminusername'););
}
View
Welcome:{!! $adminusername !!}
put this middleware in your kernel.php
protected $middlewareGroups = [
'web' => [
.....other classes
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
......other classes
],
'api' => [
'throttle:60,1',
],
];
Related
Middleware is not working (Laravel Livewire)
I am trying to authenticate user using custom auth in laravel livewire but it is not working.
It opens all the route whether user is authenticated or not
CustomAuth (This is my middleware file)
<?php
namespace App\Http\Middleware;
use Closure;
use Session;
use Illuminate\Http\Request;
class CustomAuth
{
public function handle(Request $request, Closure $next)
{
$path = $request->path();
if(($path=='login' ||$path=='register') && Session::get('user'))
{
return redirect()->route('/userpanel');
}
else if(($path!='login' && !Session::get('user')) && ($path!='register' && !Session::get('user')))
{
return redirect()->route('/login');
}
return $next($request);
}
}
Kernal.php (It is the Registration of middleware)
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Fruitcake\Cors\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
// \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'customauth' => \App\Http\Middleware\CustomAuth::class,
];
}
web.php (This is my Route file)
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Livewire\home;
use App\Http\Livewire\Gallery;
use App\Http\Livewire\Video;
use App\Http\Livewire\Faq;
use App\Http\Livewire\Team;
use App\Http\Livewire\Price;
use App\Http\Livewire\Auth\Login;
use App\Http\Livewire\Auth\Register;
use App\Http\Livewire\Userpanel;
Route::group(['middleware'=>'customauth'],function () {
Route::get('/register',Register::class)->name('register');
Route::get('/login',Login::class)->name('login');
Route::get('/', Home::class)->name('home')->middleware('auth');
Route::get('/gallery',Gallery::class)->name('gallery');
Route::get('/video',Video::class)->name('video');
Route::get('/faq',Faq::class)->name('faq');
Route::get('/team',Team::class)->name('team');
Route::get('/price',Price::class)->name('price');
Route::get('/userpanel',Userpanel::class)->name('user');
});
this would be an example of the use of middleware in the route page
Route::get('/nuevopoais', Nuevopoais::class)->middleware('can:Nuevopoais_listar')->name('nuevopoais');
Livewire has the config to set a middleware for its routes .
Check this please .
https://laravel-livewire.com/docs/2.x/authorization
I got it. Middleware is not working because of route cache
after running the following command it's work fine
php artisan route:cache
Thank you #Jesus Emanuel Becerra Santamar and #Mohamed Tahan for helping me!!!
I have Laravel passport installed on my dev environment. I noticed that no matter if I am logged in or not my api routes work. AN example of one of my routes is
Route::get('/users', function () {
return factory('App\User', 10)->make();
});
Shouldn't it automatically be authenticated with the api middle ware since it is in the api routes?
You should try this:
Route::group(['middleware' => 'auth:api'], function() {
Route::get('/users', function () {
return factory('App\User', 10)->make();
});
});
But for protect your routes not need to use an middleware declared after the route registered?
https://laravel.com/docs/5.5/passport#protecting-routes
I.e:
Route::get('/users', function () {
return factory('App\User', 10)->make()})->middleware('auth:api');
For using authenticated, you should modify your route as follows
Route::get('/users', function () {
return factory('App\User', 10)->make();
})->middleware('auth');
Moreover, please revise file config/auth.php if you did not use a default User class
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\{your User class name}::class,
],
You may need to add the bindings in your /app/Http/Kernel.php
https://laravel.com/docs/5.6/passport#via-middleware
Example:
protected $middlewareGroups = [
'web' => [
...
],
'api' => [
'throttle:60,1',
'bindings',
'auth:api',
],
];
And scopes if you want to use token scoping:
'scopes' => \Laravel\Passport\Http\Middleware\CheckScopes::class,
'scope' => \Laravel\Passport\Http\Middleware\CheckForAnyScope::class,
Full file example:
https://github.com/jeremykenedy/laravel-passport/blob/master/app/Http/Kernel.php
I have laravel 5.0 . and set sessions drivers to database . I have some link that no require to insert new row in sessions table . how i can disable inserting new row only for www.site.com/download .
Create a new route/middleware type for sessionless access. Do this by adding a new middleware group in your Http/Kernel that doesn't include the StartSession middleware, then adding a new route file to hold all your download links, and then registering your new route file in your RouteServiceProvider.
Edit the $middlewareGroups array in app/Http/Kernel.php to look like the following:
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
'sessionless' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
Then edit your app/Providers/RouteServiceProvider to map your newly-created route file:
Route::group([
'middleware' => 'sessionless',
'namespace' => $this->namespace,
'prefix' => 'download',
], function ($router) {
require base_path('routes/downloads.php');
});
Now add a file in your /routes directory named downloads.php, and add your downloadable routes there. If you want to use a wildcard to parse what file they're looking for, you can, or you can explicitly list what routes will trigger a download:
Route::get('test', function(){
$file = '/path/to/test/file';
return response()->download($file);
});
Route::get('{fileName}', function($fileName){
$file = '/path/to/' . $fileName;
return response()->download($file);
});
This doesn't address using headless authorization, which you would need if you didn't want unauthorized access to all of your sessionless routes.
this solution is good for laravel 5.0
first must define two middleware in app/http/kernel.php .first middleware is lesssession . lesssession is for route that do not need session .and second is hasssession middleware .hassession is good for route that need session :
<?php namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel {
/**
* The application's global HTTP middleware stack.
*
* #var array
*/
/**
* The application's route middleware.
*
* #var array
*/
protected $routeMiddleware = [
'auth' => 'App\Http\Middleware\Authenticate',
'hassession' => [
'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
'Illuminate\Cookie\Middleware\EncryptCookies',
'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
'Illuminate\Session\Middleware\StartSession',
'Illuminate\View\Middleware\ShareErrorsFromSession',
'App\Http\Middleware\VerifyCsrfToken',
],
'lesssession' => [] ,
'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
];
}
step 2:
put route in two group by edit app/http/route.php:
<?php
Route::group(['middleware' => ['lesssession']], function()
{
Route::get('download', function(){
// do some stuff for download file
});
});
Route::group(['middleware' => ['hassession']], function()
{
// all other route that need session
});
?>
I'm trying to pass to all templates current user object like this:
class Controller extends BaseController
{
public function __construct()
{
view()->share('usr', Auth::guard('user'));
}
}
Every controller is extended by Controller. But if i try to dump Auth::guard('user')->user() Laravel returns null, although I am logged in. Moreover when i pass this variable into template, {{ $usr->user() }} returns current user. What I've done wrong?
my config/auth.php
'defaults' => [
'guard' => 'user',
'passwords' => 'users',
],
'guards' => [
'user' => [
'driver' => 'session',
'provider' => 'user',
],
],
'providers' => [
'user' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
],
Kernel.php
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
];
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
//\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* #var array
*/
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];
my own function to log in:
public function authorizes(Request $request)
{
$this->validate($request, [
'login' => 'required|max:50',
'password' => 'required|max:50'
]);
$credentials = $request->only(['login', 'password' ]);
$remember = $request->get('remember', false) == 1 ? true : false;
if ($this->guard->attempt( $credentials, $remember)) {
$user = $this->guard->user();
$user->last_login = date('Y-m-d H:i:s');
$user->save();
return redirect()->route( 'homepage' )->withSuccess(trans('app.login.success'));
}
return redirect()->back()->withErrors(trans('app.wrong.credentials'));
}
In Laravel 5.3 you should change your controller constructor like so to make this work (assuming you use at least Laravel 5.3.4):
public function __construct()
{
$this->middleware(function ($request, $next) {
view()->share('usr', Auth::guard('user'));
return $next($request);
});
}
You can see this change described in Upgrade guide:
In previous versions of Laravel, you could access session variables or
the authenticated user in your controller's constructor. This was
never intended to be an explicit feature of the framework. In Laravel
5.3, you can't access the session or authenticated user in your controller's constructor because the middleware has not run yet.
As an alternative, you may define a Closure based middleware directly
in your controller's constructor. Before using this feature, make sure
that your application is running Laravel 5.3.4
Try to do this:
view()->share('usr', Auth::user());
Or this:
view()->share('usr', auth()->user());
Frist check if user is logged or not, then share the current user as:
public function __construct()
{
if (auth()->check()) {
$this->currentUser = auth()->user();
View::share('currentUser', $this->currentUser);
} else {
// you can redirect the user to login page.
}
}
In your case there are two things to consider
To get actual user model you should do Auth::guard('user')->user()
Auth::user() is actually not yet initialized when view()->share() is called, see https://github.com/laravel/framework/issues/6130
Therefore you could rather use view composer. In boot method of your AppServiceProvider add:
\View::composer('*', function ($view) {
$view->with('usr', \Auth::guard('user')->user());
});
I am trying to use oauth for google in laravel 5 but i am getting the error. Can any one help me to sort out this problem.
Followings are my files please check out
.env
GOOGLE_ID = 'mygoogleId'
GOOGLE_SECRET = 'mysecretID'
GOOGLE_REDIRECT = http://localhost:8090/users
services.php
'google' => [
'client_id' => env('GOOGLE_ID'),
'client_secret' => env('GOOGLE_SECRET'),
'redirect' => env('GOOGLE_REDIRECT'),
],
AuthController
public function redirectToProvider() {
return Socialite::driver('google')->redirect();
}
public function handleProviderCallback() {
$user = Socialite::driver('google')->user();
console.log($user);
}
routes.php
Route::get('google', 'Auth\AuthController#redirectToProvider');
Route::get('google/callback', 'Auth\AuthController#handleProviderCallback');
//I have set the providers and aliases in app.php.
Here is the code where i am getting an error
//on set() method
public function redirect()
{
$state = str::random(40);
if ($this->usesState()) {
$this->request->getSession()->set('state', $state);
}
return new RedirectResponse($this->getAuthUrl($state));
}
Thanks in advance..
Hey If you are using laravel 5.2, this is worked for me.
Put your controllers in 'web' middleware. like,
Route::group(['middleware' => 'web'], function() {
Route::get('google', 'Auth\AuthController#redirectToProvider');
Route::get('google/callback', 'Auth\AuthController#handleProviderCallback');
});
and Make sure Kernel file has middleware classes registered.
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
\Perkweb\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\Perkweb\Http\Middleware\VerifyCsrfToken::class,
],
'api' => [
'throttle:60,1',
],
];