Search code examples
phplaravel-5intervention

Laravel 5 intervention image upload multiple resize and save path to database


i have been able to follow this answer and i can actually create multiple image size.

My question is, how can i save each path to a database.

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();

Solution

  • You should create an appropriate Eloquent model.

    First, run an artisan command in your project's folder.

    php artisan make:model MyImage
    

    This will create the 'MyImage' Eloquent Model and it's database migration.

    Edit the newly created migration file by adding new path fields to the up() function like this:

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

    Run the new migration to make the changes to your database.

    Then, in the App\MyImage model class, add the fillable property to enable filling of the path fields:

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

    }

    Now add to your Controller's store action:

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

    I hope it helps :)