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.');
}
Related
I have a blog where I am creating an update function and I removed the required parameter from my 'image' field and set it to 'nullable' since it makes sense to give the user an option to change the image if they want to or not after creating their post.
Update function
public function update(Request $request, Posts $post) {
$formFields = $request->validate([
'title' => 'required|min:3|max:50',
'image' => 'nullable|image|mimes:jpg,png,jpeg,gif,svg|max:2048',
'sub_title' => 'required|min:3|max:100',
'tags' => 'required|min:3|max:20',
'content' => 'required',
'featured' => 'nullable',
]);
$image_path = $request->file('image')->store('thumbnails', 'public');
if($request->has('featured')) {
Posts::where('featured', '=',1)
->update(['featured' => false]);
}
$post->update([
'title' => $request->post('title'),
'image' => $image_path,
'sub_title' => $request->post('sub_title'),
'tags' => $request->post('tags'),
'content' => $request->post('content'),
'featured' => ($request->has('featured')) ? true : false,
]);
return redirect('/')->with('message', 'Post updated successfully!');
}
More specifically, the error is being pointed out on this line:
$image_path = $request->file('image')->store('thumbnails', 'public');
You should call the store method only when you have new image file:
$image_path = $request->file('image')?->store('thumbnails', 'public');
and then add $image_path to attributes only when you have new image:
$attributes = [
'title' => $request->post('title'),
'sub_title' => $request->post('sub_title'),
'tags' => $request->post('tags'),
'content' => $request->post('content'),
'featured' => ($request->has('featured')) ? true : false,
];
if ($image_path) {
$attributes['image'] = $image_path;
}
$post->update($attributes);
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.
When I try to update a post if I dont change value of slug , laravel return this error:
The slug has already been taken.
Here is my validation:
$this->validate($request, [
'name' => 'required',
'content' => 'required',
'excerpt' => 'required',
'type' => 'required',
'slug' => 'required | unique:providers'
]);
when you're updating records and there is unique validation is added. You should pass the id of which record you're inserting.
While Update
'slug' => 'required | unique:providers,slug,'.$providerId
While insert
'slug' => 'required | unique:providers'
You need to add an except rule to your unique case to exclude the current ID from check:
$this->validate($request, [
'name' => 'required',
'content' => 'required',
'excerpt' => 'required',
'type' => 'required',
'slug' => 'required|unique:providers,id,' . $provider->id
]);
Make the column and the id that you pass to use your table's data. I am just giving you an idea on what you need to add.
You need to tell the validator to do an exception for the current entity you're updating.
$this->validate($request, [
'name' => 'required',
'content' => 'required',
'excerpt' => 'required',
'type' => 'required',
'slug' => 'required|unique:providers,slug,'.$providerId
]);
When adding:
use Illuminate\Support\Str;
.
.
$slug = Str::slug($request->name, '-');
$exists = Provider::where('slug', $slug)->first();
if($exists) {
$slug = $slug.'-'.rand(1000,9999);
}
When updating:
$request->validate([
'slug' => 'required|unique:providers,slug,'.$provider_id.',id',
]);
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'));
}
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!');
}