Laravel stored image is tmp not jpg when update data - laravel

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

Related

Mimes Validation not working correctly in Laravel 9

My webpage contains a file for upload, and I want the file uploaded only to be either jpg, jpeg or png.
My HTML looks like this:
<div class="form-group">
<label for="autoSizingInput">Brand Image</label>
<input type="file" class="form-control" id="autoSizingInput" name="brand_image"
aria-describedby="emailHelp">
#error('brand_image')
<span class="text-danger"> {{ $message }}</span>
#enderror
</div>
for checking files I used:
$request->validate(
[
'brand_image' => 'required|mimes:jpg,jpeg,png'
]);
when I upload pdf files it shows an error but when I upload any gif file it doesn't show any error.
$rules = [
'brand_image' => 'required|mimes:jpeg,jpg,png,
];
$validator = Validator::make($request->all(), $rules);
$validator->validate();
Try something like this
Try this it should work
$Rules = [ 'brand_image' => 'required|mimes:jpg,jpeg,png',
];
$Validator = Validator::make($r->all(), $Rules);
if ($Validator->fails()) {
return back()->withErrors($Validator->errors()->all());
} else {
Code....
}

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

Show checkbox checked from database

Hope you're all fine.
I have an article, and I want to be able to edit it. Inside the article, I have checkboxs, and what I want is to check the ones I've checked when I first create the article (Im using a pivot table).
I have this code for now.
public function createArticle(Request $request)
{
$data = $request->validate([
'titreArticle' => 'bail|required|between:5,40',
'typeArticle' => 'bail|required',
'themeCheckbox' => 'required',
'themeCheckbox.*' => 'required',
'contenuArticle' => 'bail|required',
]);
$type_articles = Type_article::findOrFail($data['typeArticle']);
$article = new Article();
$article->type_article()->associate($type_articles);
$themes = Theme::whereIn('theme_id', array_keys($data['themeCheckbox']))->get();
$article->titre = $data['titreArticle'];
$article->contenu = $data['contenuArticle'];
$article->save();
$article->theme()->attach( $themes);
return view('admin');
}
And inside my view :
#foreach ($themes as $theme)
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" name="themeCheckbox[{{$theme->theme_id}}]" value="1" >
<label class="form-check-label">{{ $theme->nom_theme }}</label>
</div>
#endforeach
I've seen I must use contains but don't really know how to use it...
Cordially

How store and retrieve image in database use 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();
};

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

Resources