Laravel errors while storing a file - php

I am working on a laravel crud project. Now i want to store files like .xlsx and .docx
But i keep getting errors in my controller and browser:
Controller:
public function store(Request $request)
{
$request->validate([
'title'=>'required',
'description_short'=>'',
'description_long'=>'',
'file'=>'',
'language_id'=> [
'required', 'exists:language,id'
],
]);
$fileName = $request->file->getClientOriginalName();
$filePath = 'files/' . $fileName;
$path = Storage::disk('public')->put($filePath, file_get_contents($request->file));
$path = Storage::disk('public')->url($path);
$file = new File([
'title'=> $request->get('title'),
'description_short'=> $request->get('description_short'),
'description_long'=> $request->get('description_long'),
'file'=>$request->get('file'),
'language_id'=> $request->language_id,
]);
$file->save();
return back();
}
Here i get the error: Undefined method 'url'
Create page:
<form method="post" action="{{ route('admin.language.store') }}" enctype="multipart/form-data">
#csrf
<div class="form-group">
<label for="title">{{('name')}}</label>
<input type="text" class="form-control" name="name"/>
</div>
<div class="form-group">
<label for="value">{{('file')}}</label>
<input type="file" class="form-control" name="file"/>
</div>
<button type="submit" class="btn btn-primary">Add language</button>
</form>
the browser error i get is : Call to a member function getClientOriginalName() on string.
if i need to provide more information i will gladly do so!

file is reserved keyword in Request class to get submitted Files in post method.
You can not use file in input. So first you have to change file name in input box.
After that you can do like below.
$request->file('file_input_name')->getClientOriginalName();

$file = $request->file->getClientOriginalName();
fixed it

Related

How to upload an array of images with Laravel properly

I have a form like this:
<form action="{{ route('popups.store') }}" method="POST" enctype="multipart/form-data">
#csrf
<div id="dynamic_field">
<label>Date of showing</label>
<input type="text" id="date" name="datep" class="form-control datepicker" value="" autofocus>
<label for="title" class="control-label">Title</label>
<input type="text" id="title" name="title" class="form-control" value="" autofocus>
<label for="link" class="control-label">Link</label>
<input type="text" id="link" name="linkp[]" class="form-control" value="" autofocus>
<label for="bio" class="control-label">Text</label>
<textarea class="form-control" name="bio[]" rows="3"></textarea>
<label for="filep" class="control-label">Image</label>
<input type="file" class="form-control-file" id="filep" name="filep[]">
<button class="btn btn-success" type="submit">Submit</button>
<a id="add" class="btn btn-info" style="color:white">Add new form</a>
</div>
</form>
As you can see, I have added a link with id="add" for adding additional form fields dynamically with javascript.
So it means a user can add several images, texts and links. And that's why I used filep[], bio[] and linkp[], as the name of those form fields (in order to save them as an array).
Then at the Controller, I added this:
public function store(Request $request)
{
try{
$data = $request->validate([
'datep' => 'nullable',
'title' => 'nullable',
'linkp' => 'nullable',
'bio' => 'nullable',
'filep' => 'nullable',
]);
$newPop = Popup::create([
'datep' => $data['datep'],
'title' => $data['title']
]);
$files = $request->file('filep');
if($request->hasFile('filep'))
{
foreach ($files as $file) {
$newImageName = time() . '-' . $request->name . '.' . $request->filep->extension();
$request->filep->move(public_path('popups'), $newImageName);
Popup::where('id',$newPop->id)->update(['image_path'=>",".$newImageName]);
}
}
}catch (\Exception $e) {
dd($e);
}
return redirect()->back();
}
So for each image, I tried moving it into public/popups folder and then it should update the existing record of table with id of $newPop->id.
But it shows me this error:
Call to a member function extension() on array
Which is referring to this line:
$newImageName = time() . '-' . $request->name . '.' . $request->filep->extension();
So what's going wrong here? How can I upload multiple images with using array?
You can try this -
if($files=$request->file('filep')){
foreach ($files as $key=>$file) {
$extension = $file->getClientOriginalName();
$fileName = time().'-' .$request->name.'.'.$extension; // I don't know where did you get this $request->name, I didn't find it on your code.
$created = Popup::create([
'datep' => $request->datep[$key],
'title' => $request->title[$key],
'image_path' => $fileName
]);
if($created){
// $file->move('popups',$fileName); to store in public folder
// If you want to keep files in storage folder, you can use following : -
Storage::disk('public')->put('popups/'.$location,File::get($file));
// Dont't forget to run 'php artisan storage:link'
// It will store into your storage folder and you can access it by Storage::url('file_path)
}else{
// Your error message.
}
}
}

Get the actual file name and extention from image file in laravel

When I am uploading an image to the form and returning it from the controller, the image name and extention are changing.I am a beggar, so if I make a mistake while asking a question, I would like to apologize.
This is my form:
<form action="{{ route('admin.slider.store') }}" method="POST" enctype="multipart/form-data">
#csrf
<div class="row">
<div class="col-md-12">
<label class="control-label">Image</label>
<input type="file" name="image">
</div>
</div
<button type="submit" class="btn btn-success">Save</button>
</form>
This is my controller:
public function store(Request $request)
{
$this->validate($request, [
'image' => 'required|mimes:jpeg,bmp,png,jpg',
]);
$image = $request->file('image');
return $image;
}
My image file name is :demo.jpg
Controller return result is like that:
C:\xampp\tmp\php5E86.tmp
This is the same result when I give another picture, only the last four characters are changing.
C:\xampp\tmp\phpF239.tmp
It is very helpful to know why I am getting .tmp file return.
use getClientOriginalName to get orginal file name
$request->image->getClientOriginalName()
To get file extension
$request->image->extension();
or
$name = $request->file('image')->getClientOriginalName();
$extension = $request->file('image')->extension();
Ref:https://laravel.com/docs/8.x/filesystem#other-uploaded-file-information

