Query String in Laravel Framework

  1. Download and install the latest version of Composer from https://getcomposer.org/download/

  2. Open Windows Terminal in Visual Studio Code install Laravel Installer with command as below:

    composer global require laravel/installer
  3. Create new folder named LearnLaravelWithRealApps. Use Visual Studio Code open to LearnLaravelWithRealApps foler. In this folder, create new project named LearnLaravelWithRealApps with command as below:

    laravel new LearnLaravelWithRealApps

  4. Run LearnLaravelWithRealApps project with command as below:

    php artisan serve
  5. Open LearnLaravelWithRealApps project with url as below:

    http://localhost:8000

Create new PHP file named DemoController.php in app/Http/Controllers folder as below:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class DemoController extends Controller
{
    public function index()
    {
        return view('demo/index');
    }

    public function index2(Request $request)
    {
        if ($request->has('id')) {
            $id = $request->get('id');
            echo 'id: ' . $id;
        }
        return view('demo/index');
    }

    public function index3(Request $request)
    {
        if ($request->has('id')) {
            $id = $request->get('id');
            echo 'id: ' . $id;
        }
        if ($request->has('username')) {
            $username = $request->get('username');
            echo '<br>username: ' . $username;
        }
        return view('demo/index');
    }
}

Create new folder named demo in resources/views folder. In this folder, create new Blade file named index.blade.php as below:

<html>

<head>
    <title>Laravel</title>
</head>

<body>
    <h3>Index</h3>
    <a href="{{url('/demo/index2?id=123')}}">Menu 1</a>
    <br>
    <a href="{{url('/demo/index3?id=456&username=acc1')}}">Menu 2</a>
</body>

</html>

Open web.php file in routes folder, add new routes as below:

<?php
				
use Illuminate\Support\Facades\Route;

use App\Http\Controllers\DemoController;

Route::group([], function () {
    Route::get('/', [DemoController::class, 'index']);
    Route::get('/demo', [DemoController::class, 'index']);
    Route::get('/demo/index', [DemoController::class, 'index']);
    Route::get('/demo/index2', [DemoController::class, 'index2']);
    Route::get('/demo/index3', [DemoController::class, 'index3']);
});

Access index action in Demo controller with urls as below:

  • http://localhost:8000
  • http://localhost:8000/demo
  • http://localhost:8000/demo/index

Output

Click Menu 1 link will call to index2 action in Demo controller with following url: http://localhost:8000/demo/index2?id=123

Output

Click Menu 2 link will call to index3 action in Demo controller with following url: http://localhost:8000/demo/index3?id=456&username=acc1

Output