Laravel 5.5 APP_URL not changing - php

I am trying to change the path output of {{ url('images/image.png') }} and {{ asset('images/image.png') }} Based on my reading, it sounds like I just need to set APP_URL in my .env file and off we go. Well, unfortunately that is not the case. I have set APP_URL=http://localhost in my .env file. I also set 'url' => env('APP_URL', 'http://broken.af') in my config/app.php file. Additionally, I have also tried setting ASSET_URL in both locations with the same result. I have also run artisan cache:clear, artisan config:clear and artisan config:cache. I also tried restarting the server just to be extra sure. For some reason Laravel keeps using the servers configured hostname for these values.
Not a dupe, we are not talking about the route paths, we are talking about the url and asset function and APP_URL and ASSET_URL not doing anything.

I am going to go ahead and post the answer to my question. If UrlGenerator::forceRootUrl is not used, it will inevitably fallback to Request::root() which is implemented as follows: return rtrim($this->getSchemeAndHttpHost().$this->getBaseUrl(), '/');
I am not sure what ASSET_URL or SITE_URL do, if anything. These env variables are definitely not used in the url or asset functions. This does not appear to have changed in later versions of Laravel.
The only way I was able to find to get these variables to work was to manually read them in RouteServiceProvider::boot() and then call forceRootUrl.
public function boot()
{
parent::boot();
/** #var UrlGenerator $url */
$url = $this->app['url'];
// Force the application URL
$url->forceRootUrl(config('app.url'));
}
The trace:
https://github.com/illuminate/routing/blob/master/UrlGenerator.php#L204
https://github.com/illuminate/routing/blob/master/UrlGenerator.php#L492
https://github.com/illuminate/routing/blob/master/UrlGenerator.php#L494
https://github.com/illuminate/http/blob/master/Request.php#L89

As you are trying to get an asset, in your case it's an image it will be right to use asset() laravel helper,
for more information, please check laravel method-asset helper

If you have all your assets in the default public folder, use the Fully Qualified Domain Name (including security protocol) for your APP_URL in your .env file. Example:
APP_URL=https://broken.af
Also use the same for your config/app.php file:
'url' => env('APP_URL', 'https://broken.af'),

If this is helpful for someone, this code worked for me:
$url = env('APP_URL').Storage::url($file->path);
This is how I'm saving the file previously:
$file->path = $request->file("file")->store("public");
I found this answer here
p.d. Don't forget to do the symlink like documentation mention here
php artisan storage:link

Related

Livewire 404: GET http://localhost/livewire/livewire.js net::ERR_ABORTED 404 (Not Found)

