Laravel 5.1: Unable to get form data in middleware - php

I have a form submission that posts to indexController#postSwitch. I get the submitted data in the postSwitch action, but when I do the same thing in my middleware, it returns null. This is a global middleware, and I'm just trying to see if I have access to the submitted data. This documentation shows that I should be able to get the form data.
Like this..
// Form: just a simple form that posts `id` to /switch
// Complete routes
Route::group(['middleware' => ['auth'], function() {
Route::get('/', 'IndexController#dashboard');
Route::post('/switch', 'IndexController#postSwitch');
Route::get('/settings', 'IndexController#settings');
});
Route::get('auth/login', 'Auth\AuthController#getLogin');
Route::post('auth/login', 'Auth\AuthController#postLogin');
Route::get('auth/logout', 'Auth\AuthController#getLogout');
Route::get('auth/register', 'Auth\AuthController#getRegister');
Route::post('auth/register', 'Auth\AuthController#postRegister');
Route::get('password/email', 'Auth\PasswordController#getEmail');
Route::post('password/email', 'Auth\PasswordController#postEmail');
Route::get('password/reset/{token}', 'Auth\PasswordController#getReset');
Route::post('password/reset', 'Auth\PasswordController#postReset');
// Middleware
public function handle($request, Closure $next)
{
$id = $request->input('id');
dd($id); // null
return $next($request);
}
// IndexController#switch
public function postSwitchBrand(Request $request)
{
$id = $request->input('id'); // Has the submitted data
}
This middleware is registered globally. i.e. appended to the $middleware property in \App\Http\Kernel. What am I missing?

Based on our discussion in the comments, I see that there is a small glitch here, which is not defined in the documentation. I've raised an Issue on laravel Git repository stating the problem there.
Here's the link to the issue: https://github.com/laravel/framework/issues/11278
Link on the laravel Forum :: http://laravel.io/forum/12-11-2015-form-data-not-accessible-in-middleware-via-request

Try to use following:
$request->id;
To access request parameters.

It is tricky but looks as though something like the following works:
$request->getContent()
or if getting a json payload for the request:
$request->json()

Related

Can you see my routes and config with sanctum

Using https://laravel.com/docs/9.x/sanctum , I'm try create API application.
Generating token is ok.
But when I try to restrict my endpoint to authorized users with middleware, any check permission didn't work, endpoint is accessible for all.
In controller I tested with debug auth('sanctum')->check() - and I became true for valid token and false else.
My routes/api.php
Route::post('login', [AuthController::class, 'login']);
Route::group(['middleware' => ['auth:sanctum']], function () {
Route::post('logout', [AuthController::class, 'logout']);
Route::group([
'prefix' => 'services/{service}',
'where' => [
'service' => implode('|', array_column(ServiceEnum::cases(), 'name'))
]],
function () {
Route::get('accounts/{account}/balance', [AccountController::class, 'getBalance']);
});
});
It was my fail.
I recreate a project with new fresh laravel (something was broken with installing laravel passport) and then solve a problem with empty auth user in constructor of controller:
public function __construct(Request $request)
{
$this->middleware(function ($request, $next) {
$this->user = auth()->user();
return $next($request);
});
}

Redirect to other route when session has expired in Laravel 5.8

I´m trying to return another route because in my case login it´s a modal page, and when the session has expired, return to this route but it does not exist. I don´t know how I would do this.
I can see this in web: if(Auth::check()){ return route('/')} but i don´t know where i´m putting this code.
Also i can see this: in 'App\Exception\Handler' put this:
if ($exception instanceof AuthenticationException) {
return redirect('/');
}
How I would can to do this?
Thanks for helping me
You can create a route to check sessions, every minute it will check session exists or not.
You can use like this:
Blade part:
#if (Auth::user())
<script>
$(function() {
setInterval(function checkSession() {
$.get('/is-logged-in', function(data) {
// if session was expired
if (!data.isLoggedIn) {
// redirect to login page
// or, may be better, just reload page
location.reload();
}
});
}, 60000); // You can change it
});
</script>
#endif
Route:
Route::get('is-logged-in', 'Auth\AuthController#checkSession');
Controller:
public function checkSession()
{
return Response::json(['isLoggedIn' => Auth::check()]);
}
Laravel probably already has what you need. Take a look at the App\Http\Middleware\Authenticate class. This is a middleware that will redirect user to 'login' named route (by default), if the session has expired.
By default none of the routes you put in routes/web.php are protected by this middleware, but you can change this.
Method 1: Add a auth middleware in your controller's constructor:
public function __construct()
{
$this->middleware('auth');
}
Method 2: Add a auth middleware for one of your routes:
Route::get('profile', function () {
// Only authenticated users may enter...
})->middleware('auth');
Method 3: Adding all protected routes into group:
Route::group(['middleware' => ['auth']], function () {
// All your protected routes go here
});
Then you can easily change the URL which will be used for redirecting users with expired session (not authenticated). Just edit the App\Http\Middleware\Authenticate::redirectTo() method and return your URL, for example:
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('yourLoginRouteName');
}
}

Laravel routing without appending any prefix

