Laravel

From David's Wiki
Revision as of 05:38, 3 September 2022 by David (talk | contribs)
\( \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.

Security

Vulnerabilities

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

Resources