I'm learning how to use livewire and laravel, I was trying to bind some data through an input
I wrote this code:
home.blade.php:
<html>
<head>
<title>Home</title>
#livewireStyles
</head>
<body>
#livewire("hello-world")
#livewireScripts
</body>
</html>
hello-world.blade.php:
<div>
<input wire:model="nome" type="text">
<br>
Hello {{ $nome }}
</div>
HelloWorld.php:
<?php
namespace App\Http\Livewire;
use Livewire\Component;
class HelloWorld extends Component
{
public $nome = 'Name';
public function render()
{
return view('livewire.hello-world');
}
}
It is running on Apache 2.4
But if I open the browser console when I load the page I get:
(index):29 GET http://localhost/livewire/livewire.js?id=c1db26b321e994f87254 net::ERR_ABORTED 404 (Not Found)
(index):35 Uncaught ReferenceError: Livewire is not defined
at (index):35
I'm following official docs and screencasts, I tried to follow step-by-step all the instructions but it didin't work either.
Maybe I did something wrong during installation, but I don't think so, because I just hit:
composer require livewire/livewire
so it should be ok.
Any clues?
GitHub repo: learningLaravel
may you can try this:
run: php artisan livewire:publish
then open config/livewire.php
change 'asset_url' => null to 'asset_url' => 'http://localhost'
let dive deep in and find the solution
your request url you can check from your network tab
GET http://localhost/livewire/livewire.js net::ERR_ABORTED
your base url
GET http://localhost/
it should be as
GET http://localhost/your_project_directory
now correct url
GET http://localhost/your_project_directory/livewire/livewire.js
or
GET http://localhost/your_project_directory/public/livewire/livewire.js
Solution:
app/config/livewire.php
'asset_url' => env('APP_URL', 'http://localhost'),
also update the APP_URL accordingly in .env file
you should clear your cache and config
then try I hope this will be fixed the issue
While the answer by Zenabus.dev is listed in the Livewire docs as best practice now, I felt this is only a workaround and does not make clear why this is needed, so I thought I'd elaborate on this a bit and describe what a common reason for the 404 may be and what other options you have.
By default, Livewire registers a route for livewire/livewire.js and requires the request for that URL to go through the Laravel routing. The LivewireJavaScriptAssets controller will then pull the file from the vendor directory and serve it to the user.
If everything worked fine on the dev system and stops working on production like it did for me, chances are that your server / vhost configuration (Apache, Nginx, ...) has a special handling set for Javascript files which will interfere with this process and will try to serve those files directly from your document root, effectively bypassing Laravel.
Please check your server configuration and make sure www.yourapp.com/livewire/livewire.js is actually routed through Laravel (via the public/index.php file).
If it is not, you can either remove any special handling of js files, make sure the rules are only applied if the files actually exist or if you cannot do either, you can resort to publishing the assets as described in https://laravel-livewire.com/docs/2.x/installation#publish-assets.
As a side node, I would personally not add the publish command on post-autoload-dump as described in the docs, but rather on post-update-cmd. I am not comfortable with the assets being published on the production server and would rather do this on the dev system only when needed, and then push the public files to the repository.
In my case what wepe commented worked, only that instead of 'asset_url' => 'http://localhost' i put 'asset_url' => url('/')
I was going through the same challenge ... please do this to sort you out.
run
php artisan livewire:publish
Open the config/livewire.php
edit the line
'asset_url' => null
, to read
'asset_url' => 'http://localhost/your_project/public/',
run the artisan commands to clear the cache and then test. You could copy from here if you are using Linux.
php artisan cache:clear;php artisan config:clear;php artisan route:clear;php artisan view:clear;
Enjoy coding!
To others who experience the same error and nothing above helps.
In my case I had an nginx server that was set to cache and deliver static files like .css and .js and whenever I tried to access a route that had .js then the nginx was trying to find if the file existed and if not, to deliver a 404 error code and prevented laravel to do his thing.
The nginx setting was like this:
location ~* \.(?:css|js)$ {
10 expires 1M;
11 access_log off;
12 add_header Cache-Control "public";
13 }
And i removed the |js.
The following command will publish the assets to your public folder and should solve the 404 issue.
php artisan vendor:publish --force --tag=livewire:assets
The #livewireScripts blade directive is still required, but it automatically correctly fetches the assets from /public/vendor/livewire/livewire.js
open this File confi\livewire.php, then add your public directory path, Replace this 'asset_url' => null,
to
'asset_url' => https://www.yourporject.com/public,
php artisan livewire:publish does NOT throw an error, if the current user does not have permissions to copy the files.
So the public/vendor/livewire folder was missing even after the livewire publish command said it had created it.
Fixing my permissions and
re-running php artisan livewire:publish
did the trick for me.
I am learning Laravel Livewire too and I also encountered the same problem.
My problem was solved by running
php artisan vendor:publish --force --tag=livewire:assets
You can refer to this link on github: Problem loading Livewire.js
I am using Xampp with PHP8. I had to modify the config/livewire.php like below:
'asset_url' => config('app.url').'/public',
where config('app.url') refers to: 'url' => env('APP_URL', 'http://localhost'), in my config/app.php file, that internally refers to: APP_URL=http://localhost/laravel in my .env file.
In config/livewire.php file
'asset_url' => url('/'),

Linking to css file using asset in laravel

Instead of using localhost to access the file, I've used domain name lsapp.com
When I try to link to css file using asset, it links to lsapp.com/css/app.css but doesn't work. Same index.php file in public folder opens while using lsapp.com.
I've tried many different methods but none worked.Please help.
Currently using this but doesn't work
<link href="{{ asset('css/app.css') }}" rel="stylesheet" type="text/css" />
But if I use localhost to open the file, css works fine.
http://localhost/lsapp/public/index.php
Laravel using in latest version Ithink that would be more conventional.
mix.styles([
'asset/css/app.css',
]);
Please refer :
https://laracasts.com/discuss/channels/laravel/best-way-to-use-custom-css-in-laravel
https://laravel.com/docs/5.7/mix
I would recommend to watch the free lesson from laracast over laravel-mix.
https://laracasts.com/series/learn-laravel-mix/episodes/1
You will learn a lot about compiling css & js.
Make sure you have your .env file set up correctly.
"i've set url in config/app.php as 'url' => env( 'http:// www. lsapp.com', http:// localhost')" is wrong.
env() takes a variable name from your .env file, not an URL. Revert those changes back to the default:
'url' => env('APP_URL', 'http://localhost'),
This basically says, "url is either the value of APP_URL from your environment (.env file) or, if that doesn't exist, use http://localhost"
In your .env file, set APP_URL to http://www.lsapp.com, run php artisan config:cache to load and cache the values from .env and you should be good to go.
I think it would be work.
Maybe you are assuming that you have your CSS folder inside your public directory, I think you need to require illuminate/html to your project.

