Change image name and save to DB Laravel - laravel

Hi i can not store image name to database in Laravel project.
How to solve this?
Here is codes of controller
class TarifController extends Controller
{
public function store(Request $request)
{
$request->validate([
'title_uz' => 'required',
'desc_uz' => 'required',
'full_desc_uz' => 'required',
'company_id' => 'required',
'order' => 'required',
'image' => 'required|image|mimes:jpeg,png,jpg,svg|max:2048',
]);
$image1 = time().'.'.$request->image->extension();
$request->image->move(public_path('images'), $image1);
Tarif::create($request->all());
return redirect()->route('tarifs.index')
->with('success','Yangi tarif muvoffaqiyatli qo`shildi.');
}
}
and here is codes from view
<form role="form" action="{{ route('tarifs.store') }}" method="post" enctype="multipart/form-data">
#csrf
<div> .. another fields .. </div>
<div class="col-5">
<label for="image">Surat</label>
<input type="file" class="form-control" name="image" id="image" required>
</div>
<div> .. another fields .. </div>
<div class="card-footer">
<a class="btn btn-info" href="{{ route('tarifs.index') }}">Qaytish</a>
<button type="submit" class="btn btn-success">Saqlash</button>
</div>
</form>
It saves image to public/images folder but didn't saves filename or path to DB. The field name is 'image' on database.

If you need to merge new values into a request object, the following code would have done the trick :
$request->merge(['image' => 'avatar.png']);
Or, you can change your code like this :
$image1 = time().'.'.$request->image->extension();
$request->image->move(public_path('images'), $image1);
$input = $request->all();
$input['image'] = $image1;
Tarif::create($input);

Related

Can't upload files using livewire

I can't submit a form with file in order to proced to upload method, the file is selected when I submit it says that the file is required (empty data).
Everything works fine on mylocal Windows machine but I face the problem when using vps for production.
view :
<form wire:submit.prevent="submit" enctype="multipart/form-data">
<div>
#if(session()->has('message'))
<div class="alert alert-success">
{{ session('message') }}
</div>
#endif
</div>
<div class="form-group">
<label for="exampleInputName">Title:</label>
<input type="text" class="form-control" id="exampleInputName" placeholder="Enter title" wire:model="title">
#error('title') <span class="text-danger">{{ $message }}</span> #enderror
</div>
<div class="form-group">
<label for="exampleInputName">File:</label>
<input type="file" class="form-control" id="exampleInputName" wire:model="file">
#error('file') <span class="text-danger">{{ $message }}</span> #enderror
</div>
<button type="submit" class="btn btn-success">Save</button>
</form>
controller :
use WithFileUploads;
public $file, $title;
public function submit()
{
$validatedData = $this->validate([
'title' => 'required',
'file' => 'required',
]);
$validatedData['name'] = $this->file->store('files', 'public');
// File::create($validatedData);
session()->flash('message', 'File successfully Uploaded.');
}
VPS folders :
I tried to change permessions, user group.... no success.
try this
use WithFileUploads;
public $title;
public $file;
protected function rules()
{
return [
'title' => ['required', 'string', 'max:50'],
'file' => ['required', 'file', 'mimes:pdf,doc,docx', 'max:5000']
];
}
public function submit()
{
$this->validate();
$data = [
'title' => $this->title
];
if (!empty($this->file)) {
$url = $this->file->store('files', 'public');
$data['file'] = $url;
}
File::create($data);
session()->flash('message', 'File successfully Uploaded.');
}

Laravel can not display image

