How to find the Laravel base url?

Asked

Viewed 1,906 times

2

I remember that when I used the Codeigniter framework, I could find out what the base url of the application was by simply calling base_url(). On Laravel 3, I wore URL::base().

But now, on the Laravel 5, when I called URL::base(), returns the following error:

Badmethodcallexception with message 'Method base does not exist.'

I tested on Laravel 4, and the same error occurs.

So, what is the correct way to find out the base url of the application, using Laravel 4 or 5?

3 answers

1

  • Good. I tested it here on php artisan tinker (Laravel 4) and it worked. But it didn’t even have to call the bar, just use url().

1


There are several helpers to generate urls in Laravel, it is necessary to understand what would be the use case where you need only the url groundwork.

In any case, we can use the helper url() that exists since version 4 of Laravel.

$siteRoot = url('/');

It is important to insert the bar, because the from the Laravel 5.2, the helper url() will return a instance of Urlgenerator.

  • Important information. When you pass NULL in url, he really returns UrlGenerator. I haven’t seen it yet, but I’ll make sure he uses it __toString internally.

  • Do not @Wallacemaxters

  • I saw it here. It’s important to pass at least one string empty. Interactly it checks whether the parameter is NULL.

  • The author of the previous answer does not take me wrong, but I believe that this answer is more complete.

0

In version 4 of Laravel, it is possible to do this using the method URL::to(), but it is necessary to put a bar or an empty string as parameter.

 $base = URL::to('');

 // ou 

 $base = URL::to('/')

This will also work in version 5 of Laravel, but in this case it is better to use the function url(), as mentioned in the other reply.

  • Why not use the helper in Laravel 4? It already existed there https://laravel.com/docs/4.2/helpers#urls

  • @gmsantos I just found out I had this function now that I asked the question, hehehe. In any case, I often try very hard to maintain a pattern. I realized that the use of functions has become very common since the Laravel 5. In versions 4, it was common to always have a Facade class with an Alias, for you to use a resource or a third-party library. Anyway, that information is welcome

  • At the time of Laravel 4 was more common even the Facades, thankfully they are falling into disuse

  • I also think that stabbing can sometimes cause problems, especially with not using namespace (by default), can generate name conflicts. You’ve seen it, right.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.