Programster's Blog

Tutorials focusing on Linux, programming, and open-source

Laravel 5 Cheatsheet

Create New Project

mkdir my-project-name
cd my-project-name
composer create-project laravel/laravel . --prefer-dist

To make sure you have the necessary packages on Ubuntu 16.04, you may need to run:

sudo apt update && \
sudo apt install -y php7.0-mbstring php7.0-xml

Running Locally

You can test locally by running:

sudo php -S localhost:80 public/index.php

Then just go to localhost in your browser.

Routing

There are several routing files under the top level routes directory:

  • api.php - routes for an API.
  • channels.php - for websockets and broadcasting.
  • console.php - routes for if you are building a CLI application.
  • web.php - routes for a traditional web application that isn't an API.

There are two main ways to define a route. The first is by actually passing a callback that gets executed.

Route::get('/', function () {
    return view('welcome');
});

The alternative "shorthand" is to pass a string that represents the controller and method to execute.

Route::get('/my/web/path', 'MyController@method');

Official routing docs.

Patterns

If you have routes with variables in the path, then you can use something like the following to pick them up.

Route::pattern('uuid', '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}');

Route::get('users/{uuid}', function ($uuid) { 
    $userController = new App\Http\Controllers\UserController(); 
    return $userController->getUser($uuid);
});

Artisan CLI Tool

Create A Controller

php artisan make:controller MyController

Create a RESTful Resource Controller

php artisan make:controller MyController --resource

Create Model

php artisan make:model MyModel

Create Exception

php artisan make:exception NameOfMyExceptionClass

Create Middleware

php artisan make:middleware MyMiddlewareClass

Run Migrations

php artisan migrate

Reset Database Migrations

If you wish to create your database from scratch again, you can use:

php artisan migrate:refresh

Create A new App Key

php artisan key:generate --show

This will output something like:

base64:9J5F/51QKxxhAxbHvmvJtLIoop6ywOywiev9hWF3wLY=

You need to include the whole thing as the value. E.g. including the base64: part.

Database Migrations

  • Database migrations can be found under database/migrations.
  • By default, you will have two migrations in there that create the users and password_resets tables.
  • Migration filenames are prefixed with the year, month, day, and time in order for the migration tool to know which order to run the migrations.
    • Using the date/time rather than an incrementing integer should hopefully reduce the likelihood of an issue arising when merging two different branches that each created a migration script.

Create A Migration

The following command will create a migration script in your migrations table for creating a table called x.

php artisan make:migration create_x_table

If you don't use create_tableName_table naming convention, then you won't get the starting code within the up/down methods for creating/destroying the table.

Using Raw SQL

If you need use raw SQL, you can just use DB::statement() like below:

public function up()
{
    $createTableQuery = 
        "CREATE TABLE `broker` (
            `id` int unsigned NOT NULL AUTO_INCREMENT,
            `name` varchar(255) NOT NULL,
            `redirect_url` text NOT NULL,
            `secret` varchar(30) NOT NULL,
            `modified_timestamp` timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (`id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8";

    DB::statement($createTableQuery);
}

Laravel Style Migration Example

The following example will create a table that links sections to user-groups and will automatically delete rows in the table when either user-groups or content items are deleted.

public function up()
{
    Schema::create('content_user_group', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('content_id')->unsigned()->nullable(false);
        $table->integer('user_group_id')->unsigned()->nullable(false);
        $table->foreign('content_id')->references('id')->on('content')->onDelete('cascade');
        $table->foreign('user_group_id')->references('id')->on('user_group')->onDelete('cascade');
        $table->timestamps();
    });
}

Run Migrations

You can execute migrations with:

php artisan migrate

If you're just getting started, don't forget to edit the .env file with your database connection details.

Database Queries

Checking Uniqueness

Often you want to check if a record already exists before attempting an insert. For example, when adding a new user, you wish to check that a user with the same email doesn't already exist. For this, do the following:

if (User::where('email', '=', $email)->exists()) 
{
    throw new Exception("A user with that email already exists.");
}

Pluck

You can use ->pluck() to just get the values of one column. For example, the code below will get you a collection object of all the titles of posts where the category_id is 3.

$postTitles = DB::table("posts")
    ->where("category_id", 3)
    ->pluck("title");

The specific collection object is one of Illuminate\Support\Collection

Converting Collection To Array

Queries will return Laravel collections. However, you often want the array form instead. You can do this by executing the ->all() method on the collection. The example below will get an array of all the post titles.

$postTitles = DB::table("posts")
    ->where("category_id", 3)
    ->pluck("title")
    ->all();

Raw Select

Sometimes you need to do a complicated select query and it may be easier just to write it raw. Here is an example:

$rawSelectQuery = 
    "SELECT `id` FROM `myTable`" . 
    " WHERE `type_id`={$myTypeObject->id}" . 
    " AND `id` in (" . 
        "SELECT `some_id` FROM `table2` WHERE `someColumnName`={$someValue}" . 
    ")" . 
    " OR `id` in (SELECT `some_id` FROM `global_items`)";

$results = \DB::select($rawSelectQuery);

Models

Using UUID Primary Keys

If you are using PostgreSQL UUIDs as your primary key, be sure to add the following to your models:

protected $primaryKey = 'uuid';

Also, be sure to add the uuid to your model's $casts attribute so it remains a string rather than trying to be casted to an integer.

protected $casts = [
    'uuid' => 'string',
];

Soft Deletes

To make use of Laravel's soft-delete functionality, just make sure to add the \Illuminate\Database\Eloquent\SoftDeletes trait like so:

class User extends Authenticatable
{
    use \Illuminate\Database\Eloquent\SoftDeletes;

Then make sure to have the deleted_at column in the relevant table, allowing null values. If you set Laravel to using unix timestamps (below), then it needs to be an integer type.

Unix Timestamps for created_at and updated_at

If you would rather not use the SQL timestamp type, and prefer to work with unix timestamp integers, you can get Laravel to do this by editing your model and adding:

public function getDateFormat() { return 'U'; }

Views

@todo

Controllers

@todo

References