I want to retrieve data from Model employee.php by laravel eloquent relationship features. But I could't do it.
Model : Employee.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Employee extends Model
{
protected $table = 'employees';
protected $fillable = [
'name','fatname','designation_id','rank','office_id','join_date','phone','address','active',
];
protected $primaryKey = 'id';
public $timestamps = false;
public function designation(){
return $this->belongsTo(Designation::class, 'designation_id');
}
public function office(){
return $this->belongsTo(Office::class, 'office_id');
}
}
EmployeeController.php
<?php
namespace App\Http\Controllers\API;
use App\Employee;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
class EmployeeController extends Controller
{
public function index()
{
//Joing Query
return DB::table('employees')
->join('designations', 'employees.designation_id', '=', 'designations.id')
->join('offices', 'employees.office_id', '=', 'offices.id')
->select('employees.*', 'designations.name', 'designations.seniority', 'offices.name')
->orderBy('designations.seniority', 'asc')
->get();
//Alternative Way
//Eloquent Relationship
// offices and designation two table
return Employee::with(['office', 'designation'])
->where('active', 1)
->orderby('designation.seniority', 'asc')
->get();
}
But the Eloquent Relationship is not working here orderby designation field. How can I solve it?