Dev Notes

Various Cheat Sheets and Resources by David Egan/Carawebs.

Laravel Models with Artisan

Artisan, Laravel, PHP
David Egan

Laravel is an open source MVC framework for PHP. Laravel uses the concept of models to store and manage data. Laravel has a command line interface called artisan that amongst other things allows you to easily set up model stubs. The framework uses the concept of “migrations” to manage changes to the app database - and migrations can be created in conjucntion with models.

Create a Database

If you don’t already have one set up, your project will need a database:

Set up a new database with a unique user. Add database user credentials to Laravel’s /.env file.

# Create Database
mysql -u root -p -e "create database new_DB; GRANT ALL PRIVILEGES ON new_DB.* TO new_DB_user@localhost IDENTIFIED BY 'nicelongpassword'"

Create a Model

To make a model called “Experiment”:

php artisan make:model Experiment

Running this command stubs out a basic model under the /app directory.

Make a model with a corresponding migration:

php artisan make:model Experiment -m

Create DB Tables

Run the migrations to set up DB tables:

php artisan migrate

Migration Problems

Sometimes the migration fails because the laravel.log file is not writable by the current user. It needs to be writable by the server user (www-data in the case of Ubuntu/Apache), but the migration is run by your current user. You’ll get an error message like this:

david@david-desktop:$ php artisan migrate
PHP Fatal error: Uncaught UnexpectedValueException:
The stream or file "/var/www/html/your-app/storage/logs/laravel.log"
could not be opened: failed to open stream: Permission denied in

To fix this you could add your user’s primary group to the file ownership:

sudo chown -R www-data:$USER storage/logs/laravel.log

# Allow the file to be group-writable:
sudo chmod 664 storage/logs/laravel.log

This is probably pretty safe on a local development environment - and in most cases I think would be acceptable for production - you’re giving additional write access to your primary user only after all - and if this user has been compromised, file permissions on a log file are the least of your worries.

TODO: It would probably be better to set this up as an ACL as described in the Symfony documentation


comments powered by Disqus