So im building my own website and i have this feature wherein a logged-in user can upload and change his avatar. it is my first time doing this so i am having a hard time making this work. i’ll provide the codes below, you guys might see the faults that i dont know. it will be greatly appreciated if you can provide links that will help me improve. thanks in advance!
Blade.php file
<form method='POST' action="{{ route('image-upload') }}" enctype="multipart/form-data">
@csrf
<div class=" overflow-auto" style="padding-top:5%">>
<div class="p-3">
<div class="card">
<div class="card-body" >
<h4 class="card-title text-info"><strong> Attach your picture </strong></h4>
<div class="row justify-content-center">
<div class="col-sm-12 col-lg-4">
<div class="form-group row">
<label for="step5_picture" class="col-sm-3 text-right control-label col-form-label">Please upload your photo here:</label>
<div class="col-sm-9">
<input class="form-control" type="file" value="" id='upload_picture' >
</div>
</div>
</div>
</div>
<a href="/home" class="btn btn-lg waves-effect waves-light btn-success" id="btn-next" style="float:right;">Next</a>
<button class="btn btn-lg waves-effect waves-light btn-info" id="btn-upload" style="float:right; margin-right:10px;">Upload</button>
</div>
</div>
</div>
</div>
</form>
Ajax code
$("#btn-upload").click(function(e){
e.preventDefault();
var data = {
'photo_filename': $('#upload_picture').val(),
}
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: "/image-upload",
data: data,
dataType: "json",
success: function (response) {
}
});
});
});
Controller.php file The name of the column in my database is also photo_filename
public function image-upload(Request $request,){
$data = UserInfoModel::where('app_id', '=' ,Session::get('loginId'))->first();
$validator=Validator::make($request->all(), [
'photo_filename' => 'required',
'photo_filename.*' => 'image|mimes:jpeg,png,jpg,svg|max:5000'
]);
if($request->hasfile('photo_filename')){
$data->update([
'photo_filename' => $request->input('photo_filename')
]);
$photo = $request->file('photo_filename')->getClientOrginalName();
$destination = public_path() . '/public/image';
$request->file('photo_filename')->move($destination, $photo);
return back()->with('success', 'Your image has been successfully uploaded!');
}
}
Web.php file
Route::post(‘/image-upload’,[CustomAuthController::class, ‘image-upload’])->name(‘image-upload’);
2
Answers
use
FormData
to send file in form, and addcontentType: false
andprocessData: false
, you can read function settingcontentType
andprocessData
in here https://api.jquery.com/jquery.ajax/Here’s a minimal working example to create file upload in Laravel:
blade file:
Controller:
web.php:
Please note Ajax call is not necessary here, since html form will do the POST call with the CSRF token.
Also please note that using hyphens in function names won’t work in php.