I try to create an application using laravel, when I create the login page after having entered the information contained in the database I have this error:
here my code for login controller:
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use illuminate\Session\Middleware\StartSession;
class AuthController extends Controller
{
public function login(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|email',
'password' => 'required',
]);
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput();
}
$user = User::getByEmail($request->email);
if ($user && Hash::check($request->password, $user->password)) {
Auth::login($user);
return redirect()->intended('/home');
} else {
return redirect()->back()->withErrors(['email' => 'The provided credentials do not match our records.'])->withInput();
}
}
}
here my web.php:
use Illuminate\Auth\Events\Login;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Session;
use App\Http\Controllers\AuthController;
use App\Http\Controllers\Auth\LoginController;
use Illuminate\Support\Facades\DB;
use Illuminate\Session\Middleware\StartSession;
use Illuminate\View\Middleware\ShareErrorsFromSession;
Route::get('/', function () {
return view('welcome');
});
Route::group(['middleware' => ['web']], function () {
Route::get('/login', function () {
return view('login');
});
});
Session::start();
Route::post('/login', [App\Http\Controllers\AuthController::class, 'login'])->name('login');
Route::get('/client_items', 'App\Http\Controllers\ClientController#showClientItems')->middleware('auth');
Route::get('/listeitems/{siteId}/{operatorId}', 'ItemController#getItemsBySiteAndOperator');
Route::get('/hors-ligne', function () {
$pdo = DB::connection()->getPdo();
$stmt = $pdo->query('SELECT * FROM item');
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
return view('hors-ligne', ['rows' => $rows]);
});
I tried everything it's been 7 days since I was stuck on it
Edit:
here is my kernel.php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* #var array<int, class-string|string>
*/
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Illuminate\Http\Middleware\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
];
/**
* The application's route middleware groups.
*
* #var array<string, array<int, class-string|string>>
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
// \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
],
'api-session' =>[
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
]
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* #var array<string, class-string|string>
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::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' => \App\Http\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
}
and the error:
Related
Hello guys I'm using Laravel 9 with NextJs to build a ecommerce app with a shopping cart.
However when I list products I try to add them to session in Laravel, the value is always null.
Here is my NextJs code:
const addToCart = async (productId: number) => {
console.log(productId)
try {
// add product to cart
const rawResponse = await axios.post(`http://localhost:3001/product/add-to-cart/${productId}`);
// get product data from session
const cartData = await axios.get(`http://localhost:3001/products/cart`);
} catch (e) {
}
}
I'm just passing poductId, and making sure Laravel saves that product in the session
Here is how my Laravel code looks like I have 2 routes in web.php : first for adding product to session, and second to list products
Route::post('product/add-to-cart/{id}', [ProductController::class, 'addProductToCart']);
Route::get('products/cart', [ProductController::class, 'getProductsInCart']);
ProductController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Product;
class ProductController extends Controller {
public function addProductToCart(Request $request, $id) {
$product = Product::findOrFail($id);
$cart = session()->get('cart', []);
if(isset($cart[$id])) {
$cart[$id]['quantity']++;
} else {
$cart[$id] = [
"productId"=> $product->id,
"name" => $product->name,
"quantity" => 1,
"price" => $product->price,
];
}
session()->put('cart', $cart);
return response()->json(['success' => 'success'], 200);
}
public function getProductsInCart(Request $request) {
$cart = session()->get('cart');
var_dump($cart);
return $cart;
}
}
I have allowed CORS request
here is how my Kernel.php looks like
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* #var array<int, class-string|string>
*/
protected $middleware = [
\Fruitcake\Cors\HandleCors::class,
\Illuminate\Session\Middleware\StartSession::class,
\App\Http\Middleware\TrustProxies::class,
\Illuminate\Http\Middleware\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* #var array<string, array<int, class-string|string>>
*/
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' => [
\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,
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* #var array<string, class-string|string>
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::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,
'isAdmin' => \App\Http\Middleware\isAdmin::class,
];
}
But for some reason in second route, when I log session it returns null
$cart = session()->get('cart');
var_dump($cart); // is null
Does anyone know what could be potential problem?
I am building a laravel application where I have web and api routes.
I want to store sessions between my routes.
If i store as session without returning a view, it works fine.
But when i return a view my session no longer exists.
My web.php is as follows:
Route::get('/', 'ViewController#index');
Route::get('/check', 'ViewController#check');
My controller
public function index(Request $request)
{
$request->session()->put('test','123456');
$request->session()->save();
//echo $request->session()->get('test', 'default_value');
// return view('welcome'); //If I uncomment this the sessions are not working anymore.
}
public function check(Request $request)
{
echo $request->session()->get('test', 'default_value');
var_dump($request->session()->all());
//return view('welcome');
}
Maybe it has something to do that i also store sessions in my api routes in the api controllers. My api.php:
Route::group(['middleware' => ['web']], function () {
//board
Route::get('/board/create', 'BoardController#create');
Route::post('board/{id}/guess', 'BoardController#guessWord');
Route::get('/board/set', 'BoardController#set');
Route::get('/board/get', 'BoardController#get');
//user
Route::get('/user', 'UserController#get');
Route::post('/user/create', 'UserController#create');
});
kernel.php
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* #var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\TrustProxies::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\Session\Middleware\AuthenticateSession::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,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];
}
Thanks!
From the docs api routes does not use StartSession middleware because session is only available in web group of middlewares
So store session only in web routes
i have problem with laravel's (5.5) middlewares. Firstly, i created a middleware called AdminPanelAuth
Thats my middleware:
<?php
namespace App\Http\Middleware;
use Closure;
use Auth;
class AdminPanelAuth
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if(Auth::user() && Auth::user()->hasRole('admin'))
{
return $next($request);
}
else{
return redirect()->route('home');
}
}
}
and registered to Kernel.php
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* #var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\TrustProxies::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\Session\Middleware\AuthenticateSession::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,
'admin' => \App\Http\Middleware\AdminPanelAuth::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,
];
}
And i put that new admin middleware to my route file,
Route::group(
[
'namespace' => 'Backpack\Base\app\Http\Controllers',
'middleware' => ['web', 'admin'],
'prefix' => config('backpack.base.route_prefix'),
],
function () {
...
};
Admin middleware does not work for my routes. I've been tried to put this in web.php but nothings changed, still not working for me.
ps. i allready use composer dump-autoload, php artisan clear:compiled and php artisan optimize.
Thanks for your helps, best regards!
Try separating web middleware from admin like this:
Route::group(['middleware' => 'web', 'prefix' => config('backpack.base.route_prefix')], function () {
...
Route::group(['middleware' => 'admin'], function() {
...
});
...
};
EDIT:
In your middleware add use Illuminate\Support\Facades\Auth;
And in your Kernel, add admin middleware you created under throttle
EDIT 2:
Kernel.php
protected $middlewareGroups = [
'web' => [
...
\App\Http\Middleware\AdminPanelAuth::class, //Make sure your middleware is last in array
],
...
]
web.php
Route::group(['middleware' => 'web', 'prefix' => config('backpack.base.route_prefix')], function () {
...
};
I have define a middleware in laravel 5. But when I login it redirect me to dashboard but dashboard doesn't show and an error occurred. I have upload a picture of it.
http://imgur.com/a/1fCwt
AdminAuth.php
<?php
namespace App\Http\Middleware;
use Closure;
use Auth;
class AdminAuth
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if(Auth::check())
{
$user = Auth::user();
return redirect()->route('admin_display_dashboard');
} else {
return redirect()->route('admin_display_login');
}
}
}
Kernel.php
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel {
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
];
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,
],
'api' => [
'throttle:60,1',
],
];
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'adminAuth' => \App\Http\Middleware\AdminAuth::class,
];
}
Route.php
Route::group(['middleware' => ['adminAuth']], function () {
Route::get('admin/dashboard', array('as'=>'admin_display_dashboard', 'uses'=>'AdminViewController#displayDashboard'));
});
what's in your admin_display_dashboard() and admin_display_login(), you sure there is no redirect or so in there.
Meanwhile try this
if(!Auth::check())
{
return redirect()->route('admin_display_login');
}
$user = Auth::user();
return $next($request);
I am using Laravel 5.2.32, the validation of it is not work. I have tried to find solution on google and stackoverflow. However, the solution which can fix the 5.2.20 to 5.2.26 cannot fix the problem of laravel 5.2.32. Who can help me?
I have changed the router in the web middleware, the code as the following:
Route::group(['middleware' => ['web']], function () {
Route::get('/', function () {
return view('app/welcome');
});
Route::post('/signup', 'UserController#postSignup');
Route::post('/signin', 'UserController#postSignin');
Route::get('/dashboard', 'UserController#getDashboard');
Route::get('/logout', 'UserController#getLogout');
});
I also change the Kernel.php as the following. But it's still not work.
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\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,
];
The code in my controller as below:
namespace app\Http\Controllers;
use app\User;
use Illuminate\Http\Request;
use app\Http\Requests;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\Middleware\ErrorBinder;
use Validator;
class UserController extends Controller
{
// public function __construct()
// {
// $this->middleware('auth');
// }
public function postSignUp(Request $request)
{
$this->validate($request, [
'email' => 'required | email | unique:users',
'first_name' => 'required | max:60',
'password' => 'required | min:8'
]);
if ($request['password'] === $request['password_confirmation'])
{
$user = new User();
$user->first_name = $request['first_name'];
$user->email = $request['email'];
$user->password = bcrypt($request['password']);
$user->save();
Auth::login($user);
return view('app/dashboard');
}
// return redirect()->back();
}
}
you don't need the middleware web in your route anymore as its baked in to the latest version, s can do without the following:
Route::group(['middleware' => ['web']], function () {...
and your kernel something like...
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* #var array
*/
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,
],
'api' => [
'throttle:60,1',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* #var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];