Romentigo
4 months ago
381
2
Laravel

Select all records with at least 1 related record

Posted 4 months ago by Romentigo

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);
       }
   }

Please sign in or create an account to participate in this conversation.