Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Sharim's avatar

Store array path of multiple images in Laravel

I want to store path in array from multiple images in form. The files are successfully store in storage folder but the path of that file is not in array form. When I try to save it as an array, it gives me following error:

Array to string conversion

My controller:

$images = array();
$date = now()->format('F').now()->format('Y');

if ($files = $request->file('images')) {
    foreach($files as $file) {
        $name = rand() . '.' . $file->getClientOriginalExtension();
        $file->move('storage/refund/'.$date.'/', $name);
        $images[] = 'refund/'.$date.'/'.$name;
    }
    
}

$refund = Refund::create([
    'images' => $images,
]);
return $refund;

If I do like this:

$refund = Refund::create([
    'images' => implode("|", $images),
]);

The store path is

refund/February2022/1983408013.jpeg|refund/February2022/1692991204.jpg|refund/February2022/2032740006.jpg

I want the path like this

["products\/March2021\/EC8Vuu5VaOaChiVkZ0jh.jpg","products\/March2021\/CVEp4GZvW7jZOL8e2aG4.jpg","products\/March2021\/fClrEBCmTSruUOZBrkxn.jpg","products\/March2021\/gYyuP04Wo5jd2Jbaqx01.jpg"]

So I can call the multiple images using foreach

0 likes
6 replies
samehdev's avatar
samehdev
Best Answer
Level 2

migrate file :

       $table->json('images');

Refund Model

  protected $casts = [
        'images' => 'array',
    ];

then :

$refund = Refund::create([
    'images' => $images,
]);
1 like
Sharim's avatar

@samehdev Its working but when I open in Voyager Admin Panel, its showing like this

json_decode() expects parameter 1 to be string, array given

samehdev's avatar

@Sharim try add to Refund model :


public function getImagesAttribute($value)
{
    return json_decode($value, true);
}
Sharim's avatar

@samehdev still the same issue. From database the image section is like this:

["refunds/February2022/870701281.jpg", "refunds/February2022/2015928484.jpg"]

That is showing me error. But the voyager's default method of storing path is like this:

"[\"refunds\\February2022\\u1O3nY9t7WpfeLap937b.jpeg\",\"refunds\\February2022\\cR0wkg1vSPVzWPQ3xkrG.jpg\",\"refunds\\February2022\\txNB3uMT6ZAWeeSKU3AW.jpg\"]"

If I replace this section, than it work. How can I store path like this?

samehdev's avatar

@Sharim try

$refund = Refund::create([
    'images' => json_encode($images),
]);

Please or to participate in this conversation.