Outils pour utilisateurs

Outils du site


informatique:php:laravel

Laravel

Laravel The PHP Framework For Web Artisans.

Voir aussi :

Documentation

Discussion:

News

Handbooks & Cheats sheets

Tutoriels/Tutorials

Creating a Multi-User To-Do Application with Laravel JetStream 2020 with Laravel, Jetstream & Livewire

Laravel 5

Tutoriels:

Exemples:

  • bestmomo/laravel5-3-example with: Home page ; Custom error pages 403, 404 and 503 ; Authentication (registration, login, logout, password reset, mail confirmation, throttle) ; Users roles : administrator (all access), redactor (create and edit post, upload and use medias in personnal directory), and user (create comment in blog) ; Blog with comments ; Search in posts ; Tags on posts ; Contact us page ; Admin dashboard with messages, users, posts, roles and comments ; Users admin (roles filter, show, edit, delete, create, blog report) ; Posts admin (list with dynamic order, show, edit, delete, create) ; Multi users medias gestion ; Localization ; Application tests ; Use of new notifications to send emails and notify redactors for new comments

Tutorials:

Fait avec ou pour Laravel

Free

Starters:

CMS :

No Free

  • Laravel BAP Modular Backend Application Platform + Example CRM with 17 modules

Unknow

CMS on top of Laravel

Unmaintened, abandonned

Packages

Mes indispensables

Actuellement pour Laravel 5.x, à voir si ces packages ont survécus :-)

Admin panel

Menus, CRUD & more :

Préférés:

Autres:

Not free:

Unmaintened:

Only templates:

Validation

Voir aussi model validation

CSRF, XSS, SQL ...

Excluding Routes from the CSRF Middleware in Laravel 5.1

Dans la documentation: routing csrf-excluding-uris

It's now super easy to exclude specific routes from your CSRF middleware:
source: https://mattstauffer.co/blog/excluding-routes-from-the-csrf-middleware-in-laravel-5.1

Plus d'information : Excluding Routes from the CSRF Middleware

// app/Http/Middleware/VerifyCsrfToken
protected $except = [
 'webhook/*'
];

Client side validation

Avec JQuery

Le package proengsoft/laravel-jsvalidation fait la passerelle entre Laravel et “jQuery Validation Plugin” jqueryvalidation. La majorité des règles de validation et ainsi que leurs messages d'erreur sont compatibles, c'est excellent.

Avec Alpine.Js

Rien trouvé. Il y a le micro-framework Ionide mais pas compatible avec Laravel, notamment le format des messages d'erreur.

Avec Vue.js

Pas de réponse à ma question Validation VUE package compatible with Laravel Validator Rules.

Packages à évaluer:

Data, ORM, Eloquent

Boot & initialize Trait

Eloquent peut booter et initialiser les Traits utilisés par les modèles, en utilisant la méthode de nommage boot<Trait> and initialize<Trait>,

https://orkhan.dev/2020/08/17/using-traits-to-boot-and-initialize-eloquent-models/

Model validation

Discussion about Laravel Validation Options – Model, Form Request or Livewire? 2021

  • Je préfère clairement exprimer les règles dans le Model et qu'elles soient vérifiées/validées à l'enregistrement. Le package watson/validating de Dwight Watson le fait parfaitement. Ces règles gérées au niveau du Model peuvent être reprises pour d'autres techniques (Model::getRules()) tout en s'assurant que le Model reste “safe”.

On client side (javascript)

Utiliser côté client les règles de validation et messages d'erreurs définis pour les Models.

Autres

ModelForm, Laravel implementation of Django Forms, is a PHP Form Abstraction for Laravel based on Django Forms and Formset.

versions des données

Gérer les versions des données

Divers

Cursor() vs get()

La méthode cursor() au lieu de get() fonctionne vraiment :-)

Comparaison de la consommation mémoire (avec la même requête):

get() cursor()
memory_get_usage 29 360 128 12 582 912

Nested tree

Gestion d'arborescence (Nested tree structure, Nested category) :

import/export & bulk

Doctrine

Doctrine avec Laravel: http://www.laraveldoctrine.org - Problème: à cause de la forte dépendance de Laravel avec Eloquent, les packages externes continueront d'utiliser Eloquent.

SQL View

