i'm trying to upload multiple images using laravel and so far i've succeded, but the problem is that when i try to save text AND the files i get an error.
So far i've received so many errors that i can't remember all of then, but the latest is:
SQLSTATE[HY000]: General error: 1364 Field 'title' doesn't have a default value (SQL: insert into posts (image, updated_at, created_at) values (["italian.jpg"], 2019-05-23 18:48:22, 2019-05-23 18:48:22))
i've set the sql properly, and as i said, if i remove the image upload it works, and if i remove the text fields it also work, but if i try both i doesnt.
if i remember correctly when i remove the required fields it also works.
public function store(Request $request)
{
//dd($request);
$this->validate($request, [
'title' => 'required|min:3|max:120',
'text' => 'required',
'image' => 'required',
'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
if($request->hasfile('image')){
foreach($request->file('image') as $image)
{
$name=$image->getClientOriginalName();
$image->move(public_path().'/images/', $name);
$data[] = $name;
}
} else{
redirect('/posts')->with('Error', 'no image');
}
$post->image=json_encode($data);
$post = Post::create($validatedData);
return redirect('/posts')->with('success', 'yay');
}
i also tried this, but it returns
Creating default object from empty value
public function store(Request $request)
{
$validatedData = $request->validate([
'title' => 'required|min:3|max:120',
'category' => 'required|min:3|max:120',
'text' => 'required',
'image' => 'required',
'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if($request->hasfile('image'))
{
foreach($request->file('image') as $image)
{
$name=$image->getClientOriginalName();
$image->move(public_path().'/images/', $name);
$data[] = $name;
}
}
$post = new Post();
$post->image=json_encode($data);
$post->save();
return back()->with('success', 'Yay');
}
i figured it out, hehe. just had to remove these lines:
'image' => 'required',
'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
Thanks anyways.
Related
can someone help me, i want to add article with image. image has successfully entered the directory but in the database the name is always D:\xampp\tmp\php......tmp.
I have changed the system file to public.
Controller
public function store(Request $request)
{
//
$validateData = $request->validate([
'title' => 'required|max:255',
'thumbnail' => 'image|file|max:8192',
'slug' => 'required',
'description' => 'required',
]);
if ($request->file('thumbnail')) {
$imageName = time().'.'.$request->file('thumbnail')->getClientOriginalExtension();
$validatedData['thumbnail'] = $request->thumbnail->move(public_path('uploads/article/'), $imageName);
}
//dd($validateData['thumbnail']);
Article::create($validateData);
return redirect('/admin-article')->with('success', 'Data has been successfully added');
}
Try this
if ($request->file('thumbnail')) {
$imageName = time().'.'.$request->file('thumbnail')->getClientOriginalExtension();
$request->thumbnail->move(public_path('uploads/article/'), $imageName);
$validatedData['thumbnail'] = url('uploads/article/'.$imageName);
}
The reason why it's return a path instead of url because you're using public_path instead of url()
Controller Code
public function store(Request $request)
{
$validateData = $request->validate([
'title' => 'required|max:255',
'thumbnail' => 'image|file|max:8192',
'slug' => 'required',
'description' => 'required',
]);
// Check if request has file
if($request->hasFile('thumbnail')){
// Get File
$file = $request->file('thumbnail');
// Get File Extention
$fileGetFileExtension = $file->getClientOriginalExtension();
// Create customized file name
$fileName = Str::random(20).'_'.date('d_m_Y_h_i_s').'.'.$fileGetFileExtension;
// Save File to your storage folder
Storage::disk('public')->put('uploads/article/'.$fileName,File::get($file));
}else{
$fileName = null;
}
$validatedData['thumbnail'] = $fileName;
Article::create($validateData);
return redirect('/admin-article')->with('success', 'Data has been successfully added');
}
Run php artisan storage:link, if not created
In blade you can get your file like this
I hope this helps. :D
thanks for your answer my problem has been solved with code like this, but only the name of the file stored in the database not with the name of the directory.
public function store(Request $request)
{
$validateData = $request->validate([
'title' => 'required|max:255',
'thumbnail' => 'image|file|max:8192',
'slug' => 'required',
'description' => 'required',
]);
$imageName = time().'.'.$request->thumbnail->getClientOriginalExtension();
$request->thumbnail->move(public_path('articles/'), $imageName);
$Article = new Article;
$Article->title = $validateData['title'];
$Article->thumbnail = $imageName;
$Article->slug = $validateData['slug'];
$Article->description = $validateData['description'];
$Article->save();
return redirect('/admin-article')->with('success', 'Data has been successfully added');
}
I am trying to validate my data but for some reason I am getting this error
" Trying to get property 'title' of non-object"
Here's My Controller:-
public function store(Request $request)
{
$data = request()->validate([
'title' => 'required',
'body' => 'required',
]);
Post::create([
'title'=>$data->title,
'body'=>$data->body,
'created_by'=>$request->created_by,
'user_id'=>Auth::user()->id,
'filled_by'=>Auth::user()->uuid,
]);
return redirect('/home');
}
request()->validate([]); will return Array with validated data. You are using $data->title but $data is NOT an Object but Array.
Instead use
'title' => $data['title'],
I am having trouble retrieving form values using the Illuminate\Http\Request class.
I have an endpoint that creates a product and another that updates it set up like this
Route::post('products', 'ProductController#store');
Route::put('products/{product}', 'ProductController#update');
The store and update methods in the ProductController are
public function store(Request $request)
{
// validate inputs
$validator = Validator::make($request->all(), [
'name' => 'required',
'category' => 'required',
'status' => 'required',
'price' => 'required',
'image' => 'required|image|mimes:jpeg',
'interest' => 'required'
]);
// return 401 response if validation fails
if ($validator->fails()) {
return response()->json([$validator->errors()], 401);
}
// create & store the product
if ($product = Product::create([
'name' => $request->name,
'category' => $request->category,
'status' => $request->status,
'price' => $request->price,
'interest' => $request->interest,
])) {
// store the product image
$file = $request->file('image');
$destinationPath = "public/images/products";
$filename = 'pramopro_' . $product->name . '_' . $product->id . '.' . $file->extension();
Storage::putFileAs($destinationPath, $file, $filename);
ProductImage::create([
'product_id' => $product->id,
'name' => $filename
]);
}
// return new product
return new ProductResource($product);
}
public function update(Request $request, Product $product)
{
// dd($request);
// validate inputs
$validator = Validator::make($request->all(), [
'name' => 'required',
'category' => 'required',
'status' => 'required',
'price' => 'required',
'image' => 'required|image|mimes:jpeg',
'interest' => 'required'
]);
// return 401 response if validation fails
if ($validator->fails()) {
return response()->json([$validator->errors()], 401);
}
// update this product
if ($product) {
$product->update($request->all());
return new ProductResource($product);
} else {
return response()->json(["error" => "Not found"], 404);
}
}
Now when I test the endpoints in postman, I can successfully create a new product record. But if I try to update a product, I get a 401 unauthorized error even though all the required fields are filled. dd($request)returns null but dd($product) returns the product as expected.
Maybe I have been looking at it so hard so I have missed something. What am I doing wrong?
This is the reasons I think why the $request return null
The store and update request is same name. Two input name or select name or textarea name can't be the same name in the same web page. If its same it will always get the first one that is the reason why it is returning null because the first one is empty.
The name you're calling is incorrect
Hope it helps!
I'm trying to store an image in my Laravel project, but I'm having an issue. The image is sucessfuly being added to the /public/images folder as its filename, but when the request hits the database, its added as /private/var/tmp/XXXXX. I've tried to set $request->file as the name, but it still posts as the var/temp.
Controller
public function store(Request $request)
{
$rules = [
// 'address' => 'required',
// 'city' => 'required',
// 'postcode' => 'required',
// 'restDesc' => 'required',
// 'telNumb' => 'required',
// 'resWebsite' => 'required',
// 'restDesc' => 'required',
// 'business_id' => 'unique:busprofiles,business_id',
];
$customMessages = ["Message"];
if ($request->hasFile('file')) {
$request->file->store('public/uploads');
$filename = $request->file->getClientOriginalName();
$filesize = $request->file->getClientSize();
$request->file = $request->file->storeAs('public/uploads', $filename);
}
$this->validate($request, $rules, $customMessages);
Busprofile::create($request->all());
return redirect()->route('business.dashboard')
->with('success', 'Profile created successfully');
}
If it helps: return $request->file returns the correct URL.
The problem is in Busprofile::create($request->all());. You do indeed get the original filename with $filename = $request->file->getClientOriginalName(); but your request stays the same.
Create the array for the database entries manually, according to your database needs.
$data = ['filename' => $request->file->getClientOriginalName(),
...,
];
and
Busprofile::create($data);
Controller function:
public function addImages(Request $request,$imagesProductId)
{
$product = Product::create($request->all());
$filenames = array();
if ($request->images == '') {
return Redirect::back()->withErrors(['msg', 'The Message']);
}
if () {
// also need to validate on the extension and resolution of images
// (ie., if the validation fails the enum value will be "QCFailed")
} else {
foreach ($request->images as $photo) {
$filename = substr($photo->store('public/uploadedImages'), 22);
$filenames[] = asset('storage/uploadedImages/'.$filename);
ProductsPhoto::create([
'product_id' => $product->id,
'productId' => $imagesProductId,
'nonliveStatus' =>"QCVerified",
'filename' => $filename
]);
}
// echo('nonliveStatus');
}
return response()->json($filenames);
}
This is myfunction to insert array of images.For that I have used two model.The array of images get inserted but based on the validation the enum value should inserted respectively..My validations are the images are required and max size and its extensions
According Laravel 5.4 documentation you need to create validator object with set of rules. Something like this:
public function addImages(Request $request, $imagesProductId)
{
$product = Product::create($request->all());
$filenames = array();
if (empty($request->images)) {
return Redirect::back()->withErrors(['msg', 'The Message']);
}
$rules = [
'images' => 'mimes:jpeg,jpg,png' // allowed MIMEs
. '|max:1000' // max size in Kb
. '|dimensions:min_width=100,min_height=200' // size in pixels
];
$validator = Validator::make($request->all(), $rules);
$result = $validator->fails() ? 'QCFailed' : 'QCVerified';
foreach ($request->images as $photo) {
$filename = substr($photo->store('public/uploadedImages'), 22);
$filenames[] = asset('storage/uploadedImages/'.$filename);
ProductsPhoto::create([
'product_id' => $product->id,
'productId' => $imagesProductId,
'nonliveStatus' => $result,
'filename' => $filename
]);
}
return response()->json($filenames);
}
Recently I used Dropzone for multiple image upload in laravel 6 and get in problem to validate an array of images,
finally, it solved my two-step validation.
one for the whole array and second validation for each element of the array.
I put the code here, maybe helpful for someone.
$request->validate([
'product_code' => 'required|string',
'product_name' => 'required|string',
'product_price' => 'required|string',
'product_count' => 'required|string',
'category_id' => 'nullable|numeric',
'file' => 'nullable', //name of image field in form
'file.*' => 'max:2048|image' //name of image field in form
]);