I used laravel 5.1 for the previous project and I had no problem with it, but now I installed Laravel 5.2 and I got a problem with auth functionality
so I use the following routes
Route::group(['middleware' => ['web']], function () {
Route::controllers([
"auth" => "Auth\AuthController",
"password" => "Auth\PasswordController"
]) ;
});
And it's ok I can see my auth form but when I send the form to the post route /auth/login the session isn't set so I got the redirect but when I check if I logged in or not Auth::check() I get false
Not only the Authentication routes need to use the web middleware group; all routes which require the functionality it provides need to use it too.
For example
Route::group(['middleware' => ['web']], function () {
Route::auth();
});
Route::get('example-1', function () {
dd(Auth::check()); // always will return false
});
Route::group(['middleware' => ['web']], function () {
Route::get('example-2', function () {
dd(Auth::check()); // works
});
});
The web middleware group simply collects and runs lots of middleware for you.
'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,
],
You'll notice StartSession::class above. This means that for every request which you expect session data be available (for Auth and such) you'll need to have run this Middleware.
Either by using the web group, or explicitly calling that middleware on the route/route groups you want.
use this Route::auth(); simply
Related
I use Laravel 7 for an API project, I have created a JWT Middleware, and I want to apply it to all my routes, except 2 of them.
For now I have in my routes/api.php :
Route::prefix('v1')->group(function () {
Route::get('ping', 'Api\Ping\PingController#ping');
// auth routes
Route::group(['prefix' => 'login/'], function () {
Route::post('login', 'Api\Auth\AuthController#login');
Route::group(['middleware' => 'jwt:api'], function() {
Route::get('me', 'Api\Auth\AuthController#me');
Route::post('refreshToken', 'Api\Auth\AuthController#refresh');
Route::post('logout', 'Api\Auth\AuthController#logout');
});
});
Route::group(['middleware' => 'jwt:api'], function() {
Route::resource('users', 'Api\User\UserController');
// my other routes protected .....
I don't like this approach because I need to copy the middleware.
I tried this approach :
Route::group(
[
'middleware' => ['jwt:api', ['except' => 'login/login']],
'prefix' => 'v1/',
], function() {
But I have this error :
Illegal offset type in isset or empty
Is it possible ? I want to group everything in my route file.
Possible solutions:
You can pass additional parameters to middleware via dots and check in middleware to do not use passed routes
Also, you can overwrite middleware and add some property\constant with array of excepts, like in csrf middleware
Implement ability in Laravel core to pass except array as in your exmaple and make a PR to framework github
Left it as you have done
I have the following lines in my routes/api.php
Route::middleware('api')->get('/posts', function (Request $request) {
Route::resource('posts','ApiControllers\PostsApiController');
});
When I hit http://localhost:8000/api/posts it comes back blank, but when I move the above route to routes/web.php like so:
Route::group(['prefix' => 'api/v1'],function(){
Route::resource('posts','ApiControllers\PostsApiController');
});
it works.
As a reminder I have cleared the routes cache file with php artisan route:clear and my route list comes with php artisan route:list when my routes/web.php is empty and routes/api.php has the above route:
Domain
Method
URI
Name
Action
Middleware
GET|HEAD
api/posts
Closure
api
Note that with web routes part the list comes ok and works fine.
What am I doing wrong here?
Dont use the middleware api and see following route example for API routes
Example 1 (in your api.php)
Route::get('test',function(){
return response([1,2,3,4],200);
});
visit this route as
localhost/api/test
Example 2 (if you want api authentication, token based auth using laravel passport)
Route::get('user', function (Request $request) {
///// controller
})->middleware('auth:api');
You can make get request for this route but you need to pass the access token because auth:api middleware has been used.
Note: see /app/http/kernel.php
and you can find the
protected $routeMiddleware = [
//available route middlewares
]
There must not be such (api) kind of middle ware in this file (kernel.php) for routes unless you create one, that why you can not use middleware as api.
Here, How I am creating REST APIs (api.php)
//All routes goes outside of this route group which does not require authentication
Route::get('test',function(){
return response([1,2,3,4],200);
});
//following Which require authentication ................
Route::group(['prefix' => 'v1', 'middleware' => 'auth:api'], function(){
Route::get('user-list',"Api\ApiController#getUserList");
Route::post('send-fax', [
'uses'=>'api\ApiController#sendFax',
'as'=>'send-fax'
]);
Route::post('user/change-password', [
'uses'=>'api\ApiController#changePassword',
'as'=>'user/change-password'
]);
});
I need to configure middleware in Laravel that all controllers will be secured by Auth.
I mean that will redirection for every incoming request if user is not authorized.
You can do the following in your routes file:
Route::group(['prefix' => 'admin'], function () {
Route::group(['middleware' => ['auth'], function() {
...Your routes here
This will apply the auth middleware to all routes prefixed with admin. You can of course also leave the prefix away if you don't need it.
I created a new laravel project and laravel flash seems to not be working as i want. The moment I return to a route the flash is gone. I have controller method that does absolutly nothing but flash and return to a route.
Like so
public function activateContract(Request $request ){
return redirect()->to('test')->with('status', 'test');
}
My routes file
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::get('/', function(){
return redirect()->intended(route('contract.index'));
});
Route::group(['middleware' => 'auth'], function () {
Route::group(['prefix' => 'contract'], function(){
Route::get('', ['as' => 'contract.index' , 'uses' => 'User\ContractController#index']);
Route::post('', ['as' => 'contract.index' , 'uses' => 'User\ContractController#activateContract']);
Route::get('mijn', ['as' => 'user.contract.index' , 'uses' => 'User\ContractController#userContracts']);
});
});
Route::get('test', function(){
dd(session('status'));
});
c});
Here is the ouput of the die dump in the test route witch magicaly lost the flash message.
null
You need to send the message with the redirect like so:
return redirect()->to('test')->with('status', 'test');
And then you can access it with the session helper function:
session('status');
docs
Edit: Place your Route::get('test') into your group with middleware 'web'.
See more about HTTP Middleware here
Laravel 5.2 changed middleware document as :Keep in mind, the web middleware group is automatically applied to your default routes.php file by the RouteServiceProvider.
It means that if you keep a route in another ['middleware' => 'web'], the data set by session()->flash() would be lost by executed web middleware twice.
It is also the answer someone asked why web executed twice.
Laravel 5.2 : Web middleware is applied twice
As you guys know Laravel 5.2 was released a few days ago. I am trying this new version. I made a new project using the following command on CLI:
laravel new testapp
As per documentation of Authentication Quickstart, I followed the following command to scaffold routes and views of authentication:
php artisan make:auth
It worked fine. Registration is working fine. But I am facing problem in Login. After login I tested following in route.php file:
Route::get('/', function () {
dd( Auth::user());
return view('welcome');
});
Auth::user() is returning null and also Auth::check() and Auth::guest() are not working appropriately. I have tried same thing again and again two three times by making new projects but couldn't get the correct results.
Below is the complete route.php
<?php
/*
|--------------------------------------------------------------------------
| Routes File
|--------------------------------------------------------------------------
|
| Here is where you will register all of the routes in an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::get('/', function () {
dd( Auth::());
return view('welcome');
});
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| This route group applies the "web" middleware group to every route
| it contains. The "web" middleware group is defined in your HTTP
| kernel and includes session state, CSRF protection, and more.
|
*/
Route::group(['middleware' => ['web']], function () {
//
});
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::get('/home', 'HomeController#index');
});
Can anyone help me? or Is anyone facing the same problem? How can I fix it?
Laravel 5.2 introduces the middleware groups concept: you can specify that one or more middleware belongs to a group, and you can apply a middleware group to one or more routes
By default Laravel 5.2 defines a group named web, used to group the middleware handling session and other http utilities:
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,
],
So, if you want session handling, you should use this middleware group for all the routes in which you want to use authentication:
Route::group( [ 'middleware' => ['web'] ], function ()
{
//this route will use the middleware of the 'web' group, so session and auth will work here
Route::get('/', function () {
dd( Auth::user() );
});
});
UPDATE FOR LARAVEL VERSION >= 5.2.27
As of Laravel 5.2.27 version, all the routes defined in routes.php are using by default the web middleware group. That is achieved in app/Providers/RouteServiceProvider.php :
protected function mapWebRoutes(Router $router)
{
$router->group([
'namespace' => $this->namespace, 'middleware' => 'web'
], function ($router) {
require app_path('Http/routes.php');
});
}
So you don't need anymore to add manually the web middleware group to your routes.
Anyhow, if you want to use the default authentication for a route, you still need bind the auth middleware to the route