Ad

How To Execute Remaining Code After Calling Another Method Within Same Controller In Laravel?

I'm using laravel 5.8. There are two functions in my laravel controller. After calling one function into another remaining code does not execute. Is there a way to execute the remaining body of function? I have tried calling function without return statement function is not called.

public function a(){
    return "function a";
}

public function b(){
    return $this->a();
 // after the above statement remaining code does not execute
    echo "function b";
}
Ad

Answer

The return keyword gives the answer to your confusion. Return means execute this line and exit the function. Of course it will not continue with the rest of the code. It depends what you want to do with the result of the first function, but if you want the result you can store it in a variable and use it for other calculation, for example this will work:

public function b(){
    $result = $this->a();

    echo "function b and result of a: " . $result;
}

--- EDIT

After your comment below, the best way to check if user is logged in or not is not to have a separate function for that but you can achieve that using a middleware. So instead of having separate function, on your route you can define it as this:

Route::get('endpoint', '[email protected]')->middleware('auth');

This middleware will redirect the user to the login page unless he is logged in.

If none of the above is considered as solution for your case, then I found a duplicate question as your original one here.

Ad
source: stackoverflow.com
Ad