Home / Snippets / How to Get Query Parameters From Request in Laravel 8
How to Get Query Parameters From Request in Laravel 8 cover

How to Get Query Parameters From Request in Laravel 8

28.8K

3 years ago

0 comments

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');
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this