How to Solve Error: Call to a member function move() on string

I am uploading an image to a folder and saving data to the database. How can I solve this error? The error is in the following line...
$property_features_image->move($destinationPath,$property_features_image);
public function store(Request $request)
{
$this->validate($request, [
'property_feature' => 'required|unique:property_features,property_features_name',
'property_icon' => 'required|image|mimes:jpg,png,jpeg|max:10240',
]);
$property_features_name = $request->property_feature;
$property_features_image = $request->file('property_icon');
$property_features_image = $property_features_image->getClientOriginalExtension();
$destinationPath = public_path('/images');
$property_features_image->move($destinationPath, $property_features_image);
DB::table('property_features')->insert([
'property_features_name' => $property_features_name,
'property_features_image' => $property_features_image,
]);
}
Blade
<form method="post" enctype="multipart/form-data" action="{{url('/admin/property-features')}}">
<div class="form-group">
<input type="hidden" value="{{csrf_token()}}" name="_token"/>
<label for="Property">Add Property Feature</label>
<input type="text" class="form-control" id="property_feature" name="property_feature"
placeholder="Enter Property Feature">
<label for="exampleFormControlFile1">Property Features's Icon</label>
<input type="file" class="form-control-file" id="property_icon" name="property_icon">
<?php echo($errors->first('property_feature', "<li class='ab' style='color:red;'>:message</li>"));?>
<?php echo($errors->first('property_icon', "<li class='ab' style='color:red;'>:message</li>"));?>
</div>
</form>
This line:
$property_features_image = $property_features_image->getClientOriginalExtension();
Assigns $property_features_image variable to a string value.
And strings cannot have any methods (you are trying to call move() method).
So removing the line should help, but then you must ensure everything else is ok. The getClientOriginalExtension() might be required somewhere, but we don't see all the code.

Unable to upload an image in Laravel 5.4

Using Laravel 5.4, I'm tring to setup a form where a user can enter a food name and its image. While trying to upload a PNG or JPG image, I get the following Validation Error:
The image must be an image.
If I remove the validation for image, I get a FatalErrorException:
Call to a member function getClientOriginalExtension() on null
which is a helper function provided by Intervention/Image library. This could mean that the image didn't upload at all.
FORM
<form action="/hq/foods" method="POST">
{{ csrf_field() }}
<input type="text" name="name">
<input type="file" name="image">
<button type="submit" class="btn btn-success ">
ADD FOOD ITEM
</button>
</form>
CONTROLLER
public function store(Request $request) {
$this->validate($request, [
'name' => 'required|min:2|max:255',
'image' => 'required|image'
]);
$food_category = FoodCategory::find($request->food_category_id);
$food = new Food;
$food->name = $request->name;
$image = $request->file('image');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('img/foods/' . $filename);
Image::make($image)->resize(800, 400)->save($location);
$food->image = $filename;
$food->save();
Session::flash('success',
'
<h4>Success!</h4>
<p>The food item has been added to the Menu.</p>
');
return back();
}
What am I missing?
To upload images you need to add:
enctype="multipart/form-data"
to your form so instead of:
<form action="/hq/foods" method="POST">
you should use
<form action="/hq/foods" method="POST" enctype="multipart/form-data">
If you use Laravelcollective
{!! Form::open(['method'=>'post','files' => true,'url'=>'/hq/foods']) !!}
OR
Using HTML
<form action="/hq/foods" method="POST" enctype="multipart/form-data">
you need to add enctype="multipart/form-data" in your from

FileNotFoundException in laravel

In laravel i am making an application that uploads a file and the user can download that same file.
But each time i click to upload i get this error.
FileNotFoundException in File.php line 37: The file
"H:\wamp64\tmp\phpF040.tmp" does not exist
my view code is this:
#extends('layouts.app')
#section('content')
#inject('Kala','App\Kala')
<div class="container">
<div class="row">
#include('common.errors')
<form action="/addkala" method="post" enctype="multipart/form-data">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="text" name="name">
<input type="text" name="details">
<input type="file" name="photo" id="photo" >
<button type="submit">submit</button>
</form>
</div>
</div>
#endsection
and my controller
public function addkalapost(Request $request)
{
$rules = [
'name' => 'required|max:255',
'details' => 'required',
'photo' => 'max:1024',
];
$v = Validator::make($request->all(), $rules);
if($v->fails()){
return redirect()->back()->withErrors($v->errors())->withInput($request->except('photo'));
} else {
$file = $request->file('photo');
$fileName = time().'_'.$request->name;
$destinationPath = public_path().'/uploads';
$file->move($destinationPath, $fileName);
$kala=new Kala;
$kala->name=$request->name;
return 1;
$kala->details=$request->details;
$kala->pic_name=$fileName;
$kala->save();
return redirect()->back()->with('message', 'The post successfully inserted.');
}
}
and i change the upload max size in php.ini to 1000M.
plz help
im confusing
I'll recommend you using filesystems for that by default the folder is storage/app you need to get file from there
if your file is located somewhere else you can make your own disk in config/filesystems e.g. 'myDisk' => [
'driver' => 'local',
'root' =>base_path('xyzFolder'),
],
and you can call it like
use Illuminate\Support\Facades\Storage;
$data = Storage::disk('myDisk')->get('myFile.txt');
this is obviously to get file and you can perform any other function by following laravel docs.

Categories