Friday, 14 December 2018

Base url in Laravel

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') }}">

No comments:

Post a Comment

How to run multiple Laravel projects at same time?

Multiple Laravel Projects First run your first laravel project blog as follows: Open your command prompt and go to your drive where your...