Eloquent models

Contents
A model class
Create rows
Find rows
Update and delete

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

Related articles
Development with PHP
What is Laravel and where it runs
Install Laravel
Your first route
Controllers
Blade basics
Blade advanced
Migrations
Eloquent models
Relationships
Query builder
Seeders and factories
Validation
Auth intro
Hand-rolled login
Middleware
Service container
Config and env
Artisan commands
Events and listeners
Queues
Mail
Cache
Sessions in Laravel
CSRF
Hashing
Sanctum tokens
API resources
Gates and policies
Notifications
Scheduler
Filesystem
Localization
Testing
HTTP tests
Collections
Carbon dates
Pagination
File uploads
Eloquent advanced
Transactions and locks
Deployment
Debugbar and dd
Broadcasting
Full-text search
Capstone: blog
Capstone: JSON API
Capstone: shop cart
Performance: kill N+1
Modern Laravel tour
Hero roadmap: the whole course on one page

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.com
Write to info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: