How store and retrieve image in database use laravel? - laravel

I tried some code to store an image in the database, but it's not working. So i'm enough confused to do that because i am a beginner in laravel.
Anyone can help me to solve my problem?
Here is what i'm currently doing:
// store image
$this->validate($request, [ 'image' => 'image', ]);
if($request->hasFile('image')) {
$image = $request->file('image');
$filename = time() . '.' . $image->getClientOriginalExtension();
Image:make($image)->resize(145, 170)->save(public_path('/images' . $filename));
$image->save();
};

this sample shows how to upload multiple image
// view
<form class="form-horizontal" action="{{ url('/picture-update') }}" method="post" role="form" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="col-sm-4"><label>Profile picture: </label>
<div class="form-group">
<input type="file" name="filename[]" required>
<br>
</div>
<button type="submit" class="btn btn-success btn-xs">Upload</button>
</form>
//controller
public function uploadAttachment(Request $request)
{
$this->validate($request, [
'filename.*' => 'mimes:pdf,doc,docx,jpeg,jpg,gif,png,bmp|max:2048',
//processing insert into attachment table
if($request->hasfile('filename'))
{
foreach($request->file('filename') as $file)
{
$name=$file->getClientOriginalName();
$file->move(public_path().'/../../yourdomain.com/attachments_files', $name);
DB::table('tblstaffAttachment')->insert([
'filepath' => $name,
]);
}
}
return back()->with('message', 'File Uploaded!');
}
//route
Route::post('/picture-update','YourController#uploadAttachment');

the $image is not an instance of your App\Image model but an instance of UploadedFile class
the Image class is a PHP class for images
try it this way if you the attribute you want to store the path to is path
// store image
$this->validate($request, [ 'image' => 'image', ]);
if($request->hasFile('image')) {
$image = $request->file('image');
$filename = time() . '.' . $image->getClientOriginalExtension();
Image::make($image)->resize(145, 170)->save(public_path('/images' . $filename));
$imageInstance = new \App\Image();
$imageInstance->path = '/images' . $filename;
$imageInstance->save();
};

Related

Laravel Livewire Hook not firing for a multiple images

I am trying to upload images when the file field is updated but can't figure out why the UpdatedFoo method isn't fired,
<input type="file" class="custom-file-input" wire:model="photos"
multiple>
<label class="custom-file-label" for="customFile">Choose
image {{ $key + 1 }}</label>
My Livewire component
public $photos = [];
public function UpdatedPhotos($value, $key)
{
$this->validate([
'photos' => 'image|max:1024', // 1MB Max
]);
$storage = new Storage(config('kizusi.client'));
foreach ($this->photos as $photo) {
$result = $storage->createFile('tours', 'unique()', $photo);
print_r($result);
}
}
Alright, I got it,
The validation was preventing my images from being submitted
$this->validate([
'photos' => 'image|max:1024', // 1MB Max
]);

Laravel stored image is tmp not jpg when update data

When I update image the data stored is tmp, not an image file.
Here's my controller:
public function update(Request $request, $id)
{
$change = Post::findorfail($id);
$before = $change->image;
$post = [
'title' => $request['title'],
'tags_id' => $request['tags_id'],
'content' => $request['content'],
'image' => $before,
];
if($request->hasFile('image')){
$request->image->move(public_path().'/image', $before);
}
$change->update($post);
return redirect('post');
}
View:
<div class="form-group row mb-4">
<label class="col-form-label text-md-right col-12 col-md-3 col-lg-3">Featured Image</label>
<div class="col-sm-12 col-md-7">
<input type="file" name="image" class="form-control" value="{{ $data->image }}">
</div>
</div>
Thanks for your help
You must save request image file into system instead of moving old image file.
public function update(Request $request, $id)
{
$change = Post::findorfail($id);
$image = $request->hasFile('image')
? $request->photo->store('image', 'public')
: $change->image;
$post = [
'title' => $request['title'],
'tags_id' => $request['tags_id'],
'content' => $request['content'],
'image' => '/storage/' . $image,
];
$change->update($post);
return redirect('post');
}
This will save new image into /storage/public/image/ path. To make this address accessible through url, you must create a symlink from public path to storage path by running this:
php artisan storage:link
This will create a storage symlink in /public folder which points to /storage/public path. Read the complete documentation about this functionality here: https://laravel.com/docs/8.x/filesystem#the-public-disk

Ajax image upload to database not working

I am trying to upload image to database using Ajax but It store image into public/images directory only,never store image into database,I had grabbed from itsolution for test purpose but never work,Could any one tell where am I wrong?
Route
Route::get('ajaxImageUpload', ['uses'=>'AjaxImageUploadController#ajaxImageUpload']);
Route::post('ajaxImageUpload', ['as'=>'ajaxImageUpload','uses'=>'AjaxImageUploadController#ajaxImageUploadPost']);
Controller
public function ajaxImageUploadPost(Request $request) {
$validator = Validator::make($request->all(), [
'title' => 'required',
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
if ($validator->passes()) {
$input = $request->all();
$input['image'] = time() . '.' . $request->image->getClientOriginalExtension();
$request->image->move(public_path('images'), $input['image']);
AjaxImage::create($input);
return response()->json(['success' => 'done']);
}
return response()->json(['error' => $validator->errors()->all()]);
}
View
<form action="{{ route('ajaxImageUpload') }}" enctype="multipart/form-data" method="POST">
<input type="text" name="title" class="form-control" placeholder="Add Title">
<input type="file" name="image" class="form-control">
<button class="btn btn-success upload-image" type="submit">Upload Image</button>
</form>
<script>
$("body").on("click", ".upload-image", function (e) {
$(this).parents("form").ajaxForm(options);
});
var options = {
complete: function (response) {
if ($.isEmptyObject(response.responseJSON.error)) {
$("input[name='title']").val('');
alert('Image Upload Successfully.');
} else {
printErrorMsg(response.responseJSON.error);
}
}};
function printErrorMsg(msg) {
$(".print-error-msg").find("ul").html('');
$(".print-error-msg").css('display', 'block');
$.each(msg, function (key, value) {
$(".print-error-msg").find("ul").append('<li>' + value + '</li>');
});
}
</script>
Save Image Location To The Database
use intervention;
public function ajaxImageUploadPost(Request $request){
$validator = Validator::make($request->all(), ['title' => 'required','image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048']);
if ($validator->passes()) {
$image = new AjaxImage();
$image->title = $request->title;
if ($request->hasFile('image')) {
$img=$request->file('resim');
$filename=time().".".$img->getClientOriginalExtension();
$location=public_path('img/'.$filename);
Image::make($img)->save($location);
$image->image=$filename;
}
$image->save();
return response()->json(['success'=>'done']);
}
return response()->json(['error'=>$validator->errors()->all()]);
}

Call to a member function getClientOriginalName() on null when upload image use file system Laravel

I want to upload an image using Laravel storage file system in my admin data. However, there's an error when I attempt to upload an image.
Call to a member function getClientOriginalName() on null
Controller
public function store(Request $request)
{
$admin = $request->all();
$fileName = $request->file('foto')->getClientOriginalName();
$destinationPath = 'images/';
$proses = $request->file('foto')->move($destinationPath, $fileName);
if($request->hasFile('foto'))
{
$obj = array (
'foto' => $fileName,
'nama_admin' => $admin['nama_admin'],
'email' => $admin['email'],
'jabatan' => $admin['jabatan'],
'password' => $admin['password'],
'confirm_password' => $admin['confirm_password']
);
DB::table('admins')->insert($obj);
}
return redirect()->route('admin-index');
}
View
<div class="form-group">
<label for="" class="col-md-4">Upload Foto</label>
<div class="col-md-6">
<input type="file" name="foto">
</div>
</div>
Error
You can check wheather you are getting file or not by var_dump($request->file('foto')->getClientOriginalName());
And make sure your form has enctype="multipart/form-data" set
<form enctype="multipart/form-data" method="post" action="{{ url('/store')}}">
<div class="form-group">
<label for="" class="col-md-4">Upload Foto</label>
<div class="col-md-6">
<input type="file" name="foto">
</div>
</div>
</form>
Error because of client Side
<form enctype="multipart/form-data" method="post" action="{{ url('/store')}}">
<div class="form-group">
<label for="" class="col-md-4">Upload Foto</label>
<div class="col-md-6">
<input type="file" name="foto">
</div>
</div>
</form>
you ned to add enctype="multipart/form-data" inside the form
If You are using the form builder version
{!! Form::open(['url' => ['store'],'autocomplete' => 'off','files' => 'true','enctype'=>'multipart/form-data' ]) !!}
{!! Form::close() !!}
Then In your Controller You can check if the request has the file
I have Created the simple handy function to upload the file
Open Your Controller And Paste the code below
private function uploadFile($fileName = '', $destinationPath = '')
{
$fileOriginalName = $fileName->getClientOriginalName();
$timeStringFile = md5(time() . mt_rand(1, 10)) . $fileOriginalName;
$fileName->move($destinationPath, $timeStringFile);
return $timeStringFile;
}
And the store method
Eloquent way
public function store(Request $request)
{
$destinationPath = public_path().'images/';
$fotoFile='';
if ($request->hasFile('foto'))
{
$fotoFile= $this->uploadFile($request->foto,$destinationPath );
}
Admin::create(array_merge($request->all() , ['foto' => $fotoFile]));
return redirect()->route('admin-index')->with('success','Admin Created Successfully');
}
DB Facade Version
if You are using DB use use Illuminate\Support\Facades\DB; in top of your Controller
public function store(Request $request)
{
$admin = $request->all();
$destinationPath = public_path().'images/';
$fotoFile='';
if ($request->hasFile('foto'))
{
$fotoFile = $this->uploadFile($request->foto,$destinationPath );
}
$obj = array (
'foto' => $fotoFile,
'nama_admin' => $admin['nama_admin'],
'email' => $admin['email'],
'jabatan' => $admin['jabatan'],
'password' => $admin['password'],
'confirm_password' => $admin['confirm_password']
);
DB::table('admins')->insert($obj);
return redirect()->route('admin-index');
}
Hope it is clear

Upload multiple image for posts in laravel 5.5

I want to know how can I have multiple image in my posts?
Currently I have ImageController which I tried to get images and attach to post_id but the issue of that is if I use that method because I still didn't save my post there will be no id to be attached to images.
Any idea on that?
Please take a look for better understanding:
https://ibb.co/huC1Qw
blade:
<form action="upload" id="upload" enctype="multipart/form-data" method="post">
<div class="row">
<div class="col-md-6"><input type="file" class="form-control" name="files[]" multiple></div>
<div class="col-md-6"><input type="submit" class="btn btn-success" value="Upload now"></div>
</div>
</form>
controller:
public function upload(Request $request) {
$files = $request->file('file');
if (!empty($files)):
foreach($files as $file):
Storage::put($file->getClientOriginalName(), file_get_contents($file));
endforeach
endif;
return \response::json(array('success' => true));
}
route:
Route::post('/upload', 'ImageController#upload');
Approach 1.
Return $request->photos or put them in the session while you are not done yet with post submitting. After it was submitted assign references.
Approach 2.
First, save them in [temp] then move and assign to the post.
Approach 3.
Create a default record in your database, assign images to that record, get the record_id post_id and return to the form that post_id. Then just populate that post with your post_id.
Approach 4.
It is not the good choice to save images in the database, just save them as file and place de reference link in the database, or find them by the id of the folder that has the same id as your post, or beautify links to them ... definitely not by saving them to database. It is my opinion, everyone has to find his/her way for an easy living.
Try this :-
use App\ProductsPhoto; \\ add in top of controller
public function upload(Request $request) {
$product = Product::create($request->all());
if ($request->hasFile('files')) {
$files = $request->file('files');
foreach($files as $file){
$productsPhotos = new ProductsPhoto;
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$fileName = str_random(5)."-".date('his')."-".str_random(3).".".$extension;
$destinationPath = 'images/ProductsPhotos'.'/';
$file->move($destinationPath, $fileName);
$productsPhotos->product_id = $product->id,
$productsPhotos->filename = $fileName;
$productsPhotos->save();
}
}
return 'Upload successful!';
}
Hope it helps!
For upload and display images
if you are using two tables.
upload.blade.php
<form method="post" action="{{ url('/uploads') }}" enctype="multipart/form-data">
<input type="file" id="file" name="files[]" class="inputfile" value="{{ old('arquivo') }}" multiple />
Controller
public function show() {
$images = DB::select('SELECT * FROM table1 INNER JOIN table2 on table1.id = table2.id_file');
return view('index')->with('images', $images);
}
public function upload(yourRequest $request) {
$images = model1::create($request->all());
foreach ($request->files as $file) {
$filename = $file->store('/uploads');
modelFiles::create([
'id_file' => $images->id,
'file' => $filename
]);
}
return redirect()->action('Controller#show')->withInput(Request::only('name'));
}
index.blade.php
#foreach($images as $i)
<div class="item {{ $loop->first ? 'active' : '' }}">
<img src="{{ asset("storage/$i->file") }}" alt="...">
</div>
#endforeach

Resources