trying to upload an image through a post Form:
this is my controller:
public function store(Request $request)
{
$request->validate([
'title'=>'required',
'content'=>'required',
'image'=>'required',
'description'=>'required'
]);
$image = $request->image->store('images');
Post::create([
'title' => $request->input('title'),
'content' => $request->input('content'),
'description' => $request->input('description'),
'image' => $image
]);
return redirect(route('posts.index'))->with('success', 'Posts Submitted successfully');
}
I used : php artisan storage:link which generated a folder named images in public directory: Absolute path is:
C:\xampp\htdocs\blogPholio\public\storage\images\KWDKRrty2ijXjrgrismvyiV4k6UAQNrFogJl9W2f.jpeg
in my blade I am trying to show image through/:
<img src="{{Storage::url($post->image)}}">
My form in the create blade looks like:
<form action="{{ route('posts.store') }}" method="POST" enctype="multipart/form-data">
#csrf
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Image:</strong>
<input type="file" name="image" class="form-control" placeholder="upload:">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
<button type="submit" class="btn btn-primary">Add</button>
</div>
</div>
</form>
Thanksa lot
Try this
<img src="{{asset(Storage::disk('local')->url($post->image))}}"/>

Laravel Image Upload not saving to public folder

I am struggling with this image upload system.
It is supposed to upload an image that will be attached to a post (each post has 1 image).
Everything seems to be working fine, the problem is that when I check the database for the image path, I see a path to a random temporary file and the image doesn't even get uploaded to the right folder inside the app public folder.
Check the logic below:
PostController.php
public function store(Request $request)
{
$post = new Post;
$request->validate([
'title' => 'required',
'description' => 'required',
'slug' => 'required',
'message' => 'required',
'user' => 'required',
'post_image' => 'image|mimes:jpeg,png,jpg,gif|max:2048'
]);
if ($request->has('post_image')) {
$image = $request->file('post_image');
$name = Str::slug($request->input('title')).'_'.time();
$folder = '/uploads/images/';
$filePath = $folder . $name. '.' . $image->getClientOriginalExtension();
$this->uploadOne($image, $folder, 'public', $name);
$post->post_image = Storage::url($filePath);;
}
Post::create($request->all());
return \Redirect::to('admin')->with('success','Great! Post created successfully.');
}
UploadTrait.php
trait UploadTrait
{
public function uploadOne(UploadedFile $uploadedFile, $folder = null, $disk = 'public', $filename = null)
{
$name = !is_null($filename) ? $filename : Str::random(25);
$file = $uploadedFile->storeAs($folder, $name.'.'.$uploadedFile->getClientOriginalExtension(), $disk);
return $file;
}
}
Post.php (model)
class Post extends Model
{
protected $fillable = [
'title',
'description',
'slug',
'message',
'user',
'post_image'
];
public function getImageAttribute(){
return $this->post_image;
}
}
Create.blade.php
<form action="{{ route('blog.store') }}" method="POST" name="add_post" role="form" enctype="multipart/form-data">
{{ csrf_field() }}
<h1>New Post</h1>
<div role="separator" class="dropdown-divider"></div>
<div class="form-row">
<div class="form-group col-12 col-md-6">
<label for="title">Post Title</label>
<input type="text" autocomplete="off" class="form-control" id="title" name="title" placeholder="Your post title" required>
<span class="text-danger">{{ $errors->first('title') }}</span>
</div>
<div class="form-group col-12 col-md-6">
<label for="slug">Slug</label>
<input type="text" autocomplete="off" class="form-control" id="slug" name="slug" placeholder="Write post slug" required>
<span class="text-danger">{{ $errors->first('slug') }}</span>
</div>
</div>
<div class="form-row">
<div class="form-group col-12 col-md-12">
<label for="description">Post Description</label>
<textarea class="form-control" id="description" name="description" placeholder="Enter a small description for your post" required></textarea>
<span class="text-danger">{{ $errors->first('description') }}</span>
</div>
</div>
<div class="badge badge-warning badge-pill">Message</div>
<div role="separator" class="dropdown-divider"></div>
<div class="form-row">
<div class="form-group col-md-12">
<textarea class="form-control" col="4" id="message" name="message"></textarea>
<span class="text-danger">{{ $errors->first('message') }}</span>
</div>
</div>
<input type="hidden" value="{{ Auth::user()->name }}" name="user">
<input id="post_image" type="file" class="form-control" name="post_image">
<button type="submit" class="btn btn-warning btn-block">Create Post</button>
</form>
Thank you for your help!
Regards,
Tiago
You can use directly the functions provided by Laravel itself
$image_path = Storage::disk('public')->putFile('folders/inside/public', $request->file('post_image'));
Notice Storage::disk('public') that specifies the public folder.
Then you can update your request array with $request['image_path'] = $image_path and save it like you're currently doing or you cant still use your $post = new Post; and set every input data like $post->title = $request->title; then save like $post->save();
You did not save the image path in the database on the created post
$post = new Post; //here you have created an empty Post object
...
$post->post_image = Storage::url($filePath); //here you assigned the post_image to the empty object.
Post::create($request->all());// here you create a new POST object with the request data, which does not contain the post_image
Thank you David! I managed to correct the path that gets saved to the database, but the files are not getting uploaded (even though the path in database says /uploads/images/something.png, when i check the folder, the image is not there.. there is not even an uploads folder. This is the method I have now with your suggestions:
public function store(Request $request)
{
$request->validate([
'title' => 'required',
'description' => 'required',
'slug' => 'required',
'message' => 'required',
'user' => 'required',
'post_image' => 'image|mimes:jpeg,png,jpg,gif|max:2048'
]);
if ($request->has('post_image')) {
$image = $request->file('post_image');
$name = Str::slug($request->input('title')).'_'.time();
$folder = '/uploads/images';
$filePath = $folder . $name. '.' . $image->getClientOriginalExtension();
$this->uploadOne($image, $folder, 'public', $name);
$image_path = Storage::disk('public')->putFile('uploads/images', $request->file('post_image'));
$request['image_path'] = $image_path;
}
$post = new Post;
$post->title = $request->title;
$post->description = $request->description;
$post->slug = $request->slug;
$post->message = $request->message;
$post->user = $request->user;
$post->post_image = $request->image_path;
$post->save();
return \Redirect::to('admin')->with('success','Great! Post created successfully.');
}
Input in form
<form method="POST" enctype="multipart/form-data" action="/url">
<input id="category_logo" type="file" class="form-control" name="category_logo">...
Code in controller
$category = Category::find($id);
if($request->has('category_logo')) {
$image = $request->file('category_logo');
$category->category_logo = $image->getClientOriginalName();
$image->move(public_path('img/logo'), $image->getClientOriginalName());
}
$category->save();
Works for me!

The image failed to upload.on a server laravel

The image failed to upload.
link
https://comedoruniversitariouncp.000webhostapp.com/products/create
The project works in local server,
the error appears when i upload to a server
create.blade.php
<form action="{{ route('products.store') }}" method="POST" enctype="multipart/form-data">
#csrf
<div class="form-group row">
<label class="col-form-label col-sm-2">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="name">
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2">Price</label>
<div class="col-sm-10">
<input type="number" class="form-control" name="price" step="0.1">
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2">Amount</label>
<div class="col-sm-10">
<input type="number" class="form-control" name="amount" >
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2">Image</label>
<div class="col-sm-10">
<input type="file" class="form-control-file" name="image">
</div>
</div>
<button type="submit" class="btn btn-primary">Create</button>
</form>
ProductController.php
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'price' => 'required',
'amount' => 'required',
'image' => 'required|image'
]);
$image = $request->file('image');
$new_name = rand() . '.' . $image->getClientOriginalExtension();
$image->move(public_path('images'), $new_name);
Product::create([
'name' => $request->name,
'price' => $request->price,
'amount' => $request->amount,
'image' => $new_name
]);
return redirect()->route('products.index')->with('message', 'Product created successfully');
}
As you mention about works on local but not remote. I assumed that the upload_max_filesize is greater than the size your upload file, and both on local and remote are not the same.
You may use The Storage Facade as a convenient way to interact with your local filesystems.
use Illuminate\Support\Facades\Storage;
//...
$new_name = rand() . '.' . $image->getClientOriginalExtension();
Storage::disk('public')->putFileAs('images', request->file('image'), $new_name);
//...
Docs
You should try this
Try with adding mimetypes in validation of image.
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'price' => 'required',
'amount' => 'required',
'image' => 'required|mimes:jpeg,bmp,png'
]);
$image = $request->file('image');
$new_name = rand() . '.' . $image->getClientOriginalExtension();
$image->move(public_path('images'), $new_name);
Product::create([
'name' => $request->name,
'price' => $request->price,
'amount' => $request->amount,
'image' => $new_name
]);
return redirect()->route('products.index')->with('message', 'Product created successfully');
}
You Should Try code this,
you may change a part code :
$image->move(public_path('images'), $new_name);
to be code :
$image->move(public_path('images'.$new_name));
this is code, 100% work to me.

