Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
A Complete guide to Laravel 8 response

A Complete guide to Laravel 8 response

Aman Jain, December 1, 2021November 5, 2023

In this tutorial we will learn about the Laravel response. Laravel has its own library to handle the http response of the application to browser. In the most of the cases response() method is used to send the response back to browser and class Illuminate\Http\Response is also used for same purpose.

Mostly global response function is used to send response and it accepts 2 parameters, first is text and other one is status code of response.

Here are the table of content we are going to explain this article

  • Simple Text Response in Laravel
  • JSON Response in Laravel
  • HTML Response in Laravel
  • Redirect to URL in Laravel
  • Redirect to Internal URL
  • Redirect to External URL
  • Redirect to Named Route
  • Redirect to controller action
  • Attaching flash data with redirect
  • Redirect back to last request with inputs
  • Setting header in Laravel response
  • Setting cookies in Laravel response
  • Download a file in Laravel
  • Display a file in browser

Simple Text Response in laravel

Simple Text Response in Laravel

Text response is a just simple string without any html or specific design. In Laravel most basic response is text in a controller or route.

Route::get('/', function () {
    return 'Readerstacks.com';
});

// in controller

/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
    return 'Readerstacks.com';
}

// or

Route::get('/', function () {
    return response('Readerstacks.com',200);
});

JSON Response in Laravel

Whenever we use APIs in our application the most common response is JSON. We can send JSON response in two way in Laravel. First is returning a array or object and other one is response()->json($json).

Route::get('/', function () {
    return ["status"=>true,"message"=>"Success"];
});

HTML Response in Laravel

Html view is most used in web application. Laravel provides its own method to render or response the html to browser is view($path_to_blade). so we can use this method in our route and controller as below

Route::get('/', function () {
    return view("path_of_blade_file");
});

By default Laravel stores all view file in resource/views folder so if we want to render a html then we need to create a file in resource/views folder. for example creating a file in hello.blade.php

<h1> THis is readerstacks with heading </h1>

Now we can use this as below

Route::get('/', function () {
    return view("hello");
});

Redirect to URL in Laravel

We can redirect to URL in multiple way. Redirection is useful when we want to validate and send back our response to user, send user to external URL, send user forcefully to internal curls etc. Laravel provides numerous way of redirection so they are as follow

Redirect to Internal URL

Global Method redirect($url) is used to redirecting to internal URL.

Route::post('/dashboard', function () {
    // if user is not authenticated then redirect
    return redirect('login');
});

Redirect to External URL

In our application sometimes we need to redirect to external URL in that case we can use away method and we can write redirect()->away($url).

Route::post('/google', function () {
    return redirect()->away('https://www.google.com');
});

Redirect to Named Route

route method of Illuminate\Routing\Redirector is used to redirect a page to named route. When we do not pass any parameter to redirect method then it returns a object of Illuminate\Routing\Redirector. So we can us it as below

Route::post('/dashboard', function () {
    return redirect()->route('login');
});

Named route with parameter

Route::post('/dashboard', function () {
    return redirect()->route('login',["type"=>"facebook"]);
});

Redirect to controller action

We can also call directly a controller action in our route or controller as below

use App\Http\Controllers\PostController;

Route::post('/google', function () {
   return redirect()->action([PostController::class, 'index']);
});

Attaching flash data with redirect

Sometimes we want to send some message after redirect so we can attach a single request session with redirect using with method

use App\Http\Controllers\PostController;

Route::post('/google', function () {
   return redirect()->action([PostController::class, 'index'])->with("message","Success");
});

Redirect back to last request with inputs

While we validating a form we need to send back to user to the form to show validation errors. so Laravel provides an easy way to send back to form using back() method

Route::post('/dashboard', function () {
    return back()->withInput();
});

Setting header in Laravel response

We can set header header method of Illuminate\Http\Response.

Route::post('/dashboard', function () {
    return response("test")
      ->header("auth","token")
      ->header("auth2","token2");
});

Setting cookies in Laravel response

We can set header cookie method of Illuminate\Http\Response.

Route::post('/dashboard', function () {
    return response("test")
      ->cookie("auth","token")
      ->cookie("auth2","token2");
});

Download a file in Laravel

Downloading a file directly from path can be harmful for application so it’s better to download after verifying the request. therefore we can use download method of response object

Route::post('/download-secure-file', function () {
   // validate token etc.
    return response()
      -> download($pathToFile, $name, $headers);
     
});

Display a file or Image in browser

Display a file directly from path can be harmful for application so it’s better to display after verifying the request so we can use file method of response object.

Route::post('/download-secure-file', function () {
   // validate token etc.
    return response()
      -> file($pathToFile, $headers);
     
});

Extending Laravel response

Sometimes you need to extend the response according to your application need so Laravel provides Macros to register your custom method of response .

To register a custom response method we need to register it in App\Providers\AppServiceProvider

<?php

namespace App\Providers;

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

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Response::macro('lower', function ($value) {
            return Response::make(strtolower($value));
        });
    }
}

Macro accepts 2 arguments first is name of method and second is closure function which is executed when called from route or controller as below

Route::post('/custom-response-method', function () {
   
    return response()
      -> lower("THIS IS TEXT");
});

Related

Php Laravel laravelresponse

Post navigation

Previous post
Next post

Related Posts

Php How to Create a Custom Artisan Command in LaravelHow to Create a Custom Artisan Command in Laravel

How to Create a Custom Artisan Command in Laravel ?

May 19, 2022May 26, 2022

Laravel artisan provides several inbuilt commands to help the developer to build a robust applications like to create the controller, models, migration etc. and in this article i will show you to create your own custom artisan command in laravel. This custom artisan can be configure according to your needs…

Read More
Php Laravel 9 CRUD with Search, Image and Pagination

Laravel 9 CRUD with Search Image upload and Pagination

June 25, 2022November 7, 2023

In this article i will learn laravel 9 CRUD with Search Image upload and Pagination. In this post we will not only cover the CRUD operation but also the validation on form, unique validation, image uploading and view the uploaded image, Flash messages, Search the uploaded data and many more….

Read More
Php Laravel where or condition with example

How to use laravel where or condition with example ?

January 15, 2022February 19, 2022

Laravel eloquent provides multiple ways to build the query one the of the feature of laravel eloquent is creating dynamic query based on condition or complicated queries.In this article i will show you to build where or condition in laravel with example. I will show you multiple example to create…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • August 2025
  • July 2025
  • June 2025
  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • The Transformative Power of Education in the Digital Age
  • Understanding High Vulnerabilities: A Closer Look at the Week of July 14, 2025
  • Exploring Fresh Resources for Web Designers and Developers
  • The Intersection of Security and Technology: Understanding Vulnerabilities
  • Mapping Together: The Vibrant Spirit of OpenStreetMap Japan
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version