Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run ยป
HTML / CSS / JS
<?php // Defining relationships in models // app/Models/User.php class User extends Model { // One user has many posts public function posts() { return $this->hasMany(Post::class); } // One user has one profile public function profile() { return $this->hasOne(Profile::class); } } // app/Models/Post.php class Post extends Model { // Each post belongs to a user public function user() { return $this->belongsTo(User::class); } // Post belongs to many tags (pivot: post_tag) public function tags() { return $this->belongsToMany(Tag::class) ->withPivot('order') ->withTimestamps(); } } // Usage in a controller: // Eager load to avoid N+1 $posts = Post::with(['user', 'tags'])->published()->paginate(10); // Attach/sync many-to-many $post->tags()->sync([1, 2, 3]); // Access pivot data foreach ($post->tags as $tag) { echo $tag->pivot->order; }
Result
Open