GraphQL

    • Laravel ou Symfony
    • expose your Eloquent models in minutes with Anotation as:
      • REST API JSON-LD/RDF, JSON:API, HAL, and many RFCs…
      • GraphQL API
    • automatically expose an OpenAPI specification (formerly Swagger), dynamically generated from your Eloquent models and always up to date
    • benefits from the API Platform JavaScript tools: admin and create client (supports Next/React, Nuxt/Vue.js, Quasar, Vuetify and more!)
  • GraphQLite A PHP library that allows you to write your GraphQL queries in simple-to-write controllers
    • Create a complete GraphQL API by simply annotating your PHP classes
    • Framework agnostic, but Symfony, Laravel and PSR-15 bindings available!
    • Comes with batteries included: queries, mutations, subscriptions, mapping of arrays / iterators, file uploads, security, validation, extendable types and more!
  • Lighthouse A framework for serving GraphQL from Laravel
    • il faut maintenir un fichier contenant le schema

Authentification

Multi-Auth

Laravel 5.2, you may define additional authentication drivers as well define multiple authenticatable models or user tables, and control their authentication process separately from each other. For example, if your application has one database table for “admin” users and one database table for “student” users, you may now use the Auth methods to authenticate against each of these tables separately.

Authentication Scaffolding

Laravel 5.2: This command will generate plain, Bootstrap compatible views for user login, registration, and password reset. The command will also update your routes file with the appropriate routes.

Note: This feature is only meant to be used on new applications, not during application upgrades.

php artisan make:auth

Manage User last login datetime

// Migration
$table->dateTime('last_login_at')->nullable();
 
class User {
 ...
    protected $fillable = [
        'name', 'email', 'password','last_login_at'
    ];
    protected $dates = [
        'created_at', 'updated_at', 'last_login_at'
    ];
}
 
class LoginController {
 ...
 function authenticated( Request $request, $user )
 {
   $user->timestamps = false;
   $user->update([
     'last_login_at' => Carbon::now(),
   ]);
 }

OAuth

Passing parameters to Middleware

source: https://mattstauffer.co/blog/passing-parameters-to-middleware-in-laravel-5.1

Using parameterized middleware in the route defintion. When you're adding middleware to a route definition, you'd normally set it like this:

Route::get('company', ['middleware' => 'auth', function () {
    return view('company.admin');
}]);

So, let's add in our parameter to show that the user must have the owner role:

Route::get('company', ['middleware' => 'auth:owner', function () {
    return view('company.admin');
}]);

Note that you can also pass multiple parameters as a comma-separated list:

Route::get('company', ['middleware' => 'auth:owner,view', function () {
    return view('company.admin');
}]);

How to disable remember me token ?

Simply overload some methods:

class User extends BaseModel implements UserInterface, RemindableInterface
{
  ...
  public function getRememberToken(){
    return null; // not supported
  }
 
  public function setRememberToken($value){
    // not supported
  }
 
  public function getRememberTokenName(){
    return null; // not supported
  }
 
  /**
   * Overrides the method to ignore the remember token.
   */
  public function setAttribute($key, $value)
  {
    $isRememberTokenAttribute = $key == $this->getRememberTokenName();
    if (!$isRememberTokenAttribute)
    {
      parent::setAttribute($key, $value);
    }
  }
  ...

Sentinel

https://cartalyst.com/manual/sentinel

A modern and framework agnostic authorization and authentication package featuring:

  • roles, permissions,
  • custom hashing algorithms and additional security features.

The package follows the FIG standard PSR-4 (Autoloader) to ensure a high level of interoperability between shared PHP code.

The package requires PHP 5.4+ and comes bundled with a Laravel 5 Facade and a Service Provider to simplify the optional framework integration.

Route

Implicit Model Binding

Laravel 5.2: Implicit Model Binding

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

REST API

Simple but usefull RestControllerTrait

Dingo https://github.com/dingo/api/

  • A RESTful API package for the Laravel and Lumen frameworks.

JWT-auth provides a simple means of authentication within Laravel using JSON Web Tokens

Views

Laravel Mix

Laravel Mix provides a fluent API for defining Webpack build steps for your Laravel application using several common CSS and JavaScript pre-processors.

Components

Laravel Collective

  • StydeNet is an extension to the Laravel Collective HTML package.
    • Menus, Alert messages, Form fields, Collection of radios and checkboxes

Component Pull

La documentation View Composers présente l'insertion automatique de données dans des vues que je vois comme du “Component Push”. Ça manque d'exemple, notamment le paradigm du “Component Pull” : Exprimer l'insertion d'un composant depuis une vue.

Appeler le “composant” depuis une vue Blade:

