Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

kshitizmittal's avatar

Convert this query to eloquent

I want to convert this query to eloquent

select result.degname,COUNT(result.emp_id) from (Select ed.emp_id,deg.degname from employeedetails as ed LEFT JOIN designations as deg on ed.designation = deg.degid) as result GROUP BY result.degname
0 likes
1 reply
mariohbrino's avatar

Here is an example of how you can do this, this is standardized for laravel.

Migrations - designations and employee_details

Schema::create('designations', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->timestamps();
});

Schema::create('employee_details', function (Blueprint $table) {
    $table->increments('id');
    $table->unsignedInteger('designation_id');
    $table->timestamps();

    $table->foreign('designation_id')
        ->references('id')
        ->on('designations')
        ->onDelete('cascade');
});

Models - relationships one to many

class EmployeeDetail extends Model
{
    protected $table = 'employee_details';

    public $fillable = [
        'designation_id'
    ];

    public function designation() {
        return $this->belongsTo(Designation::class);
    }
}

class Designation extends Model
{
    protected $table = 'designations';

    public $fillable = [
        'name'
    ];

    public function employee_details() {
        return $this->hasMany(EmployeeDetail::class);
    }
}

Controller - DesignationController

public function index()
{
    return Designation::select('name')->withCount(['employee_details'])->get();
}

// return [ {"name": "Test', "employee_details_count": 2} , ...]

Please or to participate in this conversation.