Hi, as per subject how to retrieve data form field that has relation.
My Relation
class iklan extends Model
{
public function foto()
{
return $this->hasOne('App\foto');
}
}
table "foto" fields :
$table->increments('id');
$table->integer('iklan_id')->unsigned();
$table->foreign('iklan_id')->references('id')
->on('iklan')
->onUpdate('cascade')
->onDelete('cascade');
$table->string('foto_1')->default('/images/foto/nofoto.png');
$table->string('foto_2')->nullable();
$table->string('foto_3')->nullable();
$table->string('foto_4')->nullable();
$table->string('foto_5')->nullable();
$table->string('foto_6')->nullable();
$table->string('foto_7')->nullable();
$table->string('foto_8')->nullable();
in Controller :
public function listings()
{
$iklans = iklan::latest()->where('active',1)
->with('kategori','subkategori','provinsi','kota','foto')
->paginate(5);
return view('iklan.listings',compact('iklans'));
}
in View :
@foreach($iklans as $iklan)
<div class="row listing-row">
<div class="col-sm-2">
<a href="{{ route('iklan_link' , [$iklan->id, $iklan->slug])}}" class="thumbnail ">**This <img alt="176 * 120" src="{{ $iklan->foto->foto_1 }}"> as bold**</a>
</div>
<div class="col-sm-10">
<h3><a class="" href="{{ route('iklan_link' , [$iklan->id, $iklan->slug])}}">{{$iklan->judul}} - <strong>{{$iklan->harga}}</strong></a></h3>
<p class="muted">Kategori <strong>{{ $iklan->kategori->nama }}</strong></p>
<p class="muted">Posted {{ $iklan->created_at->diffForHumans() }} to <a href="listings.html#" class="underline">{{$iklan->subkategori->nama}}</a></p>
</div>
</div>
dd($iklan)
iklan {#219 ▼
#table: "iklan"
#fillable: array:21 [▶]
#connection: null
#primaryKey: "id"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:24 [▶]
#original: array:24 [▶]
#relations: array:5 [▼
"kategori" => kategori {#229 ▶}
"subkategori" => subkategori {#233 ▶}
"provinsi" => provinsi {#225 ▶}
"kota" => kota {#224 ▶}
"foto" => foto {#238 ▶}
dd($iklan->foto->foto_1)
"/images/foto/nofoto.png"
but when retrieve data and use "$iklan->foto->foto_1" i got an error : Trying to get property of non-object
my img :
<img alt="176 * 120" src="{{ $iklan->foto->foto_1 }}">
any idea ???
thank you.
Can you try:
return view('iklan.listings',['iklans'=>$iklans]);
instead of
return view('iklan.listings',compact('iklans'));
and tell me the results?
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community