Example 1: laravel relations find
use App\Models\User;
$user = User::find(1);
foreach ($user->roles as $role) {
}
Example 2: laravel relations find
class Project extends Model
{
public function deployments()
{
return $this->hasManyThrough(
Deployment::class,
Environment::class,
'project_id',
'environment_id',
'id',
'id'
);
}
}
Example 3: laravel relations find
class Mechanic extends Model
{
public function carOwner()
{
return $this->hasOneThrough(
Owner::class,
Car::class,
'mechanic_id',
'car_id',
'id',
'id'
);
}
}
Example 4: laravel relations find
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Mechanic extends Model
{
public function carOwner()
{
return $this->hasOneThrough(Owner::class, Car::class);
}
}
Example 5: laravel relations find
return $this->belongsToMany(Role::class, 'role_user', 'user_id', 'role_id');
Example 6: laravel relations find
return $this->belongsToMany(Role::class, 'role_user');
Example 7: laravel relations find
public function currentPricing()
{
return $this->hasOne(Price::class)->ofMany([
'published_at' => 'max',
'id' => 'max',
], function ($query) {
$query->where('published_at', '<', now());
});
}
Example 8: laravel relations find
public function largestOrder()
{
return $this->hasOne(Order::class)->ofMany('price', 'max');
}
Example 9: laravel relations find
public function oldestOrder()
{
return $this->hasOne(Order::class)->oldestOfMany();
}
Example 10: laravel relations find
public function latestOrder()
{
return $this->hasOne(Order::class)->latestOfMany();
}