Posts Learn Components Snippets Categories Tags About
/

How to Get Query Parameters From Request in Laravel 8

Learn how to easily get the query parameters value from the Request class and use it to get data passed on from the URL

Created on Jul 24, 2021

224 views

To retrieve the query parameters on your Laravel backend, you can make use of either the "Request" class or the "request()" helper method.

By using the Request Instance
Imagine you want to get the "search" query from the URL, you can do as follows.
$searchQuery = $request->query('search');

If the requested query string value data is not present, the second argument to this method will be returned.
$name = $request->query('search', 'Learn laravel');

You may call the query method without any arguments in order to retrieve all of the query string values as an associative array.
$query = $request->query();

Full Code Example
<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;

class SearchPost extends Controller
{
    /**
     * Handle the incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function __invoke(Request $request)
    {
        $searchQuerey = $request->query('search', 'Learn laravel');

        $posts = Post::query()->where('title', 'LIKE', $searchQuerey)->take(10)->get();

        return view('posts.index', compact('posts'));
    }
}

By using request() Helper
Otherwise, if you prefer to use the "request()" helper, then it will be like below.
$searchQuery = request()->query('search');

Snippets by

PostSrc poster

PostSrc

Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your project.

View Components

Other Code Snippets

More