Call to a member function setCookie() on null - laravel

I am trying to finish this middleware in larval that checks to make sure is subscribed to a subscription plan. If the user is not it redirects to the payment page.
public function handle($request, Closure $next)
{
if(Auth::check()){
if (Auth::user()->subscribed('main')) {
return true;
}else{
return view('payments.payment')->with('user',Auth::user());
}
}else{
abort(403, 'Unauthorized action.');
}
return $next($request);
}
I am getting this error with not much luck finding a solution Call to a member function setCookie() on null.

change
return view('payments.payment')
to
return response()->view('payments.payment')

The problem is where you are returning true. A middleware should return a response-style object, not a boolean.
Since that is your "good" path and you want to proceed with your application logic, you should replace return true; with return $next($request);
public function handle($request, Closure $next)
{
if(Auth::check()){
if (Auth::user()->subscribed('main')) {
return $next($request);
}else{
return view('payments.payment')->with('user',Auth::user());
}
}else{
abort(403, 'Unauthorized action.');
}
}
On an unrelated recommendation, you can clean up your conditional logic a bit to make your code easier to read/follow:
public function handle($request, Closure $next)
{
// If the user is not logged in, respond with a 403 error.
if ( ! Auth::check()) {
abort(403, 'Unauthorized action.');
}
// If the user is not subscribed, show a different payments page.
if ( ! Auth::user()->subscribed('main')) {
return view('payments.payment')->with('user',Auth::user());
}
// The user is subscribed; continue with the request.
return $next($request);
}

return response(view('payments.payment')->with('user',Auth::user()));

i solve by redirect to other routereturn redirect()->to('route');

Related

How to fix this, i try to load dashboard route when the auth middleware is true

But when authentication was success, it shown error Route [/db1] not defined. I hace declared db1 route, but this route can access only if user has session. Anyone can tell me what wrong with my code?
this is my route:
Route::group(['middleware' => ['userSession']], function() { Route::get('/db1', [WasteController::class, 'db1'])->name('db1'); });
this is my kernel in middlewareGroup:
'userSession' => [ \App\Http\Middleware\CheckUserSession::class, ],
this is my middleware:
public function handle($request, Closure $next) {
if ($request->session()->get('status') != 'true') {
//status user cannot be found in session
return redirect('/');
}
return $next($request);
}
i have tried but it show error db1 route not defined
Did you try this?
public function handle($request, Closure $next) {
if ($request->session()->get('status') = 'true') {
//status user cannot be found in session
return $next($request);
}
return redirect('/');
}

Laravel: middleware check if user is softdeleted or not

I am using softdelete for users when a user is deleted.
When logging in or authenticating, all users are authenticated. So, I made a middleware named:
isSoftdeletedorNot
public function handle($request, Closure $next)
{
if ($request->user()->deleted_at == null) :
return $next($request);
else:
Auth::logout();
Session::flush();
Session::regenerate();
return redirect()->route('login')->withErrors(['suspended' => 'Your account is deactivated']);
endif;
}
It executes well. The problem is the redirected route shows 404 error and when I manually hard refresh it, it works again.
Try this
public function handle($request, Closure $next)
{
if ($request->user()->deleted_at != null) {
Auth::logout();
Session::flush();
Session::regenerate();
return redirect()->route('login')->withErrors(['suspended' => 'Your account is deactivated']);
}else{
return $next($request);
}
}

Custom Auth Middleware not redirecting properly for unauthorized user

