Laravel 5.1 File Upload isValid() on string? - php

So I am making a function for file uploading in my project.
however, when I try it I get this error : Call to a member function isValid() on string
My code for the upload function :
public function upload(Request $request){
$file = array('profielfoto' => $request->input('profielfoto'));
$rules = array('profielfoto' => 'required',);
$validator = Validator::make($file,$rules);
if($validator->fails()){
return redirect('/profiel')->withInput()->withErrors($validator);
}
else{
if($request->input('profielfoto')->isValid()){ //<- gives error
$destinationPath = 'assets/uploads';
$extension = $request->input('profielfoto')->getClientOriginalExtension();
$fileName = rand(1111,9999).'.'.$extension;
$request->input('profielfoto')->move($destinationPath,$fileName);
Session::flash('alert-success', 'Foto uploaden gelukt');
return redirect('/profiel');
}
else{
Session::flash('alert-danger', 'Foto uploaden mislukt');
return redirect('/profiel');
}
}
}
The form in the blade view on the 4th line from down below is the location for the input!
<form method="POST" action="/profiel/upload" files="true">
{!! csrf_field() !!}
<input type="hidden" name="_method" value="PUT">
<input type="hidden" class="form-control id2" id="id2" name="id" value="{{$user->id}}">
<img src="assets/images/avatar.png" alt="gfxuser" class="img-circle center-block">
<div class="form-group center-block">
<label class="center-block text-center" for="fotoinput">Kies uw foto</label>
<input class="center-block" type="file" name="profielfoto" id="profielfoto">
</div>
<button type="submit" class="btn btn-success"><span class="fa fa-check" aria-hidden="true"></span> Verander foto</button>
</form>