 @inject('navstage', 'NavStage')
 {{ echo $navstage->render() }}.

L'appel @inject() demande au “Service Container” de trouver l'instance d'un objet référencé sous le nom NavStage. Il faut donc que cet objet ai été créer et référencé:

 // dans App/Providers/AppServiceProvider.php
 public function boot()
 {
  $this->app->singleton('NavStage', function ($app) {
   return new \App\Services\NavStage();
  });
 }

Il faut bien sûr qu'existe la classe \App\Services\NavStage avec une méthode render() (cf. la vue Blade).

Nota bene: l'appel {{ $navstage→render() }} n'imprime pas le résultat de l'appel à render(), il faut donc faire un echo dans la méthode.

Nota bene Dans le cas d'un composant qui n'est pas utilisé dans toutes les requêtes, on va préférer le charger que si besoin : Deferred Providers (aka lazy loading)

Parent component

La directive Blade @aware permet d'accéder aux propriétés du composant parent. Attention, les propriétés par défaut qui ne sont pas explicitement attribuées au tag du composant parent ne seront pas accessibles.

Twig template engine with Laravel

Inertia

https://inertiajs.com/how-it-works

Inertia replaces your application's view layer. Instead of using server-side rendering via Blade templates, the views returned by your application are JavaScript page components. This allows you to build your entire front-end using React, Vue, or Svelte while still enjoying the productivity of Laravel or your preferred server-side framework.

At its core, Inertia is essentially a client-side routing library. It allows you to make page visits without forcing a full page reload. This is done using the <Link> component, a light-weight wrapper around a normal anchor link. When you click an Inertia link, Inertia intercepts the click and makes the visit via XHR instead. You can even make these visits programmatically in JavaScript using router.visit().

Wysiwyg editor

CKeditor laravel package:

Laravel file manager (for CKEditor and TinyMCE) with multi-users support

VUE.js

voir Vue.js

Since many JavaScript frameworks also use “curly” braces to indicate a given expression should be displayed in the browser, you may use the @ symbol to inform the Blade … Blade & JavaScript Frameworks

Divers

  • Menu: The spatie/menu package provides a fluent interface to build menus of any size in your php application. If you're building your app with Laravel, the spatie/laravel-menu provides some extra treats.

Localization

Messages de validation en 52 langues pour Laravel4/5: https://github.com/caouecs/Laravel-lang

Manage translation in database:

  • hpolthof/laravel-translations-db a Laravel translations from Database;
    • store translations in the database and default load from files, cache translation, comes with a crud-interface and can perform translations via Google Translate.
  • waavi/translation translation management for Laravel with files, database and cache.
  • spatie/laravel-translation-loader offers a driver based way to store and retrieve translations and ships with a default driver that stores translations in the db.

Manage translation files:

