<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
abdelhamiderrahmouni / laravel-pivot-relations-eager-loading example snippets
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\Pivot;
class UserSkill extends Pivot
{
protected $table = 'user_skill';
public function scale(): BelongsTo
{
return $this->belongsTo(Scale::class);
}
}
declare(strict_types=1);
namespace App\Models;
use LaravelPivotRelationsEagerLoading\Concerns\WithPivotRelationsLoading;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
use WithPivotRelationsLoading;
public function skills(): BelongsToMany
{
return $this->belongsToMany(Skill::class, 'user_skill')
->using(UserSkill::class)
->withTimestamps()
->withPivot(['scale_id']);
}
}
$users = User::query()->with('skills.pivot.scale')->get();
foreach ($users as $user) {
foreach ($user->skills as $skill) {
// The scale relationship is already loaded - no N+1 queries!
$scale = $skill->pivot->scale;
}
}
declare(strict_types=1);
namespace App\Models;
use LaravelPivotRelationsEagerLoading\Concerns\WithPivotRelationsLoading;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
use WithPivotRelationsLoading;
public function skills(): BelongsToMany
{
return $this->belongsToMany(Skill::class, 'user_skill')
->using(UserSkill::class)
->withTimestamps()
->withPivot(['scale_id'])
->withPivotRelations('scale');
}
}
$users = User::query()->with('skills')->get();
foreach ($users as $user) {
foreach ($user->skills as $skill) {
// The scale relationship is already loaded - no N+1 queries!
$scale = $skill->pivot->scale;
}
}
declare(strict_types=1);
namespace App\Models;
use LaravelPivotRelationsEagerLoading\Concerns\WithPivotRelationsLoading;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use WithPivotRelationsLoading;
public function tags(): MorphToMany
{
return $this->morphToMany(Tag::class, 'taggable')
->using(Taggable::class)
->withPivotRelations('creator');
}
}
public function posts(): MorphToMany
{
return $this->morphedByMany(Post::class, 'taggable')
->using(Taggable::class)
->withPivot('added_by')
->withPivotRelations('addedBy');
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.