Validating image and storing image in specific folder - php

I am validating and storing image using my Controller.
When I validate image form is not stored in database but when I comment validation it stores in database.
FrontController.php
public function StorePost(Request $request)
{
$formInput = $request->except('image');
$this->validate($request, [
'title' => 'required',
'name' => 'required',
'email' => 'required|email',
'contact' => 'required',
'model' => 'required',
'city' => 'required',
'description' => 'required',
'image' => 'image|mimes:png,jpg,jpeg|max:10000'
]);
//image upload
$image = $request->image;
if($image){
$imageName = $image->getClientOriginalName();
$image->move('images', $imageName);
$formInput['image'] = $imageName;
}
Post::create($formInput);
$posts = Post::all();
return view('ad.ad', compact('name', 'posts'));
}

Related

How can i upload a picture in laravel?

i'm trying to insert a product with a picture into my database , but when i submit nothing get inserted .
i tried to add 'Image1' => 'required|Image' but i get Unable to guess the MIME error
This is the Store method
public function store(Request $request)
{
$data = request()->validate([
'Name' => 'required',
'Title' => 'required',
'category' => 'required',
'MainPrice' => 'required',
'MainPrice' => 'required',
'StockQuantity' => 'required',
'Discription' => 'required',
'Features' => 'required',
'Image1' => 'required'
]);
$imagePath =request('Image1')->store('uploads', 'public');
$image = Image::make(public_path("storage/{$imagePath}"))->fit(1200, 1200);
$image ->save();
$query = DB::table('products')->insert([
'Name' => $request->input('Name'),
'Title' => $request->input('Title'),
'category' => $request->input('category'),
'MainPrice' => $request->input('MainPrice'),
'DiscountPrice' => $request->input('DiscountPrice'),
'StockQuantity' => $request->input('StockQuantity'),
'Discription'=> $request->input('Discription'),
'Features'=> $request->input('Features'),
'Image1'=> $imagePath
]) ;
if($query){
return back()->with('success', 'Data have been successfuly inserted');
}
else{
return back()->with('fail', 'Somethimg went wrong');
}
}
and this is the Route
Route::post('Product', [ProductsController::class, 'store']);
Any one faced the same problem ?
Your picture is probably in the wrong format. RTF is the most commonly used format, but it's not compatible with MySQL. You need an image format that supports transparency, such as GIF, JPG, or PNG.

Laravel: Upload picture to public/images - wrong file name

i'm trying to save an uploaded picture in the public/images directory.
public function store(Request $request)
{
$request->validate([
'title' => 'required',
'description' => 'required',
'image' => 'required|image|mimes:jpg,png,jpeg|max:5048'
]);
$newImageName = uniqid() . '-' . $request->title . '.' . $request->image->extension();
$request->image->move(public_path(('images'), $newImageName));
Post::create([
'title' => $request->input('title'),
'description' => $request->input('description'),
'slug' => SlugService::createSlug(Post::class, 'slug', $request->title),
'image_path' => $newImageName,
'user_id' => auth()->user()->id
]);
return redirect('/blog')
->with('message', 'Dein Beitrag wurde erstellt.');
}
Everything works just fine - exept for the file name. It should have the name of $newImageName but it looks like 'php51F7.tmp'. Also the extension is '.tmp' and not '.png' or '.jpg'.
Thank you very much for your help!
PS: I'm an absolut beginner in Laravel, please be patient.
It is issue of extra round bracket
Replace
$request->image->move(public_path(('images'), $newImageName));
With
$request->image->move(public_path('images'), $newImageName);
You have typo in your code
public function store(Request $request)
{
$request->validate([
'title' => 'required',
'description' => 'required',
'image' => 'required|image|mimes:jpg,png,jpeg|max:5048'
]);
$newImageName = uniqid() . '-' . $request->title . '.' . $request->image->extension();
#Notice here, move() accepts two parameteres
$request->image->move(public_path('images'), $newImageName);
Post::create([
'title' => $request->input('title'),
'description' => $request->input('description'),
'slug' => SlugService::createSlug(Post::class, 'slug', $request->title),
'image_path' => $newImageName,
'user_id' => auth()->user()->id
]);
return redirect('/blog')
->with('message', 'Dein Beitrag wurde erstellt.');
}

how to make validation on composite unique key

i have three columns in my database ,
i need to make a validation for these columns ,
and to make the tree of them unique.
Validator::make($request->all(),
[
'name' => 'required|min:4|string',
'color'=>'required',
'size_id'=>'required',
]);
i already tried
Validator::make($request->all(),
[
'name' => 'required|min:4|string|unique:products,name,color,size_id',
'color'=>'required|unique:products,color,name,size_id',
'size_id'=>'required|unique:products,size_id,name,color',
]);
and i tried this
$color = $request->input('color');
$size_id = $request->input('size_id');
$name = $request->input('name');
// dd($name);
return
Validator::make($request->all(),
[
'name' => 'required|min:4|string|unique:products,name,'.'NULL'.',color,'.$color.',size_id,'.$size_id,
'description'=>'required|min:4',
'quantity'=>'required|numeric',
'subcategory_id'=> 'required',
'category_id'=> 'required',
'price'=> 'required|numeric',
'color'=>'required|unique:products,color,'.'NULL'.',name,'.$name.',size_id,'.$size_id,
'size_id'=>'required|unique:products,size_id,'.'NULL'.',name,'.$name.',color,'.$color,
'cover'=>'required|image:png,jpg,jpeg',
// 'images'=>'image:png,jpg,jpeg',
'images.
*'=>'image:png,jpg,jpeg',
]);
but it return undefined offset 3 when i check if it fails or not!
thanks
$color = $request->get('color');
$size_id = $request->get('size_id');
$name = $request->get('name');
// dd($name);
return
Validator::make($request->all(),
[
'name' => 'required|min:4|string|unique:products,name,NULL,id,color,'.$color.',size_id,'.$size_id,
'description'=>'required|min:4',
'quantity'=>'required|numeric',
'subcategory_id'=> 'required',
'category_id'=> 'required',
'price'=> 'required|numeric',
'color'=>'required|unique:products,color,NULL,id,name,'.$name.',size_id,'.$size_id,
'size_id'=>'required|unique:products,size_id,NULL,id,name,'.$name.',color,'.$color,
'cover'=>'required|image:png,jpg,jpeg',
// 'images'=>'image:png,jpg,jpeg',
'images.*'=>'image:png,jpg,jpeg',
]);
the code above solved my problem

