How to image upload into databae using laravel? - laravel

I am trying to upload an image into the database but unfortunately not inserting an image into the database how to fix it, please help me thanks.
database table
https://ibb.co/3sT7C2N
controller
public function Add_slider(Request $request)
{
$this->validate($request, [
'select_image' => 'required'
]);
$content = new Sliders;
if($request->file('select_image')) {
$content->slider_image = Storage::disk('')->putFile('slider', $request->select_image);
}
$check = Sliders::create(
$request->only(['slider_image' => $content])
);
return back()
->with('success', 'Image Uploaded Successfully')
->with('path', $check);
}

You should do with the following way:
public function Add_slider(Request $request)
{
$this->validate($request, [
'select_image' => 'required'
]);
$image = $request->file('select_image');
$extension = $image->getClientOriginalExtension();
Storage::disk('public')->put($image->getFilename().'.'.$extension, File::get($image));
$content = new Sliders;
if($request->file('select_image'))
{
$content->slider_image = $image->getFilename().'.'.$extension;;
$content->save();
$check = Sliders::where('id', $content->id)->select('slider_image')->get();
return back()->with('success', 'Image Uploaded Successfully')->with('path',$check);
}
}
And in view blade file:
<img src="{{url($path[0]->slider_image)}}" alt="{{$path[0]->slider_image}}">

This returns only the filename:
Storage::disk('')->putFile('slider', $request->select_image);
Use this instead:
Sliders::create([
'slider_image' => $request->file('select_image')->get(),
]);
Make sure the column type from database is binary/blob.

Related

image not store in database laravel

I want to Create app in laravel that manage my events
i use this code for EventController
public function store(Request $request)
{
$request->validate([
'inviter'=>'max:255',
'date'=>'max:255',
'phone'=>'max:255',
'whatsapp'=>'max:255',
'location'=>'max:255',
'approval'=>'max:255',
'number'=>'max:255',
'description'=>'max:255',
'track'=>'max:255',
]);
$eve = new Event([
'inviter'=> $request->get('inviter'),
'date'=> $request->get('date'),
'phone'=> $request->get('phone'),
'whatsapp'=> $request->get('whatsapp'),
'location'=> $request->get('location'),
'number'=> $request->get('number'),
'approval'=> $request->get('approval'),
'description'=> $request->get('description'),
'track'=> $request->get('track'),
]);
if ($request->hasFile('file')) {
$file = $request->file('file');
$fileName = $file->getClientOriginalName();
$filePath = time() . '.' . $file->getClientOriginalName();
$request->file->move(public_path('uploads/events'), $filePath);
$eventImage = Image::createNew();
$eventImage->filename_path = $filePath;
$eventImage->original_filename = $fileName;
$eventImage->event_id = $eve->id;
$eventImage->save();
}
return redirect(route('event.index'))->with('success','Event Created');
}
but image dont create I think related to event_id when I was testing the code correctly and incorrectly
Try this
$eve = Event::create([
'inviter'=> $request->get('inviter'),
'date'=> $request->get('date'),
'phone'=> $request->get('phone'),
'whatsapp'=> $request->get('whatsapp'),
'location'=> $request->get('location'),
'number'=> $request->get('number'),
'approval'=> $request->get('approval'),
'description'=> $request->get('description'),
'track'=> $request->get('track'),
]);

Laravel deleting old image after updating

I want my user's old image to be deleted when they update it. This current function does not work how I want it. How would I change it so it works?
public function update($id)
{
$profile = Profile::findOrFail($id);
$data = request()->validate([
'title' => 'required|max:255',
'image' => ''
]);
if ($profile->image) {
if (Storage::exists("storage/{$profile->image}")) {
Storage::delete("storage/{$profile->image}");
}
}
if (request('image')) {
$imagePath = request('image')->store('profile', 'public');
$image = Image::make(public_path("storage/{$imagePath}"))->orientate()->fit(1000, 1000); //Intervention Image Package
$imageArray = ['image' => $imagePath];
$image->save();
}
// $profile->image = $request->image; //Lägg till senare
$profile->update(array_merge(
$data,
$imageArray ?? [],
));
return redirect("/profile/{$profile->user_id}");
}
}
First you have to take the old image and delete it from the server
if (file_exists(('./images/partners/' . $partner->image_path))) {
unlink(('./images/partners/' . $partner->image_path));
}
after that you can upload your new image and update the record in the database

Can Anyone Check This Image Upload Code In Laravel?

