Simple question, but the answer seems quite hard to come by. In Codeigniter, I could load the url helper and then simply do
echo base_url();
<
Updates from 2018 Laravel release(5.7) documentation with some more url() functions and it's usage.
Question: To get the site's URL in Laravel?
This is kind of a general question, so we can split it.
1. Accessing The Base URL
// Get the base URL.
echo url('');
// Get the app URL from configuration which we set in .env file.
echo config('app.url');
2. Accessing The Current URL
// Get the current URL without the query string.
echo url()->current();
// Get the current URL including the query string.
echo url()->full();
// Get the full URL for the previous request.
echo url()->previous();
3. URLs For Named Routes
// http://example.com/home
echo route('home');
4. URLs To Assets(Public)
// Get the URL to the assets, mostly the base url itself.
echo asset('');
5. File URLs
use Illuminate\Support\Facades\Storage;
$url = Storage::url('file.jpg'); // stored in /storage/app/public
echo url($url);
Each of these methods may also be accessed via the URL facade:
use Illuminate\Support\Facades\URL;
echo URL::to(''); // Base URL
echo URL::current(); // Current URL
How to call these Helper functions from blade Template(Views) with usage.
// http://example.com/login
{{ url('/login') }}
// http://example.com/css/app.css
{{ asset('css/app.css') }}
// http://example.com/login
{{ route('login') }}
// usage
<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
<!-- Login link -->
<a class="nav-link" href="{{ route('login') }}">Login</a>
<!-- Login Post URL -->
<form method="POST" action="{{ url('/login') }}">
You can use the URL facade which lets you do calls to the URL generator
So you can do:
URL::to('/');
You can also use the application container:
$app->make('url')->to('/');
$app['url']->to('/');
App::make('url')->to('/');
Or inject the UrlGenerator:
<?php
namespace Vendor\Your\Class\Namespace;
use Illuminate\Routing\UrlGenerator;
class Classname
{
protected $url;
public function __construct(UrlGenerator $url)
{
$this->url = $url;
}
public function methodName()
{
$this->url->to('/');
}
}
Another possibility: {{ URL::route('index') }}
You can also use URL::to('/') to display image in Laravel. Please see below:
<img src="{{URL::to('/')}}/images/{{ $post->image }}" height="100" weight="100">
Assume that, your image is stored under "public/images".
For Laravel 5 I normally use:
<a href="{{ url('/path/uri') }}">Link Text</a>
I'm of the understanding that using the url()
function is calling the same Facade
as URL::to()