Reputation: 4397
Suppose i want to return 404 error view from my controller's method and i have this block of code.
try {
file_get_contents('http://www.somewebsite.com');
}
catch (\Exception $e) {
return view('errors.404'); // View::make('errors.404');
// or
return response()->view('errors.404'); // Response::view('errors.404');
// or
abort(404); // App::abort(404);
}
Each time i'll see the same view output of 404. Here is my questions.
What is the difference among view(), response()->view() and abort()?
What is the particular use cases of them?
Upvotes: 1
Views: 5224
Reputation: 3325
Resurrecting since I've found little explicit info on this. Other answers have pointed out what abort()
does, but still, what about view()
vs. response()->view()
?
The view()
helper function (signature view($view = null, $data = [], $mergeData = [])
) returns a \Illuminate\Contracts\View\View
(or a \Illuminate\Contracts\View\Factory
if no arguments are passed to it).
The response()->view()
method (signature view($view, $data = [], $status = 200, array $headers = [])
) returns a \Illuminate\Http\Response
From https://laravel.com/docs/10.x/responses#other-response-types:
If you need control over the response's status and headers but also need to return a view as the response's content, you should use the view method:
return response()
->view('hello', $data, 200)
->header('Content-Type', $type);
The best I can understand, the response()
methods give you more control over the response, such as a custom status and headers (as in the above example). Personally, I would use the view()
helper for most of my controller method returns, then use response()->view()
when I might need to customize the http response. When using method return types, if I'm not sure what the return might be in the future, Illuminate\Http\Response
might be best:
public function index(Request $request):Illuminate\Http\Response
{
...
return response()->[whatever]
}
Upvotes: 1
Reputation: 3226
When you use view() or response()->view() the HTTP response code your client recieves will be 200 aka OK. When using abort(404) the code will be 404 NOT FOUND!
Upvotes: 1
Reputation: 1723
view()
is just a shorthand for response()->view()
response()->view()
returns the specified view with the status code 200, but you are able to modify the response in many ways. For example set other headers or another status code like 301.
abort()
throws an NotFoundHttpException or HttpException and will make Laravel look for a view named like the corresponding code in views/errors
so you don't have to specify the view on your own.
Upvotes: 3