How to set file permissions for Laravel 5 on mac OSX

Quick Tip

If you can't be bothered to setup apache, Laravel has a super clean way to spin up a built-in PHP server. All you have to do is from your project, run:

php artisan serve

This will fire up a server on localhost / 127.0.0.1:8000 which is easily accessible. I now use this for all my local developement work and I never run into any permission issues as detailed below!

The dreaded laravel.log could not be opened

The offending error message looks like the one below.

Error in exception handler: The stream or file "laravel/app/storage/logs/laravel.log" could not be opened: failed to open stream: Permission denied

The quick and easy solution to this is just to set everything to, or at least the folders in question to have file permissions of 777, but this is a really bad idea. By doing so you are giving everyone the ability to read, write and execute the files on your server. You absolutely don't want this to be the case.

Setting the correct file permissions

There are different approaches to it, but when working locally or on a development environment, i like it when my user shares ownership with Apache (the web server).

_www is the Apache user on mac osx, so we'll use this in our examples. Issue the following command in your terminal:

sudo chown -R $USER:_www /path/to/laravel/install

This command changes the owner / group to be your username and the web server.

Next we need to give the correct folders the permissions they need, issue the follow commands:

sudo find /path/to/laravel/install -type f -exec chmod 664 {} \; 
sudo find /path/to/laravel/install -type d -exec chmod 775 {} \;

What this does is find every file (-type f) and every directory (-type d) and execute the chmod command to 664 and 775 respectively. The find command does all the hard work for you and is much quicker that doing each file/folder individually.

Giving the web server the correct file permissions

Finally, you need to make it so that the web server can write to the files/folders it needs to, such as the app/ and storage/folders. Issue the following commands:

cd /path/to/laravel/install
sudo chgrp -R _www storage bootstrap/cache
sudo chmod -R ug+rwx storage bootstrap/cache

This command changes the owning group (_www) recursively across the storage and bootstrap/cache folders and then gives the web server read, write and execute permissions.

This should be all that you need. You now have Laravel setup in a way that your user still has control over all the files and the web server can read and write to files when necessary.

Working with Production servers

If you are working on a live environment, you will probably want it so that web server (Apache) has ownership of the files and folders. If so, just replace $USER:_www with www-data:www-data (I'm assuming you're using a Debian based OS like Ubuntu here, replace www-data with whatever the web server user is, if not).


More Posts