2017-01-12 8 views
3

私はファイルという名前のテーブルを持っています。これはプロパティテーブルに関連する画像の名前を保存します。Laravelの画像ファイルをIDで表示5.2

私はこれらの画像を次のように表示しようとしています。

これはプロパティテーブルの一部です。

enter image description here

これは、テーブルファイルとプロパティテーブルとの関係です。

enter image description here

どのパラメータ私は私のコントローラ(PropertyController)のショー方法で渡すことができますか?

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

$files = File::all(); 

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

しかし、それは、ビューへのファイルのテーブルに保存されているすべての画像を返します。

現在、私は次のことを持っています。

@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 

レコードに関連する画像をプロパティテーブルのidで表示できるようにするには、正しい方法はありますか?

+1

以下:) – aceraven777

答えて

2

私はあなたがPropertyFileモデルの間にhasMany()の関係を使用していると仮定しています。

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

画像を表示するには:、またはあなたを

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

を、画像がeager loadingを使用していますすべてでプロパティをロードするには

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

:いない場合は、Propertyモデルにリレーションを作成します別々にデータを読み込むことができます:

public function show($id) 
{ 
    $property = Property::find($id); 
    $files = File::where('property_id', $property->id)->get(); 
    return view('properties.show', compact('property', 'files')); 
} 
あなたの財産モデルでは
+0

私の答えを確認してください、私は適用foreach()(ビュー:C:\ xampp \ htdocs \ crminmobiliario \ resources \ views \ layouts \ gallery.blade.php)に無効な引数が指定されています –

+0

@EdwardPalenはあなたですか最初の方法か2番目の方法について話していますか?正しい変数名を使用しているかどうか確認してください。すべてがうまくいっていて、あなたが熱心な読み込み方法について話しているなら、 '{{dd($ property)}} 'の結果を投稿してください。 –

+0

これで変数は修正されましたが、 Database \ Query \ Builder :: files() –

0

、このようなあなたのhasManyの方法定義:

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

をお使いのコントローラであなたのshowメソッドは次のようになります。

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

$files = $property->files; 

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

はい、方法を確認してエラーを修正しました。ありがとうございます。正常に動作しています。 –

+0

私の答えが役に立つなら、私の答えをupvoteしてください。 :) – aceraven777

関連する問題