LARAVEL Tutorial


Laravel 6 Response Tutorial


Laravel is a great PHP framework with a wide variety of features. A response also features laravel framework structures.

A web application responds to HTTP requests in a variety ways. Here you learn about the laravel response.

Laravel Basic Response

In the laravel web applications, controllers and routes return the response to HTTP requests in a variety of ways. The simple basic response is responding a string from a route or controller, you can see the below following example:

Route::get('/laravel-response', function () {
    return 'Hello w3alert developers. Thanks to try laravel response example';
});

Hit the following URL in your browser and to test the laravel basic response:

http://localhost:8000/laravel-response

Laravel Return Response with Header

To attach the header with response. You can use the laravel header() method, which is used to attach header with your response in your laravel web applications. Also, you can attach multiple headers in your response.

return response($content,$status)
   ->header('Content-Type', $type)
   ->header('X-Header-One', 'Header Value')
   ->header('X-Header-Two', 'Header Value');

You could do the following:

Route::get('/response-with-header',function() {
   return response("Hello w3alert", 200)->header('Content-Type', 'text/html');
});

Hit the following URL in your browser and to test the laravel response with the header:

http://localhost:8000/response-with-header

Return Response with Cookie Laravel

To attach cookies with the response. You can use the laravel withcookie() helper method, which is used to attach cookies with your response in your laravel web applications. 

You could do the following:

Route::get('/cookie-with-response',function() {
   return response("Hello W3alert", 200)->header('Content-Type', 'text/html')
      ->withcookie('topic','Laravel Cookies');
});

Hit the following URL in your browser and to test the response with cookie laravel:

http://localhost:8000/cookie-with-response

Laravel JSON Response

To send JSON response with a status code of any HTTP request. You can use the laravel json() method, which is sent JSON response in your laravel web applications. JSON method will automatically set the Content-Type header to application/json.

Route::get('json-response',function() {
   $data = ['topic' => 'json response', 'state_code' => '200'];
   return response()->json($data);
});

Hit the following URL in your browser and to test the laravel JSON response:

http://localhost:8000/cookie-with-response

Laravel Response Download File (csv, json, xml)

To download any file behalf on any web HTTP request. You can use the laravel download() method with a response() method. The download method may be used to generate a response that forces the user's browser to download the file at the given path.

return response()->download($pathToFile);

return response()->download($pathToFile, $name, $headers);

Laravel File Responses

To display a file like an image, pdf, text, etc, file, behalf on any web HTTP request. You can use the laravel file() method with a response() method. The file method can be used to display a file, such as an image or PDF, directly in the user's browser instead of initiating a download.

return response()->file($pathToFile);

return response()->file($pathToFile, $headers);

Laravel Custom Response 

To create a custom response behalf on any web HTTP request. You can use the laravel macros method on the Response facade.

Just go to app/providers and create a new file name ResponseMacroServiceProvider.php and update the below code into your file:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Response;

class ResponseMacroServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        // Success Response
        Response::macro('success', function ($message, $data = null) {

            $response = ['success' => true, 'message' => $message];
            if ($data) {
                $response['data'] = $data;
            }
            return Response::json($response, 200);
        });
        // Failed Response
        Response::macro('fail', function ($message = 'Something went to wrong.', $statuscode = 200) {
            return Response::json(['success' => false, 'message' => $message , 'code' => 420], $statuscode);
        });

    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

After that, register above creates micros. So go to config/app.php file and register like the following:

'providers' => [

  App\Providers\ResponseMacroServiceProvider::class,

 ];

Use micros with a response like below:

//for success response
return response()->success('success message');

//for fail response
return response()->fail('fail message');