Eloquent models

A model class

An Eloquent model is a PHP class that stands for one database table. By convention the Post model reads the posts table without any configuration.

The fillable list names the columns that mass assignment may fill. It guards the model when you create rows from request data.

namespace App\Models; use Illuminate\Database\Eloquent\Model; class Post extends Model { protected $fillable = ["title", "body"]; }

Create rows

The create method inserts one row from an array and returns the fresh model with its new id. It only fills columns named in the fillable list.

$post = Post::create(["title" => "Hello", "body" => "First post!"]); echo $post->id;

Find rows

The find method loads one row by its primary key, or null when nothing matches. The all method loads every row when the table is small.

$post = Post::find(1); $posts = Post::all(); foreach ($posts as $item) { echo $item->title; }

Update and delete

Change a property and call save to write it back to the database. The delete method removes the row that the model stands for.

$post = Post::find(1); $post->title = "New title"; $post->save(); $post->delete();

Next: Relationships

Article author: Arthur Isaev