Laravel

From David's Wiki
\( \newcommand{\P}[]{\unicode{xB6}} \newcommand{\AA}[]{\unicode{x212B}} \newcommand{\empty}[]{\emptyset} \newcommand{\O}[]{\emptyset} \newcommand{\Alpha}[]{Α} \newcommand{\Beta}[]{Β} \newcommand{\Epsilon}[]{Ε} \newcommand{\Iota}[]{Ι} \newcommand{\Kappa}[]{Κ} \newcommand{\Rho}[]{Ρ} \newcommand{\Tau}[]{Τ} \newcommand{\Zeta}[]{Ζ} \newcommand{\Mu}[]{\unicode{x039C}} \newcommand{\Chi}[]{Χ} \newcommand{\Eta}[]{\unicode{x0397}} \newcommand{\Nu}[]{\unicode{x039D}} \newcommand{\Omicron}[]{\unicode{x039F}} \DeclareMathOperator{\sgn}{sgn} \def\oiint{\mathop{\vcenter{\mathchoice{\huge\unicode{x222F}\,}{\unicode{x222F}}{\unicode{x222F}}{\unicode{x222F}}}\,}\nolimits} \def\oiiint{\mathop{\vcenter{\mathchoice{\huge\unicode{x2230}\,}{\unicode{x2230}}{\unicode{x2230}}{\unicode{x2230}}}\,}\nolimits} \)

Laravel is a popular MVC framework for PHP.
One of the best parts of Laravel is their excellent video course on web development. The course is published on Laracasts.

Usage

Installation

composer global require laravel/installer

Creating a new project

Run the following commands.
Initialize a laravel project then cd into your project folder and install all php and node dependencies.
Then point your webserver to your project's public folder or run php artisan serve to start a local development server.

laravel new my-project
# Equivalent to
# composer create-project --prefer-dist laravel/laravel my-project
cd my-project
composer install
npm install

Copying an existing project

After you git pull an existing project, you will need to do the following to get it running.
Note: The app key is used for encrypting cookies.
Users will lose their session if the app key is regenerated in production.

composer install
npm ci
cp .env.example .env
# Fill in the .env config variables such as database, mail server, API keys, ...
php artisan key:generate
# Use npm run prod for production
npm run dev

Blade

Components

Note: Components were completely revamped in Laravel 7.

If you don't know anything watch Blade Component Cookbook or read the Blade Templates.

Components in Laravel 7 have two parts:

  • A php script in app/View/Components. E.g. MyComponent.php
  • A blade template in resources/views/components. E.g. my-component.blade.php

To get started, run:

php artisan make:component Alert

Controllers

Documentation
Controllers handle requests. The route file associates entry points with controller methods.
To make a controller, run php artisan make:controller <name of controller>.
Add the -r flag to automatically add REST methods.

Routing

Routing is handled in the routes/web.php file.
Documentation

RESTful

Note that for put, patch, delete you will need @method('PATCH') in your form html element.
Or you can use an ajax request via fetch or jQuery.

Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);

Theses can also be simplified with a single Route::resource($uri, $className); for a resource controller

Parameters/Variables

Route::get('user/{id}', function ($id) {
    return 'User '.$id;
});

Database

Query Builder

From subquery
$subquery = DB::connection('bayarea')->table(DB::raw("restaurants x, parking y"))
  ->select("x.id as id1", "y.id as id2")->where("x.id", "=", $restaurant_id);
$mainquery = DB::connection('bayarea')->table(DB::raw("({$subquery->toSql()}) as t1"))->mergeBindings($subquery)->...->get();

Laravel Mix

Laravel mix is an asset compiler/minifier for Laravel which uses webpack.
Your configuration will be in webpack.mix.js
The following may be convenient:

const fs = require('fs-extra');
class Rm {
    name() {
        return "rm";
    }
    register(to) {
        fs.removeSync(to);
    }
}
mix.extend('rm', new Rm());

JavaScript

Passing variables from PHP to JavaScript

Variables can be passed from PHP to JS using view replacement. Note that while your JS is typically separate from your view, you will need to include some JS in your view to use this feature.
Example.

Deployment

Directly

Point your webserver with PHP to the public folder.
If your application is publically accessible, make sure APP_DEBUG is set to false.

Docker

See the example Dockerfile below:

# Dockerfile
FROM php:8.1-apache
RUN apt-get update && \
    apt-get install -y nodejs npm zip libpq-dev sudo && \
    a2enmod rewrite
COPY --from=composer:latest /usr/bin/composer /usr/local/bin/composer
ENV APACHE_DOCUMENT_ROOT /var/www/html/public
RUN sed -ri -e 's!/var/www/html!${APACHE_DOCUMENT_ROOT}!g' /etc/apache2/sites-available/*.conf
RUN sed -ri -e 's!/var/www/!${APACHE_DOCUMENT_ROOT}!g' /etc/apache2/apache2.conf /etc/apache2/conf-available/*.conf
RUN sed -i 's#AllowOverride [Nn]one#AllowOverride All#' /etc/apache2/apache2.conf
RUN mv "$PHP_INI_DIR/php.ini-production" "$PHP_INI_DIR/php.ini"
# RUN sed -i 's#upload_max_filesize = 2M#upload_max_filesize = 200M#' "$PHP_INI_DIR/php.ini"
# RUN sed -i 's#post_max_size = 8M#post_max_size = 200M#' "$PHP_INI_DIR/php.ini"
RUN chown www-data:www-data /var/www -R
ADD package.json package-lock.json /var/www/html/
RUN sudo -u www-data npm ci
ADD composer.json composer.lock artisan /var/www/html/
ADD app /var/www/html/app
ADD config /var/www/html/config
ADD database /var/www/html/database
ADD bootstrap /var/www/html/bootstrap
ADD routes /var/www/html/routes
RUN composer install
# Add remaining files
ADD . /var/www/html/ 
RUN cp .env.prod.example .env
RUN chmod 775 /root && \
    chown www-data:www-data -R /var/www/html && \
    npm run prod

Security

Vulnerabilities

  • CVE-2021-3129 - In Laravel < 8.4.2, leaving debug mode on can lead to remote execution.

Resources