Search code examples
phphtmllaraveluploaddata-retrieval

Laravel - Retrieve only images that belong to the id


Retrieving all the images from mysql instead it suppose to retrieve only the images that belongs to the form id. Any suggestions?

Cars Model

class Cars extends Model
{
    public $table = 'cars';

    protected $primaryKey = 'id';

    public function carevidence()
    {
        return $this->hasMany('App\CarEvidence', 'cars_id', 'id');
    }

}

CarEvidence Model

class CarEvidence extends Model
{
    protected $table = 'carevidence';

    protected $fillable = [
        'cars_id',
        'car_images',
    ];

    public function car()
    {
        return $this->belongsTo('App\Cars', 'cars_id', 'id');
    }
}

Store Controller

if ($post->save()) {
    if ($request->hasFile('carEvidence')) {
        $files = $request->file('carEvidence');

        foreach ($files as $file) {
            $extension = $file->getClientOriginalExtension();
            $filename = time() . '.' . $extension;
            $file->move(public_path('/image'), $filename);

            CarEvidence::create([
                'cars_id' => $post->id,
                'car_images' => $filename
            ]);
        }
    }
}

Retrieve Controller

public function edit($id)
{
    $cars = Cars::with('carevidence')->get();

    return view(
        'Validation.validation',
        compact('validations', 'validators', 'departments', 'defects', 'cars')
    );
}

Views for retrieve

@foreach($cars as $car)
    @foreach($car->carevidence as $evidence)
        <img src="{{ asset('image/'.$evidence->car_images) }}" target="_blank" height="60px" width="60px" />
    @endforeach
@endforeach

Images when retrieve

enter image description here


Solution

  • Removing the first foreach has solved the issue!

    @foreach($car->carevidence as $evidence)
        <img src="{{ asset('image/'.$evidence->car_images) }}" target="_blank" height="60px" width="60px" />
    @endforeach