Show image file by id in Laravel 5.2

懵懂的女人 提交于 2019-12-13 14:49:17

问题


I have a table named files, this saves the name of the images related to the properties table.

I am trying to make these images appear as in the following relation.

This is part of the properties table.

This is the table files and their relationship to the properties table.

What parameter can I pass in the show method of my controller (PropertyController)?

Currently I have the following:

public function show($id)
{
 $properties = Property::find($id);

 $files = File::all();

 return View::make('properties.show', ['properties' => $properties, 'files' => $files]);
}

But it returns to the view all the images stored in the files table.

@foreach($files as $file) 

    <div class="col-md-6 thumb">
        <a class="thumbnail">
            <img id="myImg" src="{{ URL::asset('uploads/products/' . $file->name) }}" alt="{{ $file->name }}" width="300" height="200">
        </a>
    </div>

@endforeach

Which method would be correct so that the images related to the records can be displayed by id in the properties table?


回答1:


I'm assuming you're using hasMany() relationship between Property and File models. If not, create the relation in the Property model:

public function files()
{
    return $this->hasMany('App\File');
}

To load the property with all it's images use eager loading:

public function show($id)
{
    $property = Property::with('files')->find($id);
    return view('properties.show', compact('property'));
}

To display images:

@foreach($property->files as $file) 
    // Here use the same code you used before.
@endforeach

Alternatively, you can load data separately:

public function show($id)
{
    $property = Property::find($id);
    $files = File::where('property_id', $property->id)->get();
    return view('properties.show', compact('property', 'files'));
}



回答2:


In your Property model, define your hasMany method like this:

public function files()
{
    return $this->hasMany('App\File');
}

Your show method in your controller will be like this:

public function show($id)
{
 $property = Property::find($id);

 $files = $property->files;

 return View::make('properties.show', ['property' => $property, 'files' => $files]);
}


来源:https://stackoverflow.com/questions/41625187/show-image-file-by-id-in-laravel-5-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!