Laravel 5 on shared hosting - wrong public_path()

2019-05-07 16:58发布

I deployed a Laravel 5 project to a shared hosting account, placing the app-files outside of the www-folder, placing only the public folder inside of the www-folder. All like explained here, in the best answer: Laravel 4 and the way to deploy app using FTP... without 3. because this file doesn't exist in Laravel 5.

Now when I call public_path() inside of a controller i get something like my-appfiles-outside-of-www/public instead of www/public. Does anyone know why I doesn't get the right path here? Can I change this somewhere? Thanks!

3条回答
可以哭但决不认输i
2楼-- · 2019-05-07 17:14

You can override public_path using container. Example:

App::bind('path.public', function() {
    return base_path().'/public_html';
});
查看更多
在下西门庆
3楼-- · 2019-05-07 17:22

There are a number of solutions, like a change to index.php or the accepted one with the ioc container.

The solution that works best, in my opinion, is described in this SO question: Laravel 5 change public_path()

Why is it better than other solutions? Because it works for regular http request, use of artisan ánd use of phpunit for testing! E.g. the change to index.php works only for http requests but leads to failures when using PHPunit (in my case: file (...) not defined in asset manifest).

A short recap of that solution: Step 1: In the file: bootstrap/app.php change the very first declaration of $app variable from:

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

to:

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

This points to your own custom Application class, which we will create in step 2.

Step 2: Create the file Application.php in the app folder:

<?php namespace App;

class Application extends \Illuminate\Foundation\Application
{
   public function publicPath()
   {
       return $this->basePath . '/../public_html';
   }
}

Be sure to change the path to your needs. The example assumes a directory structure like so:
°°laravel_app
°°°°app
°°°°bootstrap
°°°°config
°°°°...
°°public_html


In case of the OP, the path should probably be

return $this->basePath . '/../www/public';

(up one from laravel_app, then down into www/public)

查看更多
Anthone
4楼-- · 2019-05-07 17:24
$app->bind('path.public', function() {
  return __DIR__;
});

write above code in public_html\index.php above of this code

$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
查看更多
登录 后发表回答