Reputation: 643
The problem:
I want to upload an image to a mySQL database using Laravel.
what I have tried:
I looked for other stack-overflow questions but they weren't helpful.
the result I am expecting :
is to have the image name or path saved to a column in my table on the database , to retrieve and display it later as a post in a blog.
Upvotes: 3
Views: 22089
Reputation: 1
In Js
$(document).ready(function(){
console.log('doc ready');
$('#category_add_btn').on('click', function(){
add_category();
});
});
function validate() {
var Valid = true;
var allowedTypes = ['image/jpeg', 'image/png', 'image/jpg'];
var maxSize = 2 * 1024 * 1024; // 2MB
// Validate name
if ($('#name').val().trim() === "") {
Valid = false;
alert('Name is required');
}
// Validate image
var imageInput = $('#image')[0];
if (imageInput.files.length === 0) {
Valid = false;
alert('Image is required');
} else {
var imageFile = imageInput.files[0];
// Validate image type (MIME)
if (!allowedTypes.includes(imageFile.type)) {
Valid = false;
alert('Invalid image type. Only JPEG, PNG, and JPG are allowed.');
}
// Validate image size
if (imageFile.size > maxSize) {
Valid = false;
alert('Image size should not exceed 2MB.');
}
}
return Valid;
}
function add_category(){
var input_array = ['name','image'];
removeErrorMessage(input_array);
if (validate()) {
var formData = $('#category_form').serialize();
$.ajax({
data: formData,
type: 'POST',
dataType: 'JSON',
processData : 'false',
contetTpye : 'false',
url: base_url + '/add_category',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
success: function(response){
if(response.status){
window.location.href = response.redirect_url;
}else{
alert(response.message);
}
},
error: function(error, xhr, status){
console.log('xhr', xhr);
console.log('error', error);
console.log('status', status);
var response_error = error.responseJSON.errors;
console.log(response_error);
displayError(response_error);
}
});
console.log('form', formData);
} else {
console.log('not validated');
}
}
function displayError(response_error){
$.each(response_error, function(input_id, error_message){
$('#error-' + input_id).html(error_message);
});
}
function removeErrorMessage(input_array){
$.each(input_array, function(key, input_id){
$('#error-' + input_id).html('');
});
}
In controller
public function add_category(){
$return_array = ['status'=> false, 'message'=>''];
$rules = [
'name' => 'required|name|string',
'image' => 'required|image|mimes:jpeg,png,jpg|max:2048'
];
$validators = Validator::make($request->all(),$rules);
if ($validators->fails()) {
return response()->json(['status'=>false,'errors'=>$validators->errors()],422);
}else{
$create_category = new Categories();
$name = $request->input('name');
$create_category->name = $name;
if ($request->file('image')) {
$image = $request->file('image');
$extension = $image->getClientOriginalExtension();
$imagename = time().'.'.$extension;
$image->move(public_path('uploads'),$imagename);
$create_category->image = $imagename;
}else{
$return_array['message'] = 'Please Upload Valid Image';
}
$created = $create_category->save();
if ($created) {
$return_array['status'] = true;
$return_array['message'] = 'Category Added Successfully ';
$return_array['redirect_url'] = url('dashboard');
}else{
$return_array['message'] = 'Failed Try Again';
}
}
return response()->json($return_array);
}
Upvotes: 0
Reputation: 27
$data['profile_image'] = $request->profile_image->store('profile-images');
protected function profileImageUrl(): Attribute
{
return Attribute::make(
get: fn () => Storage::url($this->profile_image)
);
}
protected $appends = [
"full_doc_url",
];
public function getFullDocUrlAttribute()
{
return url('storage/TruckAttachment/'. $this->File);
}
if ($request->hasfile('file')) {
$filename = str_replace(' ', '', Str::uuid() . '.' . $request->file->getClientOriginalExtension());
$request->file->storeAs('public/TruckAttachment', $filename);
$imagepath = url('storage/TruckAttachment/' . $filename);
}
Upvotes: -1
Reputation: 11
Use this to upload image
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// $this->validate($request,[//'movie_name'=>'required',
// // 'description'=>'required',
// //'video_url'=>'required',
// 'image'=>'required|mimes:jpeg,jpg,png,gif|required|max:10000',
// ]);
if ($request->hasFile('image') && $request->hasFile('image2')) {
$file = $request->file('image');
//$image=$file->getClientOriginalName();
$image = time().'.'.$file->getClientOriginalExtension();
$destinationPath ='assets/admin/uploads/image/';
$file->move($destinationPath,$image);
//echo $destinationPath;exit();
//echo $image."<br/>";
$file2 = $request->file('image2');
$bg_images = time().'.'.$file2->getClientOriginalExtension();
//$bg_images=$file2->getClientOriginalName();
$destinationPath ='assets/admin/uploads/bg_images/';
$file2->move($destinationPath,$bg_images);
$insert_data=array('movie_name'=>$request->movie_name,
'description'=>$request->description,
'video_url'=>$request->video_url,
'image'=>$image,
'bg_images'=>$bg_images,
'created_at'=>now(),
'updated_at'=>now()
);
//print_r($insert_data);exit();
}
else
{
if ( $request->hasFile('image2')) {
$file2 = $request->file('image2');
$bg_images = time().'.'.$file2->getClientOriginalExtension();
//$bg_images=$file2->getClientOriginalName();
$destinationPath ='assets/admin/uploads/bg_images/';
$file2->move($destinationPath,$bg_images);
//echo $destinationPath;exit();
//echo $bg_images;
$insert_data=array('movie_name'=>$request->movie_name,
'description'=>$request->description,
'video_url'=>$request->video_url,
//'image'=>$image,
'bg_images'=>$bg_images,
'created_at'=>now(),
'updated_at'=>now()
);
//print_r($insert_data);exit();
}
if ($request->hasFile('image') ) {
$file = $request->file('image');
//$image=$file->getClientOriginalName();
$image = time().'.'.$file->getClientOriginalExtension();
$destinationPath ='assets/admin/uploads/image/';
$file->move($destinationPath,$image);
//echo $destinationPath;exit();
//echo $image."<br/>";
$insert_data=array('movie_name'=>$request->movie_name,
'description'=>$request->description,
'video_url'=>$request->video_url,
'image'=>$image,
//'bg_images'=>$bg_images,
'created_at'=>now(),
'updated_at'=>now()
);
// print_r($insert_data);exit();
}
if ( ! $request->hasFile('image2') && ! $request->hasFile('image') ) {
$insert_data=array('movie_name'=>$request->movie_name,
'description'=>$request->description,
'video_url'=>$request->video_url,
//'image'=>$image,
// 'bg_images'=>$bg_images,
'updated_at'=>now()
);
// print_r($update_data);exit();
}
}
//exit();
// echo $image;
//exit();
//print_r($insert_data);exit();
$insert=DB::table('movies')->insert($insert_data);
if ($insert) {
return redirect()->route('admin.list_movies')->withSuccess('Record saved');
}
else {
return redirect()->route('admin.list_movies')->withError('Record not saved');
}
}
Upvotes: 1
Reputation: 423
Actually with Laravel it only involves a few lines of code. Let's say you have a user that has an avatar which is stored in the database. Here's how you would store and retrieve the avatar from the database:
1. First you'll need to have an avatar column in the users table that can store binary data. Depending on how large you want to allow the avatar image to be, the data type of the column can be one of the following:
BLOB up to 64KB
MEDIUMBLOB up to 16MB
LONGBLOB up to 4GB
2. To store the uploaded image in the database you can do this:
Route::post('user/{id}', function (Request $request, $id) {
// Get the file from the request
$file = $request->file('image');
// Get the contents of the file
$contents = $file->openFile()->fread($file->getSize());
// Store the contents to the database
$user = App\User::find($id);
$user->avatar = $contents;
$user->save();
});
3. To fetch and ouput the avatar you can do the following:
Route::get('user/{id}/avatar', function ($id) {
// Find the user
$user = App\User::find(1);
// Return the image in the response with the correct MIME type
return response()->make($user->avatar, 200, array(
'Content-Type' => (new finfo(FILEINFO_MIME))->buffer($user->avatar)
));
});
NOTE: Please have this in your mind, MySQL isn't a suitable solution to store BLOB. You may need to use an object storage service like Amazon S3.
Upvotes: 2
Reputation: 170
First you need the form on your view (don't forget the csrf token):
<form action="/image-upload" method="POST" enctype="multipart/form-data">
@csrf
<input type="file" name="image">
<button type="submit">Upload</button>
</form>
And on your routes file add the route for POST method:
Route::post('image-upload', 'ImageUploadController@imageUploadPost');
Then on your Controller create the function that will validate and move your image to the 'public/images' folder.
public function imageUploadPost()
{
request()->validate([
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$imageName = time().'.'.request()->image->getClientOriginalExtension();
request()->image->move(public_path('images'), $imageName);
}
For better solution please read this: Laravel File Storage
Upvotes: 4