Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

293
Views
How to check hasMany relation record is empty in eloquent laravel

I need to get those record who has not join with has many table my query like this

$result = Recipes::select('id')->where("name", 'like', '%' . $item . '%')
                    ->with(['categoryItem'])
                    ->get();

And my output is

Array
(
    [0] => Array
        (
            [id] => 1
            [category_item] => Array
                (
                    [0] => Array
                        (
                            [id] => 2
                            [foodable_id] => 1
                            [foodable_type] => Recipes
                            [created_at] => 2017-04-14 16:18:22   
                        )

                )

        )

    [1] => Array
        (
            [id] => 4
            [category_item] => Array
                (
                )

        )

)

I want to get just those record who has empty category_item detail. in bellow example i want to get index 1 record so how can i give condition with query

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

If I understood you correctly and you want to get recipies which don't have categoryItem, you want to use doesntHave() method:

Recipes::where('name', 'like', '%'.$item.'%')
       ->doesntHave('categoryItem')
       ->get();

I assume that categoryItem is defined relation since you're trying to use it in with() method.

about 4 years ago · Santiago Trujillo Report

0

Hello Maybe this can help . Dont forget to add on top of your file :

use DB;

And your result will be something like this

$result = Recipes::select('id')->where("name", 'like', '%' . $item . '%') ->whereHas('categoryItem', function($q) { $q->where(DB::raw('count(*)),'>', 0); })->get();

I did't tested the count function hope this works, Good luck with it

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!