duanmengmiezen8855 2019-06-11 20:48
浏览 102

Laravel - 检查集合是否有关系

I have a form with some checkboxes and when certain checkboxes are checked, I conditionally create a join to an Eloquent model

$collection = Model::with('some_relation')
     ->when(!is_null($request->input('make')), function($query) {
         $query->with('make');
      })
      ->get();

This all works as expected.

What I need to be able to do is check for the existence of that relation in a view. In my view I have a table and need to know if the relation exists and if it does I create a table header for that relation.

I have tried everything I can find and nothing works. I've even tried the following but it returns true even if the relation doesn't exist

$test = $collection->contains(function ($value, $key) {
    return $value['make'];
});

I've also tried count($collection->make); but it says

Property [make] does not exist on this collection instance

All I want it to see if the relationship exists

  • 写回答

1条回答 默认 最新

  • doucan1996 2019-06-12 08:11
    关注

    Found the answer

    $test = $collection->filter->relationLoaded('make')->isEmpty();
    

    Will return true if the relation doesn't exist

    评论

报告相同问题?