1

Probably is a very easy question, but I'm new and after trying to find a similar I'm still unsure:

So I have an AJAX form pointing to:

function postLogin(Request $request){
   $this->fatherAuth($request); 

   return response() -> json(['url' => '/login-ok',], 200); 
}

Then I have:

public function fatherAuth($request){

    $validator = Validator::make($request->all(), [
        'email' => 'required|email',
    ],[
         'email.required' => 'Email needed',
    ]);

    # do some other checks and if there's some auth error:# 
    return response() -> json(['url' => '/login-bad',], 400); 
}

So what's happening is that I'm always getting the 200 response instead of the 400.

Should I pass a variable to postLogin? Should I send it to a new function?

BTW the reason of creating fatherAuth is because this code is shared between several controllers.

What would be the best solution / best practice?

Thanks

1 Answer 1

2

You are getting 200 response because you are not doing anything with response returned by fatherAuth method.

To make it work you should use something like:

function postLogin(Request $request){
   $response = $this->fatherAuth($request); 

   if ($response instanceof \Illuminate\Http\Response) {
       return $response;
   }

   return response() -> json(['url' => '/login-ok',], 200); 
}

but as you see it wouldn't be the best approach.

That's why you should use middleware for this. For example:

<?php

namespace App\Http\Middleware;

use Closure;

class CheckAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // here you do anything you want and assign to $result variable
        if (!$result) {
            return response() -> json(['url' => '/login-bad',], 400); 
        }

        return $next($request);
    }
}

and then you can apply this middleware to all the routes adding to $middleware array in App/Http/Kernel.php file:

App\Http\Middleware\CheckAuth::class,

Of course you can apply this middleware only to selected routes if you need.

After that in your postLogin method it's enough to have only:

function postLogin(Request $request){
   return response() -> json(['url' => '/login-ok',], 200); 
}
Sign up to request clarification or add additional context in comments.

1 Comment

oh, thank you very much! So I went option 1 because it was much more easy haha I just changed ...instanceof.. to if ($response) {return $response;}else {200}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.