Laravel 5 change public_path()

2019-01-06 10:30发布

I am trying to move the public folder to other place. However, I can't find the place to modify public_path() variable. Now, the 'public_path()' return the wrong path of folder.

Where can I set the variable for public_path()?

5条回答
神经病院院长
2楼-- · 2019-01-06 10:39

I suggest you add it in app/Providers/AppServiceProvider.php:

public function register()
{
    $this->app->bind('path.public', function() {
        return realpath(base_path().'/../public_html');
    });
}

This affects artisan as well.

查看更多
ら.Afraid
3楼-- · 2019-01-06 10:41
$app->bind('path.public', function() {
  return base_path().'/mynewpublic';
});
查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-01-06 10:45

You can override the public path using ioc container :

What worked for me flawlessly was adding to public/index.php the following three lines:

 $app->bind('path.public', function() {
    return __DIR__;
});

For more detailed explanation click here

查看更多
孤傲高冷的网名
5楼-- · 2019-01-06 10:52

In laravel 5.6 this work for me ... adding this code to bootstrap/app.php :

$app->bind('path.public', function() {
    return realpath(__DIR__.'/../');
});

where __DIR__.'/../' is path to your public folder

查看更多
老娘就宠你
6楼-- · 2019-01-06 10:54

While accepted answer works for requests coming from HTTP, it will not work for artisan.

If you need artisan to know your custom public path, you need to extend Laravel main Application class. I know it sounds scary, but it's actually very simple.

All you need to do is following:
Step 1: In the file: bootstrap/app.php change the very first declaration of $app variable

$app = new Illuminate\Foundation\Application(
    realpath(__DIR__.'/../')
);

to reflect your own custom Application class:

$app = new App\Application(
    realpath(__DIR__.'/../')
);

Step 2: Define your custom Application class somewhere. For example in app/Application.php

<?php namespace App;

class Application extends \Illuminate\Foundation\Application
{
}

Congrats! You have extended Laravel core Application class.

Step 3: Overwrite the publicPath method. Copy and paste Laravel original method to your new class and change it to your needs. In my particular case I did like this:

public function publicPath()
{
    return $this->basePath.DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'public_html';
}

That's it! You can overwrite any method in Application class the same way.

查看更多
登录 后发表回答