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.

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

Run Migrations

php artisan migrate

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

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();

Models

@todo

Views

@todo

Controllers

@todo