I wrote this Code For Image Upload but I do not know if it is secure, or not. Is There any issue or vulnerability in this code??
if($request->hasFile('image')){
$AllowedImages = ['jpeg', 'jpg', 'png'];
$AllowedImageTypes = ['image/jpeg', 'image/png'];
$image = $request->image;
$ImageNameWithExtension = $image->getClientOriginalName();
$ImageName = pathinfo($ImageNameWithExtension, PATHINFO_FILENAME);
$ImageExtension = $image->getClientOriginalExtension();
$ImageType = $image->getMimeType();
$ImageLocalPath = $image->getPathName();
$ImageSize = $image->getSize();
$ImageError = $image->getError();
$ImageNewName = sha1(md5($ImageName)).''.sha1(time()).'.'.$ImageExtension;
if(in_array($ImageType, $AllowedImageTypes) && in_array($ImageExtension, $AllowedImages) && getimagesize($ImageLocalPath) && ($ImageError === 0) && ($ImageSize <= 2000000)){
if($ImageType == 'image/jpeg' && ( $ImageExtension == 'jpeg' || $ImageExtension == 'jpg')){
$img = imagecreatefromjpeg($ImageLocalPath);
imagejpeg( $img, $ImageNewName, 100);
}
elseif($ImageType == 'image/png' && $ImageExtension == 'png'){
$img = imagecreatefrompng($ImageLocalPath);
imagepng( $img, $ImageNewName, 9);
}
imagedestroy($img);
try
{
$StoreImage = $image->storeAs('public/Upload/', $ImageNewName);
if(!$StoreImage){
throw new customException('File Upload Failed');
}
}
catch(customException $e){
session()->flash('File_Error', $e->errorMessage());
return back();
}
}
else{
session()->flash('File_Error', 'Image Validation Error Found');
return back();
}
}
else{
return back();
}
Consider this refactor for your code, it will help make your code cleaner.
public function store(Request $request)
{
$record = Model::create( $this->validateRequest() ); // this can insert other data into your database. In the db table, initially set the image related fields to nullable
$this->storeFile($record); // this will check if the request has a file and update the image related fields accordingly, else it will remain blank as it is nullable by default
return 'all data is saved';
}
private function validateRequest(){
return request()->validate([
'type' => 'nullable',
'image'=> request()->hasFile('image') ? 'mimes:jpeg,jpg,png|max:2000' : 'nullable', // 2000 means a maximum of 2MB
'other_field_1' => 'required',
'other_field_2' => 'required',
'other_field_3' => 'required'
]);
}
private function storeFile($record){
if( request()->hasFile('image') ){
$record->update([
'type' => request()->file->extension(),
'image' => request()->file->store('uploads/files', 'public') // The file will be hashed by default. public is used as second argument so you can access the uploaded file via your public folder
]);
}
}
This is check for file in the request, validate the file and other data, upload the file into storage folder.
You can use this code, for upload image :
In Request file :
public function rules()
{
return [
'image' => 'required|mimes:jpeg,jpg,png|max:50000'
],
}
And in your controller :
public function uploadImage(YourRequestClass $request){
$image = $request->file('image');
try{
$order=new Order();
if (!file_exists('upload/' . $image)) {
$currentDate = Carbon::now()->toDateString();
$imageName = $currentDate . '-' . uniqid() . '.' . $image->getClientOriginalExtension();
if (!file_exists('upload/')) {
mkdir('upload/', 0777, true);
}
$image->move('upload/', $imageName);
$order->image = $imageName;
}
$order->save();
return back();
} catche(\Exception $e){
Log::error($e);
return back();
}
}

Image is not saved/updated into database using Laravel

I am trying to save my image into database while creating my user and i am using postman for this
My Code:
public function register(Request $request) {
$body = $request->all();
$userProfile = $body['user_profile'];
$userPrev = $body['privileges'];
$userProfile['is_super_admin'] = $userPrev['is_super_admin'];
$facilities = $userPrev['facilities'];
$bodyObj = array_merge($userProfile, $userPrev);
$validator = UserValidations::validateUser($bodyObj);
if ($validator->fails()) {
return response([
'status' => false,
'message' => __('messages.validation_errors'),
'errors' => $validator->errors()->all()
], 200);
}
DB::beginTransaction();
try {
If (Input::hasFile('image')) {
$file = Input::file('image');
$destinationPath = public_path() . '/profile_images/';
$filename = $file->getClientOriginalName();
$file->move($destinationPath, $filename);
$this->user->where('id', Auth::user()->id)->update(['profile_pic' => $filename]);
}
My user is created and saved into database, but the image is not.
Your help will be highly appreciated!
I am really confused. You want to store image in database (bad Idea). Secondly, You want to store image in database but you are storing the file name only.
Suggetion : If you would like to store images in database you have an option to convert it into base64 and store the string. While retrieving you could decode base64. For example:
$file = Input::file('image');
$img_data = file_get_contents($file);
$base64 = $base64_encode($img_data);
$this->user->where('id', Auth::user()->id)->update(['profile_pic' => $base64 ]);
Another suggetion [Best way] : store path in the database and store the file in the storage or public and use the url to access the image
However if you still want to save it on database
$image = addslashes(file_get_contents(Input::file('image')));
$this->user->where('id', Auth::user()->id)->update(['profile_pic' => $image ]);

how to change laravel directory from storage/app/public to public/media

Please i want to change the default laravel configuration from storage/app/public to public/media on the server. In localhost it worked with storage:link but on the server it isn't working even after adding a symlink. Below is my symlink code.
<?php symlink('/home/cemo/cem/storage/app/public','/home/cemo/public_html');
Also if i return the public_path() from the store function i get /home/cemo/cem/public
this is the structure of my cpanel
below is my store function using image intervention
public function store(Request $request)
{
return public_path();
$this->validate($request,[
'title'=>'required|min:6',
'body'=>'required'
]);
if($request->hasFile('image')){
$img = $request->file('image');
$imgName = time().'-'.uniqid() . '.' . $img->getClientOriginalExtension();
}
else{
$imgName = 'default.jpg';
}
$posts = new post;
$posts->title = $request->title;
$posts->body = $request->body;
$posts->posted_by = $request->posted_by;
$posts->status = $request->status;
$posts->position = $request->position;
$posts->image = $imgName;
$posts->source = $request->source;
$posts->save();
$posts->tags()->sync($request->tags);
if(!empty($img)){
Image::make($img)->resize(1500,550)->save(public_path('/media/images/blog/'. $imgName));
}
$notification = array(
'message' => 'Successfully created',
'alert-type' => 'success'
);
return redirect(route('post.index'))->with($notification);
}
In config/filesystems.php
Change the array to:
'root' => 'public/media',

Resources