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

Romentigo's avatar

Select all records with at least 1 related record

Hello! I've got a question, it can be simple though. I have 2 models: Speciality and Group. Their defenitions are below:

Speciality

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Speciality extends Model
{
    protected $fillable = ['name', 'institute_id'];

    public function institute()
    {
        return $this->belongsTo('App\Models\Institute');
    }

    public function groups()
    {
        return $this->hasMany('App\Models\Group');
    }
}

Group

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Group extends Model
{
    protected $fillable = [
        'speciality_id', 'course_num', 'group_num'
    ];

    public function speciality()
    {
        return $this->belongsTo('App\Models\Speciality');
    }

    public function students()
    {
        return $this->hasMany('App\Models\Student');
    }
}

I need to get all specialities that have at least one group. That's the part of my controller that returns all specialities by institute id, but it doesn't matter now, it works fine.

Controller

public function filterByInstitute($id)
   {
       $specialities = Speciality::with('institute', 'groups')->where('institute_id', '=', $id)
           ->orderBy('name', 'ASC')->get();

       if ($specialities->isEmpty())
       {
           return response()->json(['message' => 'У системі немає жодної спеціальності.'])->setStatusCode(500);
       }
       else
       {
           return response()->json($specialities)->setStatusCode(200);
       }
   }
0 likes
2 replies
mkshingrakhiya's avatar
Level 3

You can use has() to get records with at least one defined relationship record.

$specialities = Speciality::has('groups')
    ->with('institute', 'groups')
    ->where('institute_id', '=', $id)
    ->orderBy('name', 'ASC')
    ->get();
Romentigo's avatar

Thanks! Seems like I missed it in documentation somehow.

Please or to participate in this conversation.