laravel one to many relationship with pivot table code example
Example 1: laravel has one through
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Mechanic extends Model
{
/**
* Get the car's owner.
*/
public function carOwner()
{
return $this->hasOneThrough('App\Owner', 'App\Car');
}
}
Example 2: 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 3: laravel detach
// Detach a single role from the user...
$user->roles()->detach($roleId);
// Detach all roles from the user...
$user->roles()->detach();
Example 4: laravel many to many relationship with pivot table
$user = User::find(1); //any user we want to find
$user->trophies()->attach($idOfTrophy);
//pass id or array of a Trophy ids
//suppose admin has selected the trophy from a form and trophy id
// is in $request object, then.
$trophyId = $request->trophy_id;
$user->trophies()->attach($trophyId); //record is created in DB.
attach and syncWithoutDetaching both does same job
Example 5: laravel many to many relationship with pivot table
$trophyIds = Trophy::where('some_column','some_value') ->pluck('id')->toArray(); //it will give array of ids.$user->trophies()->detach($trophyIds); //deletes given trophies of $user
Example 6: laravel many to many update all pivot
$user->customviews()
->newPivotStatement()
->where('user_id', '=', $user->id)
->update(array('default' => 0));