Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Notes on working with Laravel 5

Working with Laravel 5

Tools

Usage

Show version: php artisan --version

Show all commands: php artisan list

Show all routes: php artisan route:list

Setup

Key: php artisan key:generate

Frontend scaffolding

Removing frontend scaffolding: php artisan preset none

Setup with Vue: php artisan preset vue

Secure Dotfiles on Apache

<FilesMatch "^\.">
    Order allow,deny
    Deny from all
</FilesMatch>

(Re-)Set the timezone

Set the timezone: sudo dpkg-reconfigure tzdata

Reset the date to the current date: sudo date -s "$(wget -qSO- --max-redirect=0 google.com 2>&1 | grep Date: | cut -d' ' -f5-8)Z"

Setup Homestead with Vagrant

Multiple PHP versions

Execute a command in the command line with a particular PHP version:

  • php5.6 artisan list
  • php7.0 artisan list
  • php7.1 artisan list

Fix authentication failure on bootup

Problem: $ vagrant up results in authentication failure.

default: Warning: Authentication failure. Retrying...

Solution: SSH into the VM via $ ssh vagrant@localhost -p 2222 and remove and regenerate the private keys:

wget https://raw.githubusercontent.com/mitchellh/vagrant/master/keys/vagrant.pub -O .ssh/authorized_keys
chmod 700 .ssh
chmod 600 .ssh/authorized_keys
chown -R vagrant:vagrant .ssh

Mcrypt

Install Mcrypt via Homebrew: brew install mcrypt

Multiple PHP versions

Install Mcrypt for a particular PHP Version: sudo apt install php5.6-mcrypt

Setup Permissions

Make sure to grant Apache access to store data within storage:

  • storage/app
  • storage/framework
  • storage/logs

See: https://gist.github.com/hofmannsven/8392477#permissions

Cookies

Session Cookies

If you don't need session cookies, use the array session driver. (source)

XSRF-TOKEN

In app\Http\Kernel.php comment out \App\Http\Middleware\VerifyCsrfToken::class.

Logs

Daily logs: Add APP_LOG=daily to your .env config file.

Database

Populate: php artisan db:seed

Populate a specific database: php artisan db:seed --database mysql_testing

Queues

Start queue: php artisan queue:work

Run queue forever and save to logfile: nohup php artisan queue:work --daemon > storage/logs/laravel.log &

Migration

Create new migration: php artisan make:migration create_tasks_table --create=tasks

Migrate: php artisan migrate

Migrate, again: php artisan migrate:refresh

Reset database with default seeds: php artisan migrate:fresh --seed

Migrate a specific database: php artisan migrate --database mysql_testing

Model

Create new model: php artisan make:model Task

Create new model and do migration: php artisan make:model Task -m

Model Factory

Create new factory: php artisan make:factory TaskFactory --model="App\Task"

Policy

Create new policy: php artisan make:policy TaskPolicy

Authentication

Create views: php artisan make:auth --views

Middleware

Create: php artisan make:middleware BeforeMiddleware

Events

Note: The name of the event is usally set in past tense (event is already done).

Add new event with listeners in app/Providers/EventServiceProvider.php

Create new events automatically based on your EventServiceProvider: php artisan event:generate

Service Provider

Use the register() method to register keys in the service container. The boot() method is triggered after every service provider has been registered. The list of the providers can be found in config/app.php listed as providers.

Artisan Console

Create command: php artisan make:console AppAbout --command=app:about

Register new command:

Usage: php artisan app:about

Testing

Create a feature test for a controller: php artisan make:test Http/Controllers/UsersControllerTest

Create a unit test for a form request: php artisan make:test Http/Requests/StoreBlogPostTest --unit

Configuration

Add testing database credentials to your phpunit.xml file:

<server name="DB_HOST" value="192.168.10.10"/>
<server name="DB_DATABASE" value="homestead"/>
<server name="DB_USERNAME" value="homestead"/>
<server name="DB_PASSWORD" value="secret"/>

Use temporary in memory database:

<server name="DB_CONNECTION" value="sqlite"/>
<server name="DB_DATABASE" value=":memory:"/>

Composer

Re-generate autoload: composer dump-autoload

List dependencies of all dependencies: composer show --tree

Install on production: composer install --no-dev

Interacting with the application

Usage: php artisan tinker

  • Create an user: factory(App\User::class)->create();
  • Send an email: Mail::to('info@example.com')->send(new App\Mail\AccountCreated);

Performance & Caching

Caching

Clear application cache: php artisan cache:clear

View Caching

Each time you make a change to your Blade service provider you need to clear the view cache.

Clear cache: php artisan view:clear

Route Caching

Cache: php artisan route:cache

Clear: php artisan route:clear

Caching for production

Composer: composer dump-autoload --optimize

Use controllers instead of closures within routes/web.php file to cache routes. Use route:cache to skip route compilation on each request:

php artisan route:cache

Use config:cache to reduce configuration parsing:

php artisan config:cache

The config cache includes config files and also the .env file.

Attention: Make sure to not use env() anywhere in the code base beside the config files! env() will return null with config:cache. Use config() helper function instead.

Generated cache files can be found in: /bootstrap/cache

Eager loading

Use eager loading to avoid the n+1 query problem. Save database queries using the with() helper function and reduce the amout of queries made in total.

User::with('relation_attr')->get();

Database chunking

Reduce server memory usage on queries returning lots of data to not overload the server. Attention: This may increase the database queries and overall loading time! Use chunk() helper function in the query builder.

MySQL indexing

Add index (KEY) columns based an where statemants whenever possible as MySQL is quite fast at indexing which will result in faster queries.

MySQL explain

Set the debug bar config to explain within /config/debugbar.php to explain each SELECT statement:

'explain' => [
  'enabled' => true
]

Multi-column indexes

Set multi-column indexes as new migration from database/migrations/add_table_name_indexes.php:

Schema::table('table_name', function(Blueprint $table) {
  $table->index(['user_id', 'created_at']);
});

Object caching

Use a key-value storage option like Redis or Memcached. Set Redis drivers within .env file:

CACHE_DRIVER=redis
SESSION_DRIVER=redis

And require predis via composer: composer require predis/predis

Make sure to keep an eye on Redis memory usage on user heavy applications and save as litte information as posssbile to Redis to reduce memory usage.

Cache usage

Use and combine auth()->user()->id and other dynamic parameters to generate a unique cache key with md5(). Use the decorator pattern when adding caching to the app.

Autocompletion

Oh My Zsh

Within ~/.zshrc:

plugins=(git laravel5)
@abdelaziz321

This comment has been minimized.

Copy link

abdelaziz321 commented Feb 25, 2018

Very helpful, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.