POST method is not supported for this route

First, I've checked other question topic, but couldn't find the solution.
when I try to post my form. I am getting this error.
The POST method is not supported for this route. Supported methods:
GET, HEAD.
Form:
<div class="card-body">
<form action="{{route('profile.update', ['id' => $id])}}" method="post">
#csrf
#put
<div class="form-group">
<label for="location">Location</label>
<input class="form-control" type="text" name="location" value="{{$info->location}}">
</div>
<div class="form-group">
<label for="about">About</label>
<textarea name="about" id="about" rows="10" cols="50" class="form-control">{{$info->about}}</textarea>
</div>
<div class="form-control">
<p class="text-center">
<button class="btn btn-primary btn-md" type="submit">Update Your Info</button>
</p>
</div>
</form>
</div>
Routes:
Route::group(["middleware" => "auth"], function(){
route::get("/profile/edit", [
"uses" => "ProfilesController#edit",
"as" => "profile.edit"
]);
route::get("/profile/{slug}", [
"uses" => "ProfilesController#index",
"as" => "profile"
]);
route::put("/profile/update/{id}", [
"uses" => "ProfilesController#update",
"as" => "profile.update"
]);
});
in controller:
public function update(Request $request, $id)
{
dd($request->all());
}
From your question, i can understand that you're trying to update a profile using POST method or may be PUT method earlier. Since, the resource you are editing is unique, you're not passing any parameters for the controller to find that single resource so as to update it.
therefore modify your your route like
route::put("/profile/update/{id}", [
"uses" => "ProfilesController#update",
"as" => "profile.update"
]);
And your form like
<form action="{{route('profile.update', ['id' => $id])}}" method="post">
#csrf
#method('put')
You'll need to pass the ID of the profile you want to update as parameter
then at the controller
public function update(Request $request, $id){
//edit the profile with id = $id
}
You have an error in your form definition
<form class="{{route('profile.update', ['id' => $id])}}" method="post">
should be
<form action="{{route('profile.update', ['id' => $id])}}" method="post">
Since you made a form for PUT request, you have to change
route::post("/profile/update/profile", [
"uses" => "ProfilesController#update",
"as" => "profile.update"
]);
to this
route::put("/profile/update/profile", [
"uses" => "ProfilesController#update",
"as" => "profile.update"
]);
Here is the correction in your provided example.
In form route('profile.update', ['id' => {here you have to place id of record which you want to update}]).
View File
$info->id])}}" method="post">
<div class="form-group">
<label for="location">Location</label>
<input class="form-control" type="text" name="location" value="{{$info->location}}">
</div>
<div class="form-group">
<label for="about">About</label>
<textarea name="about" id="about" rows="10" cols="50" class="form-control">{{$info->about}}</textarea>
</div>
<div class="form-control">
<p class="text-center">
<button class="btn btn-primary btn-md" type="submit">Update Your Info</button>
</p>
</div>
</form>
</div>
In Route
Route::group(["middleware" => "auth"], function(){
route::get("/profile/{slug}", [
"uses" => "ProfilesController#index",
"as" => "profile"
]);
route::get("/profile/edit/profile", [
"uses" => "ProfilesController#edit",
"as" => "profile.edit"
]);
route::post("/profile/update/profile/{id}", [
"uses" => "ProfilesController#update",
"as" => "profile.update"
]);
});
In Controller
public function update(Request $request, $id)
{
dd($id, $request->all());
}

Resources