Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run ยป
HTML / CSS / JS
// app/Models/Post.php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Post extends Model { protected $fillable = ['title', 'body', 'user_id', 'published_at']; protected $casts = ['published_at' => 'datetime']; public function user() { return $this->belongsTo(User::class); } public function tags() { return $this->belongsToMany(Tag::class); } public function scopePublished($query) { return $query->whereNotNull('published_at'); } } // Eloquent queries $posts = Post::published()->latest()->paginate(10); $post = Post::with('user', 'tags')->findOrFail($id); $post = Post::create(['title' => 'Hello', 'body' => 'World', 'user_id' => 1]); $post->update(['title' => 'Updated Title']); $post->delete(); // Relationships $user = User::find(1); $posts = $user->posts()->where('published_at', '!=', null)->get(); echo $post->user->name;
Result
Open