Understanding Request URI in Laravel

Used:

Laravel Version 5.8

Before started:

You must already understand about:

Definition:

Laravel have several method for handling URI, namely:

  • fullUrl is used to get the full URL for the request.
  • url is used to get the URL (no query string) for the request.
  • path is used to get the current path info for the request.
  • segments is used to get all of the segments for the request path.
  • segment(argumentNumber) is used to get a segment from the URI (1 based index)
  • fullUrlWithQuery is used to get the full URL for the request with the added query string parameters.

Example

Create an Employee.php inside app/Http/Controllers folder and add this code below:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class Employee extends Controller
{
    function index(Request $request){
      $url = $request->fullUrl();
      echo 'Full URL method: '.$url;
      echo '<br>';
      
      $url = $request->url();
      echo 'URL method: '.$url;
      echo '<br>';
	   
      $path = $request->path();
      echo 'Path Method: '.$path; echo '<br>';
      $path = $request->segments();
      
      echo 'All Segments are: ';
      print_r($path);
      echo '<br>';
   	  
      $path = $request->segment(1);
      echo 'Segmen 1 is: '.$path;
      echo '<br>';
      $path = $request->segment(2);
      echo 'Segmen 2 is: '.$path;
      echo '<br>';
	 
      $url = $request->fullUrlWithQuery(['Berhenti' => 'saja']);
      echo 'Append full URL with Query: '.$url;
	
   }
}

Route Configuration

Add the following line in the routes/web.php file

Route::get('gajian/lambat', 'Employee@index');

Explain:

This route means that if i insert “http://localhost:8000/gajian/lambat” in browser then index function inside Employee Controller is executed

Result

Open your browser and insert this URL “http://localhost:8000/gajian/lambat/?banyak=pengeluaran” then the result is like image below:

Thanks For Reading

You may also like...

Leave a Reply

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