How can I save two models at the same time in Laravel?

I want to know how can I save two models which has one relationship in my models. I don't know how to save it but I need the ID for my patient model to assign to my scale model.
Here is my PatientController.
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'birth' => 'required',
'nacionality' => 'required',
'adress' => 'required',
'phone' => 'required',
'living_method' => 'required',
'responsable' => 'required',
]);
//Create Patient
$patient = new Patient;
$scales = new Scale;
$patient->name = $request->input('name');
$scales->sd_abc_1_old = $request->input('sd_abc_1_old');
$patient->save();
return redirect('/patients')->with('success', 'Paciente creado.');
}
I try this code but get error.
DB::transaction(function() use ($patient, $scales) {
$patient = $patient->save(); //Patient Exists First
Patient::find($patient->id)->scales()->save($scales)
});
You could try something like this:
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'birth' => 'required',
'nacionality' => 'required',
'adress' => 'required',
'phone' => 'required',
'living_method' => 'required',
'responsable' => 'required',
]);
//Create Patient
$patient = new Patient;
$patient->name = $request->name;
$patient->save();
$patient->scale()->create(['patient_id' => $patient->id, 'sd_abc_1_old' => $request->sd_abc_1_old]);
);
return redirect('/patients')->with('success', 'Paciente creado.');
}
If the model uses a hasOne() relation like you said then the code show work, with a bit of modification of course.
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'birth' => 'required',
'nacionality' => 'required',
'adress' => 'required',
'phone' => 'required',
'living_method' => 'required',
'responsable' => 'required',
]);
//Create Patient
$patient = Patient::create([
'name' => $request->input('name'),
]);
$scale = Scale::create([
'patient_id' => $patient->id,
'sd_abc_1_old' => $request->sd_abc_1_old,
]);
return redirect('/patients')->with('success', 'Paciente creado.');
}
First create and store base model and referencing it save related model
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'birth' => 'required',
'nacionality' => 'required',
'adress' => 'required',
'phone' => 'required',
'living_method' => 'required',
'responsable' => 'required',
]);
//Create Patient
$patient = new Patient;
$patient->name = $request->input('name');
$patient->save();
$scales = new Scale;
$scales->sd_abc_1_old = $request->input('sd_abc_1_old');
$patient->scales()->save($scales);
return redirect('/patients')->with('success', 'Paciente creado.');
}

Data is again added to the database after reloading the page

Whenever I am directed to ad page and then reload same data is again entered in the database. Is there any other of redirecting of page while keeping those compact variables???
Controller.php
public function StorePost(Request $request)
{
$formInput = $request->except('image');
$this->validate($request, [
'title' => 'required',
'name' => 'required',
'email' => 'required|email',
'contact' => 'required',
'model' => 'required',
'city' => 'required',
'description' => 'required',
'image'=>'image|mimes:png,jpg,jpeg|max:10000'
]);
$image = $request->image;
if($image){
$imageName = $image->getClientOriginalName();
$image->move('images',$imageName);
$formInput['image'] = $imageName;
}
Post::create($formInput);
$posts = Post::all();
return view('ad.ad',compact('name','posts'));
}}
You may want to simply redirect (redirect('/ad_url')) to the 'ad' route/page. Lets say maybe 'ControllerForAddPage' is the one that displays your 'ad' view, simply instead fetch all the posts in that controller and not in the controller that handles saving your data.
I think it's better to use different route between store and show. you just need to redirect to index route after store success. ex:
...
Post::create($formInput);
return redirect()->route('ad.index');
You should redirect to different location to avoid this. If data is successfully store then redirect it to posts list url otherwise to the same location again with error message.
Example code is follows:
public function StorePost(Request $request) {
$formInput = $request->except('image');
$this->validate($request, [
'title' => 'required',
'name' => 'required',
'email' => 'required|email',
'contact' => 'required',
'model' => 'required',
'city' => 'required',
'description' => 'required',
'image' => 'image|mimes:png,jpg,jpeg|max:10000'
]);
$image = $request->image;
if ($image) {
$imageName = $image->getClientOriginalName();
$image->move('images', $imageName);
$formInput['image'] = $imageName;
}
$store = Post::create($formInput);
if($store){
//return to posts list view
return redirect('posts')->with('success', 'Post successfully stored.');
}
//redirect to the form to create post
return redirect()->back()->with('failed', 'Failed to store the post!');
}

Categories