  • barryvdh/laravel-translation-manager is a package to manage Laravel translation files. It does not replace the Translation system, only import/export the php files to a database and make them editable through a webinterface.

Translation in Eloquent ORM

Tests & Testing

Others

Command

$this->getOutput()->isQuiet()       - no verbosity is set                                   (no option set)
$this->getOutput()->isVerbose()     - if the level is quiet or verbose                      (-v)
$this->getOutput()->isVeryVerbose() - if the level is very verbose, verbose or quiet        (-vv)
$this->getOutput()->isDebug()       - if the level is debug, very verbose, verbose or quiet (-vvv)

Cache

Cache Lock

Cache Lock appears with Laravel 5.5, only for Redis et Memcached cache driver. It's not in the cache documentation but in Release documentation.

try {
    $lock = Cache::lock('foo', 10)->block(5);
 
    // Lock acquired after waiting maximum of 5 seconds...
} catch (LockTimeoutException $e) {
    // Unable to acquire lock...
} finally {
    optional($lock)->release();
}

Security

Throttle

Le middleware Illuminate\Routing\Middleware\ThrottleRequests retourne un code HTTP 429 quand le nombre de requêtes dans un nombre de minutes est dépassé. Il utilise le cache Illuminate\Cache\RateLimiter. Pour identifier le client il utilise la méthode fingerprint() de Illuminate\Http\Request.
Malheureusement cette méthode fingerprint() n'utilise que l'IP comme données du client.
Bien qu'il soit impossible de calculer une empreinte sure, j'ai demandé l'ajout du remote port #12872.

Ce bug n'est-il pas réapparu ? Un test unitaire existe-t-il ?

Laravel cookie forgery, decryption, and RCE MWR, 11 April 2014

Infrastructure & serveur

To make default prefixed route working, like /admin or /foo, while a folder with the same name exists, like public/admin or public/foo, should remove the $uri/ from nginx rewriting:

replace
 location / {
  try_files $uri $uri/ /index.php?$query_string ;
 }
by
 location / {
  try_files $uri /index.php?$query_string ;
 }

Error catcher

PhpDoc

Merci à Italo Baeza Cabrera pour Laravel: PHPDocs for Models everyone should have

/**
 * @mixin \Illuminate\Database\Eloquent\Builder
 *
 * @method static \Illuminate\Database\Eloquent\Builder|static query()
 * @method static static make(array $attributes = [])
 * @method static static create(array $attributes = [])
 * @method static static forceCreate(array $attributes)
 * @method \App\Models\User firstOrNew(array $attributes = [], array $values = [])
 * @method \App\Models\User firstOrFail($columns = ['*'])
 * @method \App\Models\User firstOrCreate(array $attributes, array $values = [])
 * @method \App\Models\User firstOr($columns = ['*'], \Closure $callback = null)
 * @method \App\Models\User firstWhere($column, $operator = null, $value = null, $boolean = 'and')
 * @method \App\Models\User updateOrCreate(array $attributes, array $values = [])
 * @method null|static first($columns = ['*'])
 * @method static static findOrFail($id, $columns = ['*'])
 * @method static static findOrNew($id, $columns = ['*'])
 * @method static null|static find($id, $columns = ['*'])
 *
 * @property-read int $id
 *
 * @property string $first_name
 * @property string $last_name
 * @property \Illuminate\Support\Collection|null $favorite_songs
 * @property int $stars
 *
 * @property-read \Illuminate\Support\Carbon $created_at
 * @property-read \Illuminate\Support\Carbon $updated_at
 * @property-read \Illuminate\Support\Carbon $deleted_at
 *
 * @property-read string $full_name
 *
 * @property-read \App\Models\Avatar $avatar
 * @property-read \App\Models\Biography|null $biography
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\Post[] $posts
 *
 * @method \Illuminate\Database\Eloquent\Builder|static age(int $age)
 */

Wordpress and Laravel

Charts & graphs

  • Charts is a multi-library chart package to create interactive charts using laravel (chartjs, highcharts, material, morris …).

Package development

Wordpress and Laravel

Charts & graphs

  • Charts is a multi-library chart package to create interactive charts using laravel (chartjs, highcharts, material, morris …).

Tools

tinker and tinkerWell

Queue and MQ

Laravel Queue

When the queued job is being pulled out from the queue, the CallQueuedListener will check if it’s using the InteractsWithQueue trait, and if it is, the framework will inject the underlying “job” instance inside.

More about horizon.

RabbitMQ

RabbitMQ

Posts:

Libs:

  • RabbitMQ driver for Laravel Queue
  • php-enqueue/laravel-queue (2017-07→2017-12, 2 contributors)
  • Laravel Enqueue message queue extension.
  • Supports AMQP, Amazon SQS, Kafka, Google PubSub, Redis, STOMP, Gearman, Beanstalk and others
  • shaobaojie/laravel_rabbit_mq (updated 2016-07)
  • RabbitMQ Queue driver for Laravel
  • mookofe/tail (2015-03→2016-07, 2 contributors)
  • RabbitMQ and PHP client for Laravel that allows you to add and listen queues messages just simple.
  • Simple queue configuration
  • Multiple server connections
  • Add message to queues easily
  • Listen queues with useful options
  • require videlalvaro/php-amqplib: 2.*
  • bschmitt/laravel-amqp (2016-01→2017-10, 7 contributors)
  • AMQP wrapper for Laravel and Lumen to publish and consume messages
  • Advanced queue configuration
  • Add message to queues easily
  • Listen queues with useful options
  • methods: Amqp::publish(), Amqp::consume()
  • Some concepts were used from mookofe/tail
informatique/php/laravel.txt · Dernière modification : 23/10/2024 06:20 de cyrille

Sauf mention contraire, le contenu de ce wiki est placé sous les termes de la licence suivante : CC0 1.0 Universal
CC0 1.0 Universal Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki