📚 Cheatsheet

Une collection organisée de snippets de code pour accélérer votre développement. Parcourez, recherchez et copiez en un clic.

Snippets 12

Retour
Assignation de masse (Mass Assignment)
Intermédiaire
// Dans le modèle : protected $fillable = ['name'];

$flight = Flight::create(['name' => 'London']);
Construire une requête avec where()
Facile
$users = User::where('active', 1)->orderBy('name')->get();
Créer un nouvel enregistrement
Facile
$flight = new Flight;
$flight->name = 'Paris';
$flight->save();
Eager Loading (chargement anticipé)
Avancé
$books = Book::with('author')->get();
Mettre à jour un modèle
Facile
$flight = Flight::find(1);
$flight->name = 'San Diego';
$flight->save();
Récupérer tous les modèles
Facile
$flights = Flight::all();
Relation Many-to-Many
Avancé
public function roles()
{
    return $this->belongsToMany(Role::class);
}
Relation One-to-Many
Intermédiaire
public function posts()
{
    return $this->hasMany(Post::class);
}
Relation One-to-One
Intermédiaire
public function phone()
{
    return $this->hasOne(Phone::class);
}
Soft Deleting (suppression douce)
Avancé
// Dans le modèle : use SoftDeletes;

Flight::find(1)->delete();
Supprimer un modèle
Facile
$flight = Flight::find(1);
$flight->delete();
Trouver un modèle par sa clé primaire
Facile
$flight = Flight::find(1);