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
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 ran deb deploy and it got down to this point.
The command "/usr/bin/php ~/NetTube/releases/1/artisan optimize" failed.
Exit Code: 1 (General error)
Host Name: 68.183.20.108
================
Configuration cache cleared!
Configuration cached successfully!
Route cache cleared!
In Route.php line 917:
Unable to prepare route [api/user] for serialization. Uses Closure.
I've looked into this and it seems that I can't use closures with routes, which is fine. I'm just not sure how to prevent closures.
This is my web.php
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
// Route::get('/', function () {
// return view('welcome');
// });
Route::get('/','HomeController#index')->name('home');
Auth::routes();
// Route::get('/home', 'HomeController#index')->name('home');
Route::group(['middleware' => ['auth']], function(){
Route::get('/upload','VideoUploadController#index');
Route::get('/channel/{channel}/edit','ChannelSettingsController#edit');
Route::put('/channel/{channel}/edit','ChannelSettingsController#update');
});
Route::get('/channel/{channel}','ChannelController#index');
Route::get('/{channel}','ChannelController#index');
I have tried putting the routes not in a group with
Route::get('/upload', [
'uses' => 'VideoUploadController#index',
'middleware' => ['auth'],
]);
Route::get('/channel/{channel}/edit', [
'uses' => 'ChannelSettingsController#edit',
'middleware' => ['auth'],
]);
Route::put('/channel/{channel}/edit', [
'uses' => 'ChannelSettingsController#update',
'middleware' => ['auth'],
]);
I am running laravel 6.17.1. I hope I gave enough information to anybody that can help.
the problem resides on the routes\api.php.
Do something like Route::middleware('auth:api')->get('/user', 'MyProfileController#index');. This route needs to be binded to a controller. If you don't need the route, comment or delete it.
For apis auth I am currently using:
Route::group([
'middleware' => 'auth:api'
], function() {
Route::post('logout', 'AuthController#logout');
Route::get('user', 'AuthController#user');
});
If I want to use same for session based logins do I need to create same routes in web.php file or can I set up middleware in AuthController constructor with something like this or this?
In this answer 'auth:api' means auth is checking for api so do I need to pass anything there to check for sessions like 'auth:api,web' or what?
Create same routes in web.php just ommit the middleware, as web middleware is applied automatically. Same goes for api.php, auth:api is default middleware there.
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 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