Laravel eloquent hasmany relationship is returned when one row is required

there are many questions in this area, but I cannot find one that fits. I think this is a very basic understanding of Laravel.

I have a simple relationship between "properties" and "images". For a certain kind of display, I need to get the property data along with the filename of the "host" image. This way I only need one image result, depending on whether the image is marked "1" as the leading image in the DB.

The controller code looks like this:

if(Input::get('m') == 'true'){
            //$map_data = Property::all();

            $map_data = Property::with(array('images' => function($query)
            {
                //just grab the lead image to put in the marker popups.
                $query->where('is_lead', 1)->first();

            }))->get();


            return View::make('property_map')->with('data', $map_data);
        }

      

But in view, the only way to get this to work is with a foreach loop, although I only need one result:

@foreach($property->images as $image)
  {{$image->filename}}
@endforeach

      

This is obviously stupid. I think I was just missing something simple with this loop in the view, but I may have misunderstood how to handle this in the controller too. I think I have read the laravel docs about 20 times, just cant get this little detail. Thank.

UPDATE - I just tried this and I managed to get rid of the pointless foreach by doing this in the view:

$property->images->first()["filename"]

      

.. but this is still not very "laravelle" .. still appreciates any thoughts on the best way to do this.

+3


source to share


1 answer


Try changing ->get()

to ->first()

.



if(Input::get('m') == 'true'){
            //$map_data = Property::all();

            $map_data = Property::with(array('images' => function($query)
            {
                //just grab the lead image to put in the marker popups.
                $query->where('is_lead', 1)->first();

            }))->first();


            return View::make('property_map')->with('data', $map_data);
        }

      

0


source







All Articles