I have a path in Laravel it is like subdomain.mydomain.com/admin/login
I am trying to call
subdomain.mydomain.com and need to get the login page straight.
Currently, it's not working
This is the function I am using in routerserviceprovider.php
protected function mapAdminRoutes()
{
Route::middleware('subdomain.mydomain.com')
->prefix('admin')
->namespace($this->namespace)
->group(base_path('routes/admin.php'));
}
and in admin.php there is a resource group shows like this:
Route::group(['prefix' => 'admin', 'namespace' => 'Admin'], function() {
//Login Routes...
Route::view('login','admin.login');
});
can anyone help with this?
Add following route
Route::get('/',function(){ return view('login.index'); })->name('admin.login');
i hope it helps

How to access model method based on api auth in laravel 5.6?

I have user cars having many to many relation between users and cars. I am using passport and everthing is working properly (Sign-in, Sign-up etc) In my I have a method like below in Users Model
public function cars()
{
return $this->belongsToMany(Car::class, 'users_cars', 'user_id', 'car_id');
}
I also have API auth routes which is working fine
Route::group([
'prefix' => 'auth'
], function () {
Route::post('login', 'AuthController#login');
Route::post('signup', 'AuthController#signup');
Route::group([
'middleware' => 'auth:api'
], function() {
Route::get('logout', 'AuthController#logout');
Route::get('user', 'AuthController#user');
Route::get('car-list','CarController#carList');
});
});
And in CarController I am trying to get user cars based on auth login user_id as like below
public function carList(){
$User = new User();
return new CarResource($User->cars());
}
I am also using API resource for API's
use App\Http\Resources\Car as CarResource;
But it does not working so can someone kindly guide me how to fix the issue. I would appreciate, thank you so much.
In the CarController you are instantiating a new User object. They are never going to have any cars. If you want to get all the cars that the user who is logged in, you will need to do something like the following:
public function carList(){
$User = User::with('cars')->findOrFail(Auth::id());
return new CarResource($User->cars);
}

Laravel auth on all requests (global auth?)

I am working on a Laravel project which is only intended to be used by backend admin staff. So, there is no separation of "standard user" and "admin user". So, I want to implement some sort of global auth filter on the entire project.
What I have so far is this on by app/routes.php
<?php
// Home route with login required
Route::get('/', array('as' => 'home', function () {
return View::make('hello');
}))->before('auth');
/*
* Global Auth Filter - All Guests Go To Login
*/
Route::filter('auth', function($route, $request) {
if (Auth::guest())
return Redirect::guest('login')
->with('login_error', 'Login required!');
});
/*
* Login Route Handler
*/
Route::get('login', array('as' => 'login', function () {
if (Auth::check())
return Redirect::route('home');
return View::make('login');
}))->before('guest');
/*
* Login Post Event Handler
*/
Route::post('login', function ()
{
// Parse form data
$user = array(
'username' => Input::get('username'),
'password' => Input::get('password')
);
// Try to login user
if (Auth::attempt($user))
{
// login success
return Redirect::route('home');
}
else
{
// Login error
return Redirect::route('login')
->withInput()
->with('login_error', 'Invalid username and/or password!');
}
});
/*
* Logout Route Handler
*/
Route::get('logout', array('as' => 'logout', function () {
Session::flush();
return Redirect::route('home');
}))->before('auth');
This works fine. If I got to the / page, it redirects me to /login route and from there I can login. Once logged in, I have a /logout link on the hello view and that also works (i.e. logging out).
This code above is my test code. In the real application I am working on (taking over the project from previous developer), the routes app/routes.php are setup like this:
<?php
Route::controller('dev', 'DevController');
Route::controller('orders', 'OrdersController');
Route::controller('customers', 'CustomersController');
Route::controller('picking', 'PickingController');
Route::controller('stock', 'StockController');
Route::controller('suppliers', 'SuppliersController');
Route::controller('warehouse', 'WarehouseController');
Route::controller('upload', 'UploadController');
Route::controller('apixero', 'XeroController');
Route::controller('api/orders', 'OrdersAPIController');
Route::controller('api/picking', 'PickingAPIController');
Route::controller('api/po', 'PurchaseOrdersAPIController');
Route::controller('api/products', 'ProductsAPIController');
Route::controller('api/customer', 'CustomerAPIController');
Route::controller('api/suppliers', 'SuppliersAPIController');
Route::controller('api/currency', 'CurrencyAPIController');
Route::controller('api/notes', 'NotesAPIController');
Route::get('/', function() {
return View::make('dashboard');
});
My question #1 is, how do I apply a "global" auth on requests with this app/routes.php? As the real application routes code seems to be different from what I have worked out in my test code..
Question #2 - Looking at my test code, can someone tell me at which point this filter gets executed:
Route::filter('auth', function($route, $request) { ... });
This code concept was taken out of a tutorial I was reading, but I noticed that my test code continues to work fine - even if I remove this code block. So, I am not entirely sure in which scenario the above code block is being executed.
Route filters are disabled when in the testing environment. To enable them, add Route::enableFilters() to your test.
To add a global auth filter - you could do this:
Route::get('/login')... //rest of code here
Route::get('logout')... //rest of code here
Route::group(array('before' => 'auth'), function()
{
Route::controller('dev', 'DevController');
Route::controller('orders', 'OrdersController');
...
Route::controller('api/notes', 'NotesAPIController');
Route::get('/', function() {
return View::make('dashboard');
});
});

Categories