laravel 7图像阵列未在刀片页面上显示图像

时间:2020-06-23 18:30:52

标签: php mysql laravel

我刚刚开始学习laravel。对于我的实践项目,我试图显示图像阵列中的第一张图像。当只有一幅图像时,它会倾斜,而当有多幅图像时,它不会倾斜。但是,我已经检查了数据库,并且图像存储在该数据库中。我猜问题出在“ img src”部分。我的代码是-

迁移

public function up()
    {
        Schema::create('cars', function (Blueprint $table) {
            $table->id();
            $table->string('carreg');
            $table->string('make');
            $table->string('model');
            $table->string('images');
            $table->timestamps();
        });
    }

模型

class Car extends Model
{
    protected $fillable = [
        'carreg', 'make', 'model', 'images'
    ];
}

控制器

$data = $request->all();
        $images = array();

        if ($files = $request->file('images')) {
            foreach ($files as $file) {
                $image_temp = date('dmy_H_s_i');
                $image_ext = strtolower($file->getClientOriginalExtension());
                $image_name = $image_temp . '.' . $image_ext;
                $upload_dir = 'images/uploaded_cars/';
                $image_url = $upload_dir . $image_name;
                $file->move($upload_dir, $image_name);
                $images[] = $image_url;
            }
        }
        Car::insert([
            'carreg' => $data['carreg'],
            'make' => $data['make'],
            'model' => $data['model'],
            'images' => implode("|", $images)
        ]);

add.blade

<div class="col-md-2">
      <input type="file"  id="images"  name="images[]" multiple >
</div>

index.blade

@foreach ($cars as $car)
         <tr>
             <td><img src="{{ asset($car->images[0]) }}" style ="height:100px; width:150px;"></td>
                        <td>{{ $car->id }}</td>
                        <td>{{ $car->carreg }}</td>
                        <td>{{ $car->make }}</td>
                        <td>{{ $car->model }}</td>
                    </tr>
                @endforeach

1 个答案:

答案 0 :(得分:0)

您需要使用json编码和解码,这是我的解决方法,不会内爆。我希望这会有所帮助

控制器

 $data = $request->all();
            $images = array();
    
            if ($files = $request->file('images')) {
                foreach ($files as $file) {
                   ......
                   .....
                    $images[] = $image_url;
                }
            }
            Car::insert([
                .........
                'images' => json_encode($images)
            ]);

刀片

@foreach ($cars as $car)
         <tr>@php ($images=json_decode($car->images))
             <td><img src="{{ asset(images[0]) }}" style ="height:100px; width:150px;"></td>
                      ..........
                    </tr>
                @endforeach