i want to upload pdf FILE with laravel,,, in my controller :
public function store(Request $request)
{
$categories = Category::findOrFail($request->category_id);
$request->request->add(['code' => $categories->aliases]);
$request->validate([
'code' => 'string',
'pdf' => 'required',
'eur' => 'required|numeric',
'date' => 'required'
]);
`
enter code here`$rawInput = $request->except('image');
$priceInput = $request->only(['idr', 'usd', 'eur', 'date']);
$pdf = $request->file('pdf')->getClientOriginalName();
in my blade...
<div class="form-group row">
<label class="col-md-4 col-form-label text-md-right">PDF</label>
<div class="col-md-6">
<input type="file" name="pdf" class="form-control{{ $errors->has('pdf') ? ' is-invalid' : '' }}">
#if ($errors->has('pdf'))
<span class="invalid-feedback">
<strong>{{ $errors->first('pdf') }}</strong>
</span>
#endif
</div>
</div>
when i click upload,,, error like this
i am getting error undefined varibale $pdf.. $pdf variable i PUT and compact in
return view('inventory::raws.show', compact(['raw', 'pdf']));
..
whats wrong my code........
use
$pdf = $request->file('pdf')->getClientOriginalName();
Related
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.');
}
I want to store the image file with the id as a name .
So I tried the following code :
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'casting_photo' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if ($validator->passes()) {
$request->casting_photo->storeAs(public_path('castingimages'),$request->Casting()->id.'.'.$request->casting_photo->extension() );
$data = ['casting_photo' =>$request->casting_photo];
Casting::create($data);
return response()->json(["status" => "success", "message" => "Success! post created."]);
}
return response()->json(["status" => "failed", "message" => "Alert! post not created"]);
}
But it gives me the 500 (Internal Server Error)
EDIT
if ($validator->passes()) {
$input['casting_photo'] = $request->Casting()->id .'.'.$request->casting_photo->extension();
$request->casting_photo->storeAs(public_path('castingimages'),$request->Casting()->id.'.'.$request->casting_photo->extension() );
$data = ['casting_name' => $request->casting_name,
'casting_cin' => $request->casting_cin,
'casting_email' => $request->casting_email,
'casting_phone' => $request->casting_phone,
'casting_age' => $request->casting_age,
'casting_sexe' => $request->casting_sexe,
'casting_city' => $request->casting_city,
'casting_address' => $request->casting_address,
'casting_photo'=> $input['casting_photo'] ];
Casting::create($data);
return response()->json(["status" => "success", "message" => "Success! post created."]);
}
return response()->json(["status" => "failed", "message" => "Alert! post not created"]);
I tried that and the same error occurs.
EDIT2
$fileName = $request->get('id') . '.' . $request->file('casting_photo')->extension();
$request->file('casting_photo')->storeAs('castingimages', $fileName);
But in databse I finf the image stored with just the extension like .png
EDIT3
<form id="castingform" method="post" action="castings" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="hidden" name="id" />
<div class="form-group col-md-6">
<label for="casting_name">Nom</label>
<input type="text" class="form-control" id="casting_name" name="casting_name" placeholder="Nom" >
<span class="text-danger">{{ $errors->first('casting_name') }}</span>
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">Upload</span>
</div>
<div class="custom-file">
<input type="file" name="casting_photo" class="custom-file-input" id="casting_photo">
<div class="input-group-prepend">
<span class="text-danger">{{ $errors->first('casting_photo') }}</span>
</div>
<label class="custom-file-label" for="casting_photo">Choose file</label>
</div>
</div>
<button type="submit" id="createBtn" class="btn btn-success">Sign in</button>
</form>
You are accessing unknown id from request
$input['casting_photo'] = $request->Casting()->id .'.'.$request->casting_photo->extension();
it should be
$request->casting_photo->storeAs(public_path('castingimages'),$request->id.'.'.$request->casting_photo->extension() );
Updated
$request->casting_photo->storeAs(public_path('castingimages'),$request->Casting()->id.'.'.$request->casting_photo->extension() );
$data = ['casting_name' => $request->casting_name,
'casting_cin' => $request->casting_cin,
'casting_email' => $request->casting_email,
'casting_phone' => $request->casting_phone,
'casting_age' => $request->casting_age,
'casting_sexe' => $request->casting_sexe,
'casting_city' => $request->casting_city,
'casting_address' => $request->casting_address,
$casting=Casting::create($data);
$casting->casting_photo=$casting->id.'.'.$request->casting_photo->extension() );
$casting->save();
there is no problem when I do create new data. everything is ok including uploading image. My image inserted to public/image directory.
But when i try editing or updating, i have a problem. my image that should be inserted to public/image not work on update function.
the controller is below
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'sequence' => 'required',
'image' => 'required|image|max:2048',
'link' => 'required',
'status' => 'required',
]);
$image = $request->file('image');
$new_name = $request->name .rand(). '.' . $image->getClientOriginalExtension();
$image->move(public_path('images'), $new_name);
$form_data = array(
'name' => $request->name,
'sequence' => $request->sequence,
'image' => $new_name,
'link' => $request->link,
'status' => $request->status,
);
Banner::create($form_data);
return redirect()->route('banner.index');
}
public function update(Request $request, Banner $banner)
{
$image_name = $request->hidden_image;
$image = $request->file('image');
if($image != ''){
$request->validate([
'name' => 'required',
'sequence' => 'required',
'image' => 'image|max:2048',
'link' => 'required',
'status' => 'required',
]);
$image_name = $request->name .rand(). '.' . $image->getClientOriginalExtension();
$image->move(public_path('images'), $image_name);
}
else{
$request->validate([
'name' => 'required',
'sequence' => 'required',
'link' => 'required',
'status' => 'required',
]);
}
$form_data = array(
'name' => $request->name,
'sequence' => $request->sequence,
'image' => $image_name,
'link' => $request->link,
'status' => $request->status,
);
Banner::whereId($banner)->update($form_data);
return redirect()->route('banner.index');
}
And my view code is below
<form action="{{ route('banner.update',$banner->id) }}" method="POST">
#csrf
#method('PUT')
<div class="row" style="margin-top: 10px">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Name:</strong>
<input type="text" name="name" value="{{ $banner->name }}" class="form-control" placeholder="Name">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Sequence</strong>
<input type="number" name="sequence" value="{{ $banner->sequence }}" class="form-control" placeholder="Sequence">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Image</strong>
<div class="col-md-8">
<img src="{{ URL::to('/') }}/images/{{ $banner->image }}" class="img-thumbnail" width="200" />
</div>
<div class="col-md-8">
<input type="file" name="image" />
<input type="text" name="hidden_image" value="{{ $banner->image }}" />
</div>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Link</strong>
<input type="text" name="link" value="{{ $banner->link }}" class="form-control" placeholder="Link">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Status</strong>
<input type="text" name="status" value="{{ $banner->status }}" class="form-control" placeholder="Status">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
your form is missing enctype attribute and so no file is passing with the form. add that attribute and everything will work.
<form action="{{ route('banner.update',$banner->id) }}" method="POST" enctype="multipart/form-data">
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.
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.