You must ask isValid() to a file, not to the name of the file. That's why you get the error. You can get the file through $request->file() or through Input::file() :
else{
if( $request->file('profielfoto')->isValid()){ //<- gives error
Also your form should include the correct enctype to send files:
<form enctype="multipart/form-data">

I think you should use as this.
$file = $request -> file('Filedata');
if (!$file -> isValid()) {
echo Protocol::ajaxModel('JSEND_ERROR', 'not an valid file.');
return;
}
Add attribute on
enctype="multipart/form-data"

Related

move_uploaded_file is not fetching path in laravel

Here is my controller
public function createAdmin()
{
$photo=$_FILES['bannerPic']['name'];
$tempname=$_FILES['bannerPic']['tmp_name'];
// echo $tempname." ".$photo;
move_uploaded_file($tempname, 'picture/banner/'.$photo);
$data=[
'sliderPic' => $photo,
];
dd($data);
// \App\Models\Banner::create($data);
// return view('Banner');
}
here is my route
Route::post('/BannerEdit', [App\Http\Controllers\BannerController::class,
'createAdmin']);
here is my blade form
<form action="{{ url('') }}/BannerEdit" method="post" class="col-12"
enctype="multipart/form-data">
#csrf
<div class="mb-3 col-12">
<label class="col-4 text-label form-label">Banner Photo*</label>
<input type="file" name="bannerPic" class="form-control input-rounded col-4 mb-3"
required>
</div>
<div class="mb-3 text-end">
<input type="submit" class="btn btn-primary" value="Upload">
</div>
</form>
When i submit the data it Gives me an Error as
move_uploaded_file(picture/banner/favicon.jpg): Failed to open stream: No such file or directory
But this Directory Exists
And i checked with full pathof localhost then it does not supports http path
You need to use getcwd() function like this:
$dirpath = realpath(dirname(getcwd()));
So your controller code will be:
public function createAdmin()
{
$photo=$_FILES['bannerPic']['name'];
$tempname=$_FILES['bannerPic']['tmp_name'];
// echo $tempname." ".$photo;
$dirpath = realpath(dirname(getcwd()));
move_uploaded_file($tempname, $dirpath.'/'.$photo);
$data=[
'sliderPic' => $photo,
];
dd($data);
// \App\Models\Banner::create($data);
// return view('Banner');
}
let me know if it works.. if not then we'll modify $dirpath variable
PS: this solution will work on server. are you working on server or in localhost?
EDIT:
Other solution is to use below function to get proper directory structure:
$dirpath = public_path('picture/banner/');

Laravel 8, how to upload more than one image at a time

I want to upload more than one image at a time through an in Laravel 8 to my SQL database, and I am not able to do it. I have managed to upload only one, but when I try with more I get failure.
My Database
Imagenes
id
nombre
id_coche
01
name.jpg
0004
...
...
...
My Code
Blade with the Form
#foreach ($Vehiculo as $obj) /*this is to take the Car ID*/
<form method="POST" action="{{ route('añadirImagen')}}" enctype="multipart/form-data" >
#csrf
<div class="form-row">
<div class="form-group col-md-3">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">ID</span>
</div>
<input type="text" class="form-control" name="id_coche" value="{{$obj->id}}" style="background: white" required readonly>
</div>
</div>
<div class="col-md-6">
<input type="file" class="form-control" name="imagen" required multiple/>
</div>
<div class="form-group col-md-3">
<button type="submit" class="btn btn-success">AÑADIR IMAGENES</button>
</div>
</div>
</form>
#endforeach
Controller
"To upload only one image"
public function añadirImagen(Request $request){
$validated = $request->validate([
'id_coche' => 'required',
'nombre.*' => 'mimes:image'
]);
$data = $request->input();
$id_coche = $data['id_coche'];
$Imagenes= new Imagenes;
$Imagenes->id_coche = $id_coche;
if($request->file("imagen")!=null){
$nombre = $request->file('imagen');
$nombreFoto = $nombre->getClientOriginalName();
$nombre->move('img/Coches/', $nombreFoto);
$Imagenes->nombre = $nombreFoto;
}
$Imagenes->save();
return redirect()->back()->with('error','Se han añadido las imagenes correctamente.');
}
}
"My attempt to upload more than one"
public function añadirImagen(Request $request){
$validated = $request->validate([
'id_coche' => 'required',
'imagen.*' => 'mimes:image'
]);
$data = $request->input();
$id_coche = $data['id_coche'];
$Imagenes= new Imagenes;
$Imagenes->id_coche = $id_coche;
if($request->hasfile("imagen")){
$nombre_img = $request->file('imagen');
foreach($nombre_img as $nombre) {
$nombreFoto = $nombre->getClientOriginalName();
$nombre->move('img/Coches/', $nombreFoto);
$Imagenes->nombre = $nombreFoto;
}
}
$Imagenes->save();
When doing this, it adds in the database a single row, with the correct id_coche, the Auto_Increment does well the ID, but the name remains NULL.
Thank You.
You currently have:
<input type="file" class="form-control" name="imagen" required multiple/>
and it needs to be:
<input type="file" class="form-control" name="imagen[]" required/>
multiple attribute is not required.
Then you can do in your controller:
if($request->hasfile('imagen')) {
foreach($request->file('imagen') as $file)
{
...
}
}

File not uploading

I was working on a project and was trying to develop a file uploading system for skins.
When I tried to upload my skin, I was given "Call to a member function storeAs() on null"
public function uploadSkin(Request $request)
{
/* $request->validate([
'skins' => 'required|mimes:png|max:1024',
]); */
$storage_dir = storage_path('app/skins');
$request->file('skins')->storeAs($storage_dir, Auth::user->name . '.png');
return route('settings')->with('success', 'skin uploaded :)');
}
Form code:
<form method="post" enctype="multipart/form-data" action="/settings">
#csrf
<br/>
<div class="form-group">
<input type="file" class="form-control-file" id="skins" name="skins" required>
</div>
<button type="submit" class="btn btn-success">Upload</button>
</form>
To store a file like an image or any kind of files you can use a code like this:
public function uploadSkin(Request $request){
$image = $request->file('skins');
if ($image != null) {
$image->move('uploads/skins/', Auth::user()->name . $image->getClientOriginalExtension());
}
return route('settings')->with('success', 'skin uploaded :)');
}
To uppload a file there are various ways in the laravel but for now you can try this to simply move your file to your directory:
if($files= $request->file('skins')){
$files->move('uploads/skins/', Auth::user->name . '.png');
}

When saving, how to fix "set" method to update an entry. after add form validation on controllers

after add form validation in my controllers
public function save($id_kecamatan='')
{
$this->form_validation->set_rules('nama_kecamatan','nama_kecamatan', 'required');
if ($this->form_validation->run() != FALSE){
$data = [
'nama_kecamatan' => $this->input->post('nama_kecamatan')
];
}
$simpan = $this->KecamatanModel->saveKecamatan($data);
redirect('admin/kecamatan/add');
}
this is my model, on the line $this->db->insert
public function saveKecamatan($data)
{
$this->db->insert('tbl_kecamatan', $data);
$id_kecamatan = $this->db->insert_id();
return true;
}
my view, when submit, appear You must use the "set" method to update an entry.
<?= validation_errors(); ?>
<form action="<?= site_url('admin/kecamatan/save');?>" method="POST">
<div class="box-body">
<div class="form-group">
<label class="control-label">Kecamatan</label>
<input type="text" class="form-control" name="nama_kecamatan" id="" placeholder="Nama Kecamatan">
</div>
<div class="form-actions">
<input type="hidden" name="id_kecamatan" value="">
<button type="submit" class="btn btn-success"><i class="fa fa-check"></i> Simpan</button>
<i class="fa fa-undo"></i> Batal
</div>
</form>
The validation is useless because it will not prevent empty value to be passed to
$this->db->insert('tbl_kecamatan', $data).
Try to prevent empty value by moving $simpan variable one line up :
public function save($id_kecamatan='')
{
$this->form_validation->set_rules('nama_kecamatan','nama_kecamatan', 'required');
if ($this->form_validation->run() != FALSE){
$data = [
'nama_kecamatan' => $this->input->post('nama_kecamatan')
];
$simpan = $this->KecamatanModel->saveKecamatan($data);
}
redirect('admin/kecamatan/add');
}

Unable to submit binary image into database in laravel

I am trying to submit an image into the database but I keep getting this error: Type error: Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() must be an instance of Illuminate\Database\Eloquent\Model, null given, called in C:\xampp\htdocs\Evaluation\app\Http\Controllers\ImageController.php on line 24.
I checked with other questions in StackOverflow and mostly they said it was the fault of the saving part where they put something like this, $post but I have checked and there is nothing wrong with it. The relationship doesn't seem to have any problem as well but why is it still not working? The error also return me a null when I upload image. The null is returning at the part here, $UserImage = $request->input('UserImage'); So could my problem be in image1.blade.php?
ImageController:
public function test(personal_info $user){
return view('image1',compact('user'));
}
public function test1(Request $request){
$UserImage = new Image;
$personal_info = new personal_info;
$UserImage = $request->input('UserImage');
$id = $request->user_id;
$id = personal_info::find($id);
$id->Images()->save($UserImage);
return redirect('/summary');
}
image1.blade.php (where i submit the form)
<form class="form-horizontal" method="post" action="{{ url('/Upload')}}" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="hidden" name="user_id" value="{{$user->id}}">
<div class="form-group">
<label for="imageInput" class="control-label col-sm-3">Upload Image</label>
<div class="col-sm-9">
<input type="file" name="UserImage">
</div>
</div>
<div class="form-group">
<div class="col-md-6-offset-2" style="padding-left: 30px">
<input type="submit" class="btn btn-primary" value="Save">
</div>
</div>
</form>
Image.php:
public function personal_infos() {
return $this->belongsTo('App\personal_info', 'user_id', 'id');
}
personal_info.php:
public function Images() {
return $this->hasOne('App\Image','user_id');
}
public function test1(Request $request)
{
// make new instance of Image Model
$imageModel = new Image;
// find personal_info Model by id
$personal_info = personal_info::findOrFail($request->input('user_id'));
// UploadedFile
$image = $request->file('UserImage');
// get the file contents?
$imageModel->content = ...
// save the relationships, pass a model instance to `save`
$personal_info->Images()->save($imageModel);
return redirect('/summary');
}

Categories