Showing posts with label Get Full URL. Show all posts
Showing posts with label Get Full URL. Show all posts

Friday, February 24, 2017

Get Current URL Using Laravel

Laravel is a strong php based framework today. We frequently coding on this platform. And who coded its important for him to know / get current working url sometimes. Its easy to get current url inside an Controller/Service class. Just need to use Request attribute to get desired output at Laravel. 

First need to import Request class to Controller/Service class:
use Illuminate\Http\Request;

And then need to pass Request as parameter as follows:
public function someAction(Request $request)

And finally use following method to get current full url:
$request->fullUrl();

You have different options when you use Laravel Request class as follows:

Get the request method
$request->method();

Get the root URL for the application
$request->root();

Get the URL (no query string) for the request
$request->url();

Get the full URL for the request
$request->fullUrl();

Get the current path info for the request
$request->path();

Determine if the request is the result of an AJAX call
$request->ajax(); 


There is another way around to get URL from Laravel Controller
At first you have to import following component:
use Illuminate\Routing\UrlGenerator;

Then need to initialize it on construct on controller as follows:
private $UrlGenerator;
public function __construct(UrlGenerator $UrlGenerator)
{
    $this->UrlGenerator = $UrlGenerator;
}

And then use below line of code get Laravel base URL:
$urlGenerator->to("/");

You can get all available method details of UrlGenerator from below link:
https://laravel.com/api/5.0/Illuminate/Routing/UrlGenerator.html