简体   繁体   中英

How to get images of a record from database with laravel?

I have two tables one store stuff information and one store stuff images

-table stuffs

stuff_id |  name  | detail

-table images

id  | stuff_id  | images

-my model relationship

-Stuffs

namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class Stuffs extends Model
{
// A Stuff has many images
 public function image(){
return $this->hasMany('App\Model\image', 'stuff_id');
}
}


-Image

namespace App\Model;
use Illuminate\Database\Eloquent\Model;
{
// images belongs to only one Stuff
public function stuff(){
return $this->belongsTo('App\Model\Stuffs');
{
{

Now I get some stuff info and look like this:

ID  | Name
1   |[July][1]
2   |[Bona][1]

I need that if I click on that stuff's name it will go to detail page with all the images of the stuff has.

My Detail Page

@foreach($getDetails as $getDetail)
<a rel="lightbox" data-lightbox = "gallery" href="{{URL::asset($getDetail->images)}}">
 <img class="img-responsive" width="150" src="{{URL::asset($getDetail->images)}}">
 </a>
 @endforeach

My Controller

public function Detail($id){
$getDetails = Image::join('Stuffs', 'stuffs.stuff_id' , '=', 'image.stuff_id')
 ->find($id);
 return view('crud.more_detail', compact('getDetails'));
}
}

It is not work and get this error

ErrorException in b5e95ef79c2c035f3a379c139e5e7ac6 line 11:
Trying to get property of non-object (View: 
C:\wamp\www\crud\resources\views\crud\more_detail.blade.php)

Please help me thanks;

One of the main points of using relationships is that you don't have to manually join tables together.

To get an image with it's stuff you would just need to do:

$getDetails = Image::with('stuff')->find($id); 
//'stuff' is the name of the method you're using in your model

Also, using find() will only return the row where the id of that row is equal to $id so looping through $getDetails won't work. This is most likely the reason you're getting an error.

If you want to get all images and their stuff you could do:

$getDetails = Image::with('stuff')->get();

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM