In many projects, we have to save images in the database. In this post your will learn how to save multiple images include watermark and save in the database. PHP framework has many library to upload, resize, edit, optimize pictures. Here I will show with PHP Laravel Framework.
PHP is the easy and secure way to save image data in the database.
In view page:
<form class="form-horizontal" method="POST" action="{{ url('save_image_in_database') }}" enctype="multipart/form-data">
{!! csrf_field() !!}
<div id="form-container">
<fieldset>
<div class="form-group">
<label class="col-md-3 control-label" for="image"> {{ t('Pictures') }} </label>
<div class="col-md-8">
<input id="image" name="images[]" type="file" class="file" multiple="multiple">
<div class="">
<p class="help-block">
{{ t('Use a real image of your product'}}
</p>
</div>
</div>
</div>
<fieldset>
</div>
</form>
Set route for image save:
Route::post('save_image_in_database', 'PostController@save_images');
Create a model to save data in the database table:
We create a Picture model.
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Schema;
class Picture extends Model
{
protected $table = 'pictures';
public $timestamps = true;
protected $fillable = [
'pictures',
];
}
Create a Controller(Here is PostController)
use Picture model in this controller.
use App\Models\Picture.
public function save_image(request $request){
if ($request->file('images')) {
$destination_path ='uploads/images/';
$full_destination_path = public_path() . '/' . $destination_path;
$images = $request->file('images');
$count_images = count($images);
if ($count_images > 0) {
foreach ($images as $key => $image) {
try {
// Create destination path if not exists
if (!File::exists($full_destination_path)) {
File::makeDirectory($full_destination_path, 0755, true);
}
// Get file info
$new_filename = slugify(strtolower($image->getClientOriginalName()));
$img = Image::make($image);
$width = $img->width();
$height = $img->height();
$watermarkSize = $width / 2.2;
$watermark = Image::make(public_path('/assets/img/watermark.png'));
$watermark->resize($watermarkSize, null, function ($constraint) {
$constraint->aspectRatio();
});
$img->insert($watermark, 'center');
$img->save($full_destination_path . $new_filename);
// Save Picture in database
$picture = new Picture(array(
'filename' => $new_filename,
));
$picture->save();
} catch (\Exception $e) {
flash()->error($e->getMessage());
}
}
flash()->success('Images save in the database successfully!');
return redirect()->back();
}
}
}
If you have any query commet below.