How to send a response by a method that is not a controller method?

I have Controller.phpwhose method show($id)gets along the route.

public function show($id)
{
    // fetch a couple attributes from the request ...

    $this->checkEverythingIsOk($attributes);

    // ... return the requested resource.
    return $response;
}

Now, in checkEverythingIsOk(), I perform some actions for verification and authorization. These checks are common to several routes within the same controller, so I would like to extract these checks and call the method every time I need to perform the same operations.

The problem is that I cannot send some answers from this method:

private function checkEverythingIsOk($attributes)
{
    if (checkSomething()) {
        return response()->json('Something went wrong'); // this does not work - it will return, but the response won't be sent.
    }

    // more checks...
    return response()->callAResponseMacro('Something else went wrong'); // does not work either.

    dd($attributes); // this works.
    abort(422); // this works too.
}

Note. Yes, I know that in the general case, you can use the middleware or verification services to perform checks before the request reaches the controller, but I do not want to do this. I need to do it this way.

+4
2

, :

function checkEverythingIsOk(){
    if (checkSomething()) {
        return Response::json('Something went wrong', 300);
    }
    if(checkSomethingElse()) {
        return Response::someMacro('Something else is wrong')
    }
    return null; // all is fine
}

:

$response = $this->checkEverythingIsOk();
if(!is_null($response)) {
    return $response;
}
+3

, , . , . , -, , .

// build a new request
$returnEarly = Request::create('/returnearly');

// dispatch the new request
app()->handle($newRequest);

// have a route set up to catch those
Route::get('/returnearly', ...);

, , , , /... , .

, , , . , . . .

, , ?

, Laravel:

// create intended Response
$response = Response::create(''); // or use the response() helper

// throw it, it is a Illuminate\Http\Exception\HttpResponseException
$response->throwResponse();  

, , .. .. \Illuminate\Foundation\Exceptions\Handler render, , , HttpResponseException. , .

+1

Source: https://habr.com/ru/post/1648954/


All Articles