many to many relationship laravel code example
Example 1: one to many laravel
For example, a blog post may have an infinite number of comments. And a single
comment belongs to only a single post
class Post extends Model
{
public function comments()
{
return $this->hasMany('App\Models\Comment');
}
}
class Comment extends Model
{
public function post()
{
return $this->belongsTo('App\Models\Post');
}
}
Example 2: laravel detach
// Detach a single role from the user...
$user->roles()->detach($roleId);
// Detach all roles from the user...
$user->roles()->detach();
Example 3: whereHas site:https://laravel.com/docs/
use Illuminate\Database\Eloquent\Builder;
// Retrieve posts with at least one comment containing words like code%...
$posts = Post::whereHas('comments', function (Builder $query) {
$query->where('content', 'like', 'code%');
})->get();
// Retrieve posts with at least ten comments containing words like code%...
$posts = Post::whereHas('comments', function (Builder $query) {
$query->where('content', 'like', 'code%');
}, '>=', 10)->get();
Example 4: laravel pivot table model
/*Model - Service*/
public function customer(){
return $this->belongsToMany('customer')->withPivot(
'start_date',
'stop_date',
'rem_date',
'due_date',
'status'
);
}
/*Model - customer*/
public function services(){
return $this->belongsToMany('Service')->withPivot(
'start_date',
'stop_date',
'rem_date',
'due_date',
'status'
);
}
////These following relations didnt workout
/*Model - custserv*/ //uses the pivot table customer_service//
public function staff(){
return $this->belongsToMany('Staff');
}
/*Model - Staff*/
public function custservs(){
return $this->belongsToMany('Custserv');
}
/*schema for pivot table 'staff' and 'Custserv' */
Schema::create('customer_service_user', function(Blueprint $table)
{
$table->increments('id');
$table->integer('customer_service_id')->unsigned()->index();
$table->foreign('customer_service_id')->references('id')->on('customer_service')->onDelete('cascade');
$table->integer('staff_id')->unsigned()->index();
$table->foreign('staff_id')->references('id')->on('staff')->onDelete('cascade');
$table->timestamps();
});
Example 5: many to many relationship laravel
use App\Models\User;
$user = User::find(1);
$user->roles()->attach($roleId);
Example 6: add the data inside has many relationship laravel
$post = App\Models\Post::find(1);
$comment = $post->comments()->create([
'message' => 'A new comment.',
]);
--------------- OR ------------------
$post->comments()->createMany([
[
'message' => 'A new comment.',
],
[
'message' => 'Another new comment.',
],
]);