【问题标题】:Laravel 5 intervention image upload multiple resize and save path to databaseLaravel 5 干预图片上传多次调整大小并保存路径到数据库
【发布时间】:2016-01-24 01:11:06
【问题描述】:

我已经能够关注这个answer 并且我实际上可以创建多个图像大小。

我的问题是,如何将每个路径保存到数据库。

public function store(Request $request)
{
    $input= $request->all();

    $file = $input['image'];

    $destinationPath='images/products';
    $destinationPathlarge='images/products/large';

    $extension = $file->getClientOriginalExtension();

    $fileName = rand(111,999).'.'.$extension;
    $image = $destinationPath . '/' .$fileName;

   $upload_success=  $file-> move($destinationPath,$fileName);
    $doc = new Products();
    $doc->name = $input['name'];
    $doc->price = $input['price'];
    $doc->description = $input['description'];
    $doc->s_description = $input['s_description'];
    $doc->brands_id = $input['brands_id'];
    $doc->categories_id = $input['categories_id'];
   $upload = Image::make($image)->resize(190,185)->save($destinationPath. '/' .$fileName)
        ->resize(100,100)->save($destinationPathlarge. '/'.$fileName);
    $doc->save();

【问题讨论】:

    标签: php laravel-5 intervention


    【解决方案1】:

    你应该创建一个合适的 Eloquent 模型。

    首先,在项目文件夹中运行 artisan 命令。

    php artisan make:model MyImage
    

    这将创建“MyImage”Eloquent 模型及其数据库迁移。

    通过向 up() 函数添加新的路径字段来编辑新创建的迁移文件,如下所示:

    Schema::create('my_images', function(Blueprint $table)
    {
        $table->increments('id');
    
        $table->string('path_190');
        $table->string('path_100');
    
        $table->timestamps();
    });
    

    运行新的迁移以对您的数据库进行更改。

    然后,在 App\MyImage 模型类中,添加 fillable 属性以启用路径字段的填充:

    class Image extends Model {
    
    protected $fillable = [
        'path_100',
        'path_190',
    ];
    

    }

    现在添加到控制器的存储操作中:

    App\MyImage::create([
        'path_100' => asset($destinationPathlarge. '/'.$fileName100),
        'path_190' => asset($destinationPathlarge. '/'.$fileName190),
    ])->save();
    

    希望对你有帮助:)

    【讨论】:

    • 我不认为为不同大小的图像创建表格是一个好方法。适当的命名约定要好得多。
    • 你错了。我只创建了一个包含两个路径字段的表“my_images”。
    • 不,我明白了。我只是选择了坏话。为这个特定的事情使用数据库是不必要的 IMO。我会在几分钟后发布答案。
    • 问题是:如何将每个路径保存到数据库确实存储上传和调整大小的图像的路径以便按需检索它们是有意义的。 每次想要显示时都裁剪图像。
    • 哦,你是对的,我没有注意到他明确想要数据库。我为此道歉。顺便说一句,我的答案中的代码不会在每个请求中裁剪。它比使用数据库相当有效,但唯一的问题是缺乏灵活性。无论如何,由于这不是 OP 要求的,我将删除我的答案并投票给你。
    猜你喜欢
    • 2017-08-20
    • 1970-01-01
    • 2015-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-01
    • 2023-04-09
    • 2015-06-01
    相关资源
    最近更新 更多