I have created a custom auth controller for recognising unauthorized user and redirect them to login path. If logged in the middlewre is working absolutely fine, but showing error if not logged in. Here is my code
Middleware:
class CheckUserAuthenticated
{
public function handle($request, Closure $next)
{
if(auth()->check()) {
$user_id = auth()->user()->id;
define('authenticated_user_id' ,$user_id);
return $next($request);
}
return redirect('login'); // this code is not working
}
}
Error:
try this hope it help
public function handle($request, Closure $next)
{
if(auth()->check()) {
$user_id = auth()->user()->id;
define('authenticated_user_id' ,$user_id);
return $next($request);
}
return redirect('/login'); OR return redirect(route('login'));
}
class CheckUserAuthenticated
{
public function handle($request, Closure $next)
{
if(auth()->check()) {
$user_id = auth()->user()->id;
define('authenticated_user_id' ,$user_id);
return $next($request);
}
// return redirect('login'); // this code is not working
return redirect()->guest('/login');
}
}
redirect()->guest() will redirect if there is no authenticated user.
Example: If an authenticated user is logged in, it won't redirect them as they aren't a guest. If a user isn't logged in, the redirect will happen.
The issue is in circular routing, you are calling from one route, and then return to the same route from the middleware, so your request never reaches the endpoint.
if you call middleware on the...
Route::get('login')->middleware('auth);
...then middleware can not route to 'login' on the fail...
return redirect('login');
... because it will create the loop that never ends. The middleware should reroute to something else, or be placed on other route like 'admin'...
You probably have the middleware on the 'login', that creates the loop, just remove it.

How to get id in Middleware when i use user()

I have a relationship between users and roles. In middleware, I need to get roles to check if the role is 1 or 2. However, I get the following error.
"Trying to get property 'role_id' of non-object."
I am sure I have id 1 in role_id.
User Model
public function role()
{
return $this->belongsTo(Role::class, 'role_id');
}
public function handle($request, Closure $next)
{
if (!Auth()->check() && $request->user()->role_id == 1) {
return redirect()->back();
}
return $next($request);
}
Your if statement's logic is mistakenly checking if the user is logged out, while also checking the user's roles. If Auth::check() is false, then the user is not logged in and $request->user() will return null.
Removing the ! from the conditional will fix the error you're receiving.
public function handle($request, Closure $next)
{
if (Auth()->check() && $request->user()->role_id == 1) {
return redirect()->back();
}
return $next($request);
}
However, this will allow all guests to proceed, which you may not want. Assuming you want the middleware to only allow logged-in users with a specific role to proceed, use a more white-listed approach like this:
public function handle($request, Closure $next)
{
// Role ID 2 has permission to proceed
if (Auth()->check() && $request->user()->role_id == 2) {
return $next($request);
}
// Everyone else should go back, including logged-in users and guests.
return redirect()->back();
}
[Can't comment so I'm making a post.]
Aken already answered you but I'd suggest one more thing. Don't use 1 or 2 as ID's but constants:
public function handle($request, Closure $next)
{
if (Auth()->check() && $request->user()->role_id == ADMIN) {
return $next($request);
}
return redirect()->back();
}
You don't even need the comments for this one. Maybe even better:
public function handle($request, Closure $next)
{
if (Auth()->check() && $request->user()->isAdmin()) {
return $next($request);
}
return redirect()->back();
}
but you need to implement it on your own.

Laravel Edit Auth Middleware

I'm trying to edit the main Authenticate.php middleware, but when I add the following, I get an error
app.app has redirected you too many times
My intent here is to edit the auth middleware to check if the user has a username. This would prevent someone from exiting the registration page and then simply going into a secure portion of the website.
Auth Middleware:
public function handle($request, Closure $next)
{
if ($this->auth->guest()) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('/');
}
}
// This is the modified portion. Check for a username, if one is found, complete
the request, otherwise redirect back to the oauth page.
if (Auth::user()->username)
{
return $next($request);
}
return redirect()->route('oauth.oauth')->with('user' , Auth::user()->id);
}
You are creating a circular reference by using the auth middleware to redirect them to your oauth page when Auth::user()->username isn't present.
They are hitting the oauth page and then failing that check and so being constantly redirected to that page.
The best thing to do would be to split this out in the new middleware, but given you don't want to do this you could check the URL that they are hitting and make an exclusion based on this.
For example:
Add use Request; up the top and then in the body of your middleware add the below:
if (Request::path() == 'your/oauth/path')
{
return $next($request);
}
So it could fit in like this:
public function handle($request, Closure $next)
{
if ($this->auth->guest()) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('/');
}
}
// This is the modified portion. Check for a username, if one is found, complete
the request, otherwise redirect back to the oauth page.
if (Auth::user()->username)
{
return $next($request);
}
if (Request::path() == 'your/oauth/path')
{
return $next($request);
}
return redirect()->route('oauth.oauth')->with('user' , Auth::user()->id);
}
Just replace the 'your/oauth/path' with the actual path. That example would look like this as a full url www.example.com/your/oauth/path

Resources