agyanadda@gmail.com

Laravel Request and Response

Laravel Basics 1 min read Updated Dec 2, 2026 Topic 9 of 31

Every controller method can receive the Request object and must return a Response.

Reading input

Type-hint Request $request and Laravel gives you the current request:

  • $request->input('name') — a form field or JSON value
  • $request->input('city', 'Patna') — with a default
  • $request->query('page') — only the query string (?page=2)
  • $request->only(['name', 'email']) / $request->except(['password'])
  • $request->has('remember'), $request->filled('phone')
  • $request->file('photo') — an uploaded file
  • $request->ip(), $request->user(), $request->is('admin/*')

Kinds of responses

  • return view('home', ['name' => 'Asha']);
  • return redirect()->route('posts.index'); or return back();
  • return response()->json(['ok' => true]);
  • return response()->download($path);
  • abort(404); — stop and show an error page

Flash data

redirect()->back()->with('success', 'Saved!') stores a message for the next request only — perfect for "saved successfully" alerts.

Example

Example — Search page with query string PHP
<?php
use Illuminate\Http\Request;

// GET /search?q=laravel&page=2
public function search(Request $request)
{
    $q = trim($request->query('q', ''));

    if ($q === '') {
        return redirect()->route('home')->with('error', 'Type something to search');
    }

    if ($request->wantsJson()) {
        return response()->json(['query' => $q, 'results' => []]);
    }

    return view('search', ['q' => $q]);
}

/search?q=laravel shows the search view. An empty search redirects home with a one-time error message. A request that asks for JSON gets {"query":"laravel","results":[]}.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which method reads only the query string value ?page=2?

Exercise 2 True / False

Data added with ->with() on a redirect is available only for the next request.

Exercise 3 Fill in the Blank

Call ___(404) to stop and show a Not Found page.

Frequently Asked Questions

has('phone') is true if the field was sent at all, even empty. filled('phone') is true only if it was sent and is not empty.