mehrdad70's avatar

display image in laravel

Hi, I uploaded some photos , but there is a problem displaying it

    public function store(Request $request)
    {
        if ($request->hasFile('images')) {
            foreach ($request->images as $image) {
                $fileName = time().'.'.$image->extension();
                $image->move(public_path().'/images/',$fileName);
                $data[] = $fileName;
            }
        }

       File::create([
            'images' => json_encode($data)
        ]);
        session()->flash('success' , 'file upload');
        return back();
    }
 @foreach ($files as $file)
                @foreach (json_decode($file->images , true) as $image)
                <img src="{{'/public/' . $image->images}}" alt="" srcset="">
                @endforeach
            @endforeach
        Schema::create('files', function (Blueprint $table) {
            $table->id();
            $table->string('images');
            $table->timestamps();
        });
#attributes: array:4 [▼
    "id" => 5
    "images" => "["1621240307.png","1621240307.png","1621240307.png","1621240307.png"]"
    "created_at" => "2021-05-17 08:31:47"
    "updated_at" => "2021-05-17 08:31:47"
  ]
Trying to get property 'images' of non-object (View: C:\Users\Mehrdad\Desktop\Education\resources\views\file.blade.php)

0 likes
7 replies
MichalOravec's avatar

This will work

@foreach ($files as $file)
    @foreach (json_decode($file->images, true) as $image)
        <img src="{{ asset($image) }}" alt="Image">
    @endforeach
@endforeach

But it's totally wrong... all what you are doing...

2 Lessons completed, start watching videos on Laracasts finally.

mehrdad70's avatar

Excuse a question There is also a problem with the controller code related to uploading photos I upload 4 different photos but this code only uploads one photo 4 times repeatedly

mehrdad70's avatar

What is your suggested way to upload multiple photos?

automica's avatar

you'll need to do something better with how you name the files then.

 $fileName = time().'.'.$image->extension();

your time is the same for each image.

I suggest:

   foreach ($request->images as $index => $image) {
                $fileName = time() . '-' . $index . '.' . $image->extension();
                $image->move(public_path().'/images/',$fileName);
                $data[] = $fileName;
            }
mehrdad70's avatar

Thank you, this solution is correct. I have a question ? Is this method suitable for uploading multiple photos?

automica's avatar

@mehrdad70 it suitable for saving multiple images. The method you've currently got seems to be working enough to get the images to the server, so try above and see how you get on.

Please or to participate in this conversation.