Accessing Laravel .env variables in blade

I am trying to get some API keys which I have stored in my .env file to use in the blade javascript. I have added two keys like:
APP_ENV=local
APP_KEY=////
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost
APP_GOOGLE_MAPS=////
APP_OVERHEID_IO=////
In blade I need to use the Google Maps API and OverheidIO API key. I have tried getting one of the default .env variables just in case I have formatted the custom .env variables wrong.:
{{ env('APP.ENV') }} // nothing
{{ env('APP_ENV') }} // nothing
{{ env('APP_ENV'), 'test' }} // returns 'test'
Could someone help me call the google maps api and overheidio api key in the blade?
Five most important commands if your Laravel is not working as expected after some modifications in .env or database folder or because of any other modifications.
Here is full explanation:
https://www.youtube.com/watch?v=Q1ynDMC8UGg
php artisan config:clear
php artisan cache:clear
composer dump-autoload
php artisan view:clear
php artisan route:clear
VERY IMPORTANT
All env() like: env('APP_ENV') calls WON'T WORK in production (when you use php artisan config:cache)
What to use?
use env() only in config files
use App::environment() for checking the environment (APP_ENV in .env).
use config('app.var') for all other env variables, ex. config('app.debug')
create own config files for your own ENV variables. Example:
In your .env:
MY_VALUE=foo
example config/myconfig.php
return [
'myvalue' => env('MY_VALUE', 'bar'), // 'bar' is default if MY_VALUE is missing in .env
];
Access in your code:
config('myconfig.myvalue') // will result in 'foo'
More details see HERE
I have it implemented in the following way:
#if (env('APP_ENV')!='Production')
Enviroment Test
#endif
My recommendation is to execute the following command: composer self-update
You should only access .env values directly inside configuration files, then access them from everywhere (controllers, views) from configuration files using config() helper
For example:
.env
TEST_URL=http://test
config/app.php
return [
'test_url' => env('TEST_URL','http://default.url')
];
resources/views/welcome.blade.php
{{ config('app.test_url')}}
see configuration caching from laravel documentation for more info.
If you want to get the environment of the app then try this:
{{App::environment()}}
I have not tried other variables.
Since Laravel 7.11, you can use the #env('') and #production() directives in blade templates:
#env('staging')
// The application is running in "staging"...
#endenv
#env(['staging', 'production'])
// The application is running in "staging" or "production"...
#endenv
or
#production
// Production specific content...
#endproduction
See also in the Laravel Blade Documentation.
php artisan config:clear
should fix it
It causes problems to use env() anywhere else than in the config/ folder. Use env in there and then config () in the other parts of the app
get values here: config/app.php
in blade:
{{ config('app.name', 'default value here') }}
in class/controller:
config('app.name', 'default value here')
Here's a link to the documentation: https://laravel.com/docs/6.x/configuration#retrieving-environment-configuration
In the sample below, I spit out the actual error when I'm in my development environment but give a generic message if in any other environment.
#if(App::environment('development'))
Error: {{ $record->s_error }}
#else
XML Parsing Error - Please double check that your file is formatted correctly.
#endif
{{ env('APP_ENV') }}
**If It doesn't work then run the below command. It worked for me. You can try. This command will clear the configuration cache. **
php artisan config:clear
Never use env() anywhere in your code, other than inside config/*.php
Use config() to access default/custom variables in blade files/Controllers.
For example
config('app.name')
config('app.env')
where app is the file name inside the config directory.
you can use any file name inside config directory to access the variable inside it.
Although answers by others are right, i found it hard to understand, so finally read the whole documentation for config page.
Important comment from documentation.
Once the configuration has been cached, the .env file will not be loaded; therefore, the env function will only return external, system level environment variables.
This command should be written after you edit .env file to access variables in easy way
php artisan config:cache
i was also having trouble getting value from .env file, then i did this and it helped :
Check env file and see if you have given the correct value.
then check blade or controller where you using that variable from .env file.
if both steps above goes right, you just need to do these steps -
php artisan config:clear
php artisan cache:clear
php artisan view:clear
php artisan route:clear
composer dump-autoload
Run the following command.
php artisan optimize
if (env('APP_ENV')=='Production')
do something login,verify etc
else
do something
Here env('APP_ENV') won't work in production so better to get from
config folder and make your own file and access that.
Ex:-config/customconfig.php ->make new file
env('APP_ENV'),
];
and then you can access like this
if (config('customconfig.appenv')=='Production')
do something login,verify etc
else
do something
and final run php artisan config:cache

Change default URL or path for whole application?

On my local development I face the issue that my applicaton uses relative path, to the domain, e.g. /css/style.css.
This works generally good, as I can configure virutal hosts on my develop machine, e.g. localhost.foo, so that the relative path is resolved to localhost.foo/css/style.css.
In my current situation, I cannot edit the hosts file to setup a development domain, so that the relative path to the domain does not work anymore. My develop url looks like localhost/projectfoo/public.
So that the app works, it should reference to localhost/projectfoo/public/css/style.css. Based on the relative path in the code it now reference to locahost/css/style.css, and there it will - obviously - not find the requested files.
Is there a way to configure laravel, to use at one case localhost/projectfoo/public as URL and on the other case the standard?
You can always add a new entry in your config files, lets say in the config/app.php
// this is the one that comes with laravel
'url' => 'http://localhost',
// this is the one that you can define
'url_public' => 'http://localhost/something_else/public'
and then use it in your view like:
<link href="{{ config('app.url_public') }}/style/style.css" rel="stylesheet">
Laravel has a helper function asset which generates a full URL for a relative path, based on your config app.url value.
For example, if app.url is http://localhost:
In your view put {{ asset("css/style.css") }} and Laravel will convert this to http://localhost/css/style.css
So in your case all you need to do is change app.url to http://localhost/public and then start using that asset method in your views instead of the relative path.
Better yet, add a new environment variable to your .env file (make sure to put it in .env.example as well) called APP_URL, e.g.
APP_URL=http://localhost
Then in config/app.php set it to:
'url' => env('APP_URL'),
That way you only have to set it once per environment

Laravel phpunit not getting right url

I've changed the app.url config value to the correct url (http://testing.local) for testing locally, however when I run my phpunit tests and try to call(), it is trying to query http://localhost instead of the value of app.url. What do I need to do to get phpunit to call the right path?
I know that it is not actually calling the url, just processing it as if it was, but I can't seem to get it to actually work. Could it have something to do with testing.local directly linking to /public instead of /?
If you want to statically specify a root URL for your tests, add this to phpunit.xml:
<env name="APP_URL" value="http://testing.local"/>
Instead, if you want to change the URL dinamically during your tests, from Laravel 5.4 the $baseUrl method doesn't work anymore.
Also, trying to set the url dinamically with \Config:set('app.url', 'http://testing.local') doesn't work either, as it seems that Laravel caches the root url
You can set dynamically a custom URL with:
\URL::forceRootUrl('http://testing.local');
To change testing url of PHPUnit:
Go to /tests/TestCase.php in your Laravel project.
Change next line to url you need:
// The base URL to use while testing the application.
protected $baseUrl = 'http://newurl.com';
Done.
As stated above, you can use Config::get('app.url') anywhere in your laravel code, including your unit-test.
Note: it is recommended to set this value in your .env file so that it can be set specifically for each environment.
When working with config and .env variables, remember to clear the cache for these with the following commands:
php artisan cache:clear
php artisan config:cache
Laravel has a few functions to get url: (1) url()->current() (2) request()->url()
Both of them are using the same source.
In case of phpunit, tests are setting data there from the config
config('app.url')
and config is getting data from .env record APP_URL.
So you have a few options
1)
to set APP_URL in .env file or in phpunit.xml file - in both cases, a the value is only used in unit tests.
BUT you would have only one URL for all your unit tests.
2)
set APP_URL in runtime
but, you need to do it before function setUp() in Tests\TestCase
public function setUp(): void
{
$_ENV['APP_URL'] = 'example.com';
parent::setUp();
}
Because all the initialisation is hidden in setUp function you CANNOT use
config()->set('app.url',.... Before parent::setUp(); would be too early, and after it - would be too late.
BUT you would have only one URL per unit test file.
3)
request()->headers->set('HOST', 'example.com');
you can set it anywhere after setUp() function and it will overwrite .env and config()
No 'BUTs'.
I think the best way is to set the test app url in phpunit.xml configuration file:
<env name="APP_URL" value="some-url.test"/>
To the best of my understanding, Laravel is supposed to use the 'testing' environment variables when you run PHPUnit. However, I am having the same issue that you are. To get it to work I manually set the app url.
$test_url = Config::get('app.url');
Hope this helps anyone who comes across the same issue.

Categories