Laravel Response
In this post we will know about laravel responses, its types and way to manage them.
We must return something from route or controller in order for users to see response in data.
We can simply pass return response like this.
Route::get('/', function () {
return 'Todo List';
});
Above code will automatically convert the string to HTTP response. Also if we return an array laravel will automatically convert the array to json response.
We can use response()
helper function to return response using snippet like the one below.
Route::get('test', function () {
return response('Hello Todo', 200)
->header('Content-Type', 'text/plain');
});
We can also attach headers by chaining header function to response. header
accepts key value pair as shown in above snippet.
We can also redirect to some url or named route using code below.
Redirect to url
Route::get('backend', function () {
return redirect('admin/backend');
});
Redirect to named route
Route::post('tasks/{task}', function (Task $task) {
// tasks.show is the name of the route.
return redirect()->route('tasks.show', ['task' => $task]);
});
We can also pass the parameters as shown above if route requires one.
We can also pass flash messages after successfully storing or editing or deleting or in any other requirements with redirect like this.
return redirect('tasks')->with('status', 'Task updated!');
And then after redirect we can show flash message like this.
@if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
@endif
Json Response
We can also return json response if we are creating apis like this.
return response()->json([
'id' => 1,
'title' => 'Sanitize your hands regularly'
]);
To find more details about laravel responses, visit this link.