I have 2 tables employees and employee_locations. One employee has many locations. I need to find out one employee record with related latest employee_locations record. I wrote below query.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Employee_location;
class Employee extends Model
{
protected $fillable = ['name', 'emi_number', 'account_id'];
public function employee_locations()
{
return $this->hasMany(Employee_location::class);
}
}
But now lets say that you want to change some part of relation.. That could be sorting, amount or something else. Then you would use a function to specify that. Notice how the function is linked to the 'employee_locations'
$employees = Employee::with(['employee_locations' => function($query) {
$query->where('status', 1)->latest()->limit(5); //here we say that status of locations must be 1, that we want them order by latest and to only get 5.
})->find([1]);