Laravel save tmp files - laravel

I changed the image upload directory to the public folder, but why is the file uploaded to the database on the tmp path? I want the record name in the database to match the file name. Can anyone help?
Controller (store method)
public function store(Request $request)
{
$validatedData = $request->validate([
'banner_title' => 'required|max:255',
'image' => 'image|file|max:5120',
]);
$imageName = time() . '.' . $request->image->extension();
$request->image->move(public_path('images/banner-image'), $imageName);
Banner::create($validatedData);
return redirect('/dashboard/banner')->with('msg', 'Success!');
}

Here is the solution,
Add below statement before the Banner::create($validatedData);
$validatedData['image'] = $imageName;
In here we can assign validated image to $imageName after that we can save it in database.

Related

How to delete old picture after new one uploaded

I have this in my Controller which handles image upload
public function updateProfileImage(Request $request)
{
$user = auth('api')->user();
$image = $request->input('image'); // image base64 encoded
preg_match("/data:image\/(.*?);/",$image,$image_extension); // extract the image extension
$image = preg_replace('/data:image\/(.*?);base64,/','',$image); // remove the type part
$image = str_replace(' ', '+', $image);
$imageName = 'profile' . time() . '.' . $image_extension[1];
Storage::disk('public')->put($imageName,base64_decode($image));
$user->update($request->except('image') + [
'profilePicture' => $imageName
]);
return [
//'Message' => "Success",
'profilePhoto' => $user['profilePicture']
];
}
How can i delete the old picture from the directory after new one has been uploaded.
You can delete the image with Storage::delete() method (https://laravel.com/docs/7.x/filesystem#deleting-files). So, get the image before you update, then delete when it's ok to do:
$oldImage = $user->profilePicture;
Storage::disk('public')->put($imageName,base64_decode($image));
$user->update($request->except('image') + [
'profilePicture' => $imageName
]);
Storage::disk('public')->delete($oldImage);
return [
//'Message' => "Success",
'profilePhoto' => $user['profilePicture']
];
PS: I'm not sure if the profilePicture attribute is the same of your storage. Anyway, make any adjustment to match if needed.

How to image upload into databae using 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.

update file name of a file and updating data in database at the same time in laravel

I have a working upload file function. here's the code
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'filename' => 'required|mimes:jpeg,png,jpg,gif,svg,doc,docx,xls,xlsx,pdf,txt|max:2048',
]);
$fileName = auth::user()->id.'_'.$name.'.'.request()->filename->getClientOriginalExtension();
request()->filename->storeAs('files', $fileName);
File::create ([
'name' => $name,
'filename' => $fileName,
'user_id' => $request['user_id'],
'extension' => request()->filename->getClientOriginalExtension(),
]);
return redirect('dashboard/files')->with('flash_message', 'File added!');
}
now my problem is how am I going to update the filename of the file once I update the name in the database?
thanks in advance!
Well you may want to look at observers. That would be good practise.. Observers fires when CRUD operations done. So when you change a file name on database, you'll be there through observers.
first create an observer.
php artisan make:observer FileObserver --model=File
then register your observer on AppServiceProvider::boot.
public function boot()
{
File::observe(FileObserver::class);
}
Open your FileObserver and edit "updated" method. Below method will run when a file record updated through File model.
public function updated(File $file)
{
// get old file name
$dirty = $file->getDirty();
$oldFileName = $dirty["filename"] . "." . $file->extension;
// get new file name
$newFileName = $file->filename . "." . $file->extension;
// replace old file name with new
Storage::move('files/' . $oldFileName, 'files/' . $newFileName);
}

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