Files input missing from Request Laravel - php

I am using laravel to make form upload, it worked well before. But, now it doesn't work.
I've tried to debug my code using dd($request->all(), but my photo file was missing.
This is my view code
<form action="" method="post" class="form-horizontal form-bordered" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group">
<label class="col-xs-2 col-md-1 control-label" style="text-align: left;position: relative;right: -8px;">
<div class="row">
<span class="fa fa-file-image-o" aria-hidden="true" style="position: relative;font-size: 20px;top: 0px;text-align: left;color: #ADADAD;"></span>
</div>
</label>
<div class="col-xs-10 col-md-11">
<input name="photo" value="" class="form-control" style="padding-top: 5px;height: auto;" type="file">
</div>
</div>
</form>
and this is the controller code
public function store(Request $request)
{
...
dump($request->all());
if ($request->hasFile('photo')) {
$file = $request->file('photo');
$timestamp = 21;
$name = $timestamp. '-' .$file->getClientOriginalName();
$Members->photo = $name;
$n = Image::make(Input::file('photo'));
$n->resize(330, 330);
$path = 'uploads/'.$name;
$n->save($path);
}
}
PS. I was modified php.ini file before, does it matter?

Related

Cannot store file in my storage - laravel

i'm trying to upload some files via form to my db and also in the storage of my project
I did the following code on my homepage :
<x-layout>
#if (session('message'))
<div class="alert alert-success">{{session('message')}}</div>
#endif
<div class="container vh-100">
<div class="row h-100 w-100 align-items-center">
<div class="offset-3 col-6">
<form method="POST" action="{{route('transfer.submit')}}" class="card" enctype="multipart/form-data">
#csrf
<div class="border w-100" id="fileWrapper">
<div class="mb-3 w-100 h-100">
<input type="file" class="form-control w-100 h-100 fileInput" id="fileupload" name="files[]" multiple >
</div>
</div>
<div class="mb-3">
<label for="exampleInputPassword1" class="form-label">Invia file a </label>
<input type="email" class="form-control" id="exampleInputPassword1" name="recipient_mail">
</div>
<div class="mb-3">
<label for="exampleInputPassword1" class="form-label">La tua mail</label>
<input type="email" class="form-control" id="exampleInputPassword1" name="sender_mail">
</div>
<div class="mb-3">
<input type="text" class="form-control" id="title" name="title">
</div>
<div class="mb-3">
<textarea name="message" cols="50" rows="10"></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</x-layout>
Then i done the following in my model :
protected $fillable = [
'recipient_mail',
'sender_mail',
'title',
'message',
'files[]'
];
and the following in my controller :
public function transferSubmit(TransferRequest $request){
$transfer = Transfer::create([
'sender_mail'=>$request->input('sender_mail'),
'recipient_mail'=>$request->input('recipient_mail'),
'title'=>$request->input('title'),
'message'=>$request->input('message'),
'files'=>$request->file('files[]')->store('public/files'),
]);
return redirect(route('home'))->with('message', 'File inviato con successo');
}
I havo also created the POST route and completed the migrations but, when i try to submit the form i get the following error :
Error Call to a member function store() on null
After this i tried the dd($request) ro check the data that i was actually passing to the Trasnfer class and i found that it is receiving correctly every data including the array of files.
Is there anybody that can help me to understand why i'm getting that error?
Thank you so much
You want store multiple files. And you will get an array. Then you have to iteratrate over your file array like that.
$files = [];
if($request->hasfile('files[]'))
{
foreach($request->file('files[]') as $file)
{
$files => $file->store('public/files'),
}
}
Important Note:
And don't forget the symlink before working with the Laravel storage.
php artisan storage:link
Updated
You iterate first then you have the file array which contains the paths to the images. you can then pass that to your model.
A little note: data coming from a form should always be validated.
public function transferSubmit(TransferRequest $request){
$files = [];
if($request->hasfile('files[]'))
{
foreach($request->file('files[]') as $file)
{
$files => $file->store('public/files'),
}
}
$transfer = Transfer::create([
'sender_mail'=>$request->input('sender_mail'),
'recipient_mail'=>$request->input('recipient_mail'),
'title'=>$request->input('title'),
'message'=>$request->input('message'),
'files'=> $files;
return redirect(route('home'))->with('message', 'File inviato con successo');
}

How I upload an image on laravel 6?

im trying to edit an image on laravel 6, but but it does not advance to next view, stays on the form view.
I have seen many tutorials of laravel 5.8 and 6. I can't make it work in any way
This is de controller:
public function update(Request $request, $id)
{
$validator = $request->validate([
'titulo' => 'required | max:50', //campo obligatorio y máximo 50 caracteres
'contenido' => 'required | max:150',
'imagen' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:4096',
]);
$image_name = time().'.'.$request->imagen->getClientOriginalExtension();
$request->image->move(public_path('images'), $image_name);
$datos = array(
'titulo' => $request->titulo,
'contenido' => $request->contenido,
'imagen' => $image_name,
);
Noticia::whereId($id)->update($datos);
return redirect('/mostrar');
}
THis is Web.php file:
Route::get('/actualizar/{id}', 'crearNoticiaController#update')->name('actualizar');
Route::get('/editar/{id}', 'crearNoticiaController#edit')->name('editar');
this is form file:
<div class="subir-imagen">
<form method="get" action="{{ route('actualizar', $noticia->id) }}" enctype="multipart/form-data">
#csrf
<div class="crear-titulo">
<input class="titulo" type="text" name="titulo" placeholder="Escriba el titulo" value="{{$noticia->titulo}}">
</div>
<div class="crear-contenido">
<textarea class="ckeditor" name="contenido" placeholder="Escriba el contenido" >
{{$noticia->contenido}}
</textarea>
</div>
<table border="2">
<tr>
<td><img src="{{URL::to('/')}}/images/{{$noticia->imagen}}" alt="imagen" width="250" align="left"/></td>
</tr>
</table>
<div class="form-group">
<div class="col-md-6">
<input type="file" class="form-control" name="imagen" />
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<input type="submit" class="btn btn-primary" value="Enviar" id="btn-enviar" />
</div>
</div>
</form>
</div>
Thnaks for help
I faced same issue, but luckily i solved this problem.I added my solution below, i think this will help you to solve this problem
public function updatePost(Request $request, $id)
{
$validatedData = $request->validate([
'title' => 'required|unique:posts|max:25|min:4',
'image' => 'mimes:jpeg,jpg,png,JPEG,JPG,PNG | max:100000',
]);
$data = array();
$data['category_id'] = $request->category_id;
$data['title'] = $request->title;
$data['details'] = $request->details;
$image = $request->file('image');
if($image)
{
$image_name = hexdec(uniqid());
$ext = strtolower($image->getClientOriginalExtension());
$image_full_name = $image_name.'.'.$ext;
$upload_path = 'public/assets/img/';
$image_url = $upload_path.$image_full_name;
$success = $image->move($upload_path,$image_full_name);
$data['image'] = $image_url;
unlink($request->old_photo);
$posts = DB::table('posts')->where('posts.id', $id)->update($data);
if($posts)
{
return Redirect()->route('all.posts')->with('success','Posts are inserted successfully');
}
else
{
return back()->with('error', 'Posts are not inserted successfully');
}
}
else
{
$data['image'] = $request->old_photo;
$posts = DB::table('posts')->where('posts.id', $id)->update($data);
if($posts)
{
return Redirect()->route('all.posts')->with('success','Posts are inserted successfully');
}
else
{
return back()->with('error', 'Posts are not inserted successfully');
}
}
}
edit_post.blade.php
#extends('welcome')
#section('content')
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
<p>
List Posts
</p>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="{{ url('posts.update_posts/'.$posts->id) }}" method="post" enctype="multipart/form-data">
#csrf
<div class="control-group">
<div class="form-group floating-label-form-group controls">
<div>Category Name</div>
<label>Category ID</label>
<select class="form-control" name="category_id">
#foreach($category as $categories)
<option value="{{ $categories->id }}" <?php if ($categories->id == $posts->category_id)
echo "selected"; ?> > {{ $categories->name }} </option>
#endforeach
</select>
<p class="help-block text-danger"></p>
</div>
</div>
<div class="control-group">
<div class="form-group floating-label-form-group controls">
<label>Product Title</label>
<input type="text" name="title" class="form-control" value="{{ $posts->title }}" id="title" required data-validation-required-message="Please product name.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="control-group">
<div class="form-group floating-label-form-group controls">
<label>Details</label>
<textarea name="details" rows="5" class="form-control" value="{{ $posts->details }}" id="details"></textarea>
<p class="help-block text-danger"></p>
</div>
</div>
<div class="control-group">
<div class="form-group floating-label-form-group controls">
<label>Product Image</label>
<input type="file" name="image" class="form-control" id="image"><br/>
Old Image : <img src="{{ URL::to($posts->image) }}" style="hight: 40px; width: 100px">
<input type="hidden" name="old_photo" value="{{ $posts->image }}">
</div>
</div>
<br>
<div id="success"></div>
<div class="form-group">
<button type="submit" class="btn btn-success" id="sendMessageButton">Update</button>
</div>
</form>
</div>
</div>
</div>
#endsection
First run on your project console command:
php artisan storage:link
Then try this code and if return any error message tell me khow:
$imagen = $request->file("imagen");
$extension = $imagen->extension();
$filename = time().".".$extension;
$request->file('imagen')->storeAs("public/images", $filename);
Finally check your public/images folder for image file exists.
Also you can read about storing uploaded files in laravel 6.x official documentation
I've solved with this way:
In web.php I put patch instead get
Route::patch('/actualizar/{id}', 'crearNoticiaController#update')->name('actualizar');
In the edit blade I put: #method('PATCH')
And this is the update in the controller:
public function update(Request $request, $id)
{
$noticia = Noticia::findOrFail($id);
$noticia->titulo = $request->get('titulo');
$noticia->contenido = $request->get('contenido');
$noticia->imagen = $request->file('imagen');
$validator = $request->validate([
'imagen' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:4096',
]);
$imageName = time().'.'.request()->imagen->getClientOriginalExtension();
request()->imagen->move(public_path('images'), $imageName);
$noticia->imagen = $imageName;
$noticia->update();
return redirect('/mostrar'); //Redirigimos a la la vista para mostrar las noticias
}

Input type "file" returns EMPTY in Laravel php

I have this problem getting my string to an input type file, I'd try changing the input type to text, and when I return $request it works (just with type text, with file type it returns empty).
I'd put enctype="multipart/form-data" but that still empty value for file input.
web.php
Route::get('/profile', 'miPerfilController#index')->name('profile');
Route::post('/profile/update', 'miPerfilController#updatePhoto')->name('profile.update');
updatePhoto.blade.php
<form class="form-group" method="POST" action="/profile/update" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="modal fade row" id="updatePhoto">
<div class="modal-dialog modal-md">
<div class="modal-content">
<div class="card-body">
<div class="mb-5 form-group" >
<h3 class="pull-left">Update profile image</h3>
<button type="button" class="close pull-right" data-dismiss="modal">
<span>
×
</span>
</button>
</div>
<label v-for="error in errors" class="text-danger">#{{ error }}</label>
<div class="form-group">
<label for="name">Choose image<span class="help"></span></label>
<br><br>
<input type="file" name="profile_image" id="profile_image"
class="form-control">
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-primary" value="Guardar">
</div>
</div>
</div>
</div>
</div>
</form>
miPerfilController.php
public function updatePhoto( Request $request )
{
return $request;
}
Result
write the form tag like this
<form class="form-group" method="POST" action="{{ route('profile.update') }}" enctype="multipart/form-data">
Try this
public function updatePhoto( Request $request , $id )
{
return $request->all();
}
You should try to get files using $request->file() method.
public function updatePhoto( Request $request , $id ){
if ($request->file('profile_image')) {
print_r($request->file('profile_image'));
} else {
echo 'file not found';
}
}
Thanks.

how can i save my image as base 64 into database

I'm trying to save an image from a form into database. I tried this but it's not working:
public function store(Request $request)
{
$article = new article;
$photo_articles = new photo_articles;
// $type = new type;
$article->NOM_ARTICLE = $request->NOM_ARTICLE;
$article->DESCRIPTION_ARTICLE = $request->DESCRIPTION_ARTICLE;
$article->id = auth()->user()->id;
$article->TYPE_ARTICLE = $request->LABEL_TYPE;
$article->save();
$photo_articles->PHOTO_ARTICLE = base64_encode(file_get_contents($request->PHOTO_ARTICLE));
$photo_articles->ID_ARTICLE = $article->ID_ARTICLE;
$photo_articles->save();
return;
}
Here is my form:
<form method="post" action="{{ route('addarticle.store') }}" class="contact_form text-center" id="contact_form">
{{ csrf_field() }}
<div class="row">
<div class="col-lg-6">
<div class="col-lg-12">
<input type="text" class="contact_input" name="NOM_ARTICLE" placeholder="Nom d'article"
required="required">
</div>
<div class="col-lg-12">
<select class="contact_input" name="LABEL_TYPE">
#foreach($types as $type)
<option> {{$type->LABEL_TYPE}}</option>
#endforeach
</select>
</div>
</div>
<div class="col-lg-6">
<div id="uploading" class="uploadfile">
<input type="hidden" name="MAX_FILE_SIZE" value="250000"/>
<input type="file" class="contact_input uploadFileInput" id="imagearticle" name="PHOTO_ARTICLE"
placeholder="Capture de votre article" name="fic" size=50 required="required"/>
<p id="uploadtextid" class="uploadText">upload image</p>
<img class="uploadImage" src="" id="displayedimage">
</div>
</div>
<div class="col-lg-12">
<textarea class="contact_textarea contact_input" name="DESCRIPTION_ARTICLE" placeholder="Description"
required="required"></textarea>
</div>
<button class="contact_button right" type="submit">Valider!</button>
</div>
</form>
My image is in $request->PHOTO_ARTICLE.
Can someone show me how to save it as base64? I've searched a lot but without result.
When you're submitting a file with a form you have to set add the attribute
enctype="multipart/form-data" to the opening form tag:
<form enctype="multipart/form-data" method="post" action="{{ route('addarticle.store') }}" class="contact_form text-center" id="contact_form">
otherwise it will only submit the name of the file and not the file itself.
Then in your route you would just need:
$photo_articles->PHOTO_ARTICLE = base64_encode(
file_get_contents($request->file('PHOTO_ARTICLE')->path())
);

move_uploaded_file( ) not working on video/audio/pdf

I've done an upload page that should upload the files and set their name in the database. It works just perfect with the pictures , but the sound formats and the other ones doesn't seem to work.
This is how my html part look
<form method="post" enctype="multipart/form-data">
<div class="card card-login">
<?= FH::csrfInput() ?>
<div class="card-header text-center" data-background-color="rose" >
<h3 class="card-title">Upload</h3>
</div>
<div class="card-content">
<div class="input-group">
<span class="input-group-addon">
</span>
<div class="form-group label-floating">
<label class="control-label"><h4>Chose a name for the file</h4></label>
<br>
<input type="textd" name="name" id="name" class="form-control" value="">
</div>
<br><br>
<div class="form-group label-floating">
<label class="control-label"><h4>Choose a file</h4></label>
<br>
<input type="file" id="file" name="file" >
</div>
</div>
</div>
<div class="footer text-center">
<div class="file-upload">
<label for="submit" class="file-upload__label">
<div class="isa_error_class">
<?= FH::displayErrors($this->displayErrors)?>
</div>
<button class="btn btn-wd btn-lg" data-background-color="rose">Submit</button>
</label>
<input type="submit" name="submit" value="Submit" class="file-upload__input">
</div>
</div>
</form>
And there is the php part
if($this->request->isPost())
{
$this->request->csrfCheck();
$upload->assign($this->request->get());
$upload->user_id = Users::currentUser()->id;
$upload->name .= "." . pathinfo($_FILES['file']['name'] , PATHINFO_EXTENSION);
$value = pathinfo($_FILES['file']['name'] , PATHINFO_EXTENSION);
$upload->format = Upload::setFormat($value);
$dir = Users::currentUser()->id;
if(move_uploaded_file($_FILES["file"]["tmp_name"],'files' . DS . $dir . DS . $upload->name ))
{
if($upload->save())
{
Router::redirect('upload');
}
else
{
$upload->addErrorMessage('file','There were a problem saving in the database.');
}
}
else
{
$upload->addErrorMessage('file','There were a problem uploading it.');
}
}
The DS is the separator. The image formats seems to work perfect , but the other formats don't. Any ideas ?
You should check if u have allowed file_uploads = On in your php.ini and also check the maximum file size upload_max_filesize= 20M and to make sure that you are not passing it.

Categories