How to get URL parameters into Controller in laravel

May 24, 2022
Laravel
How to get URL parameters into Controller in laravel

In this article, you will learn 2 ways on how to get the URL parameters from the GET request in laravel. By the end of the article, you will be able to get the URL parameters into controller in laravel.

We will be discussing:

  1. How to get the URL parameters attached to the URL after the question mark in laravel ?
  2. How to get the URL parameters attached to the URL without the question mark in laravel?

Let’s get Started!

1. How to get the URL parameters attached to the URL after the question mark in laravel ?

So lets you have the URL like his

http://www.yoursite.com/page?name=hussain

And you need to get the value of name variable.

Step 1: Register Route

You need to first register the route. In our case we have created the Controller PagesController and register as the name page.

Route::get('page', [PagesController::class, 'page'])->name('page');

Step 2: Create Controller Function

Lets create the function page in the PagesController. In which we are getting the value of name field.

// PagesController.php

public function page(Request $request)
    {

        $name= $request->name
        echo $name
    }

Now if you call the in browser http://www.yoursite.com/page?name=hussain, you will get the that name field value.

2. How to get the URL parameters attached to the URL without the question mark in laravel ?

So lets you have the URL like his

http://www.yoursite.com/page/hussain

And you need to get the value hussain or anthing which you have set.

Step 1: Register Route

You need to first register the route like following.

Route::get('page/{name}', [PagesController::class, 'page'])->name('page');

In our case we have created the Controller PagesController and register as the name page.

Step 2: Create Controller Function

Lets create the function page in the PagesController.

// PagesController.php

public function page($name)
    {

        echo $name
    }

This will print the hussain in our case.

Conclusion:

Hope in the article above, you have learnt both ways of getting the URL parameters from the GET request in laravel.

Let me know know if you have any questions, see you in the next one.

Write a Reply or Comment

Your email address will not be published. Required fields are marked *


Icon