Laravel: File upload not working - php

I'm trying to upload an image via an HTML form in Laravel 5.5. I have included the enctype="multipart/form-data" attribute, still nothing happens.
Form code:
<form method="POST" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group">
<label for="m_photo" class="col-md-4 control-label">Main photo</label>
<div class="col-md-6">
<input id="m_photo" type="file" class="form-control-file space" name="m_photo" required>
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
Route (web.php) code:
Route::post('smartphones/entry', 'HomeController#s_submit')->name('s_submit');
Controller code:
public function s_submit() {
if (Input::hasFile('m_photo')) {
// doing something
}
else {
echo 'Nothing happened';
}
}
'Nothing happened' is echoed out when I submit the form.
It's interesting that when I do this:
public function s_submit(Request $request) {
$input = Input::all();
dd($input);
}
I see:
array:1 [
"m_photo" => UploadedFile {#210 ▶}
]
It's like the image is getting passed, but I'm unable to retrieve it. Please help.

This can happen when PHP max_file_size is not set to a size that allows the file you are trying to upload to be sent. This causes hasFile returns false, when, for example, file->getClientOriginalName() works.
Try to check upload_max_filesize or post_max_size in your php.ini, or try with a smaller file to check if it works.

if (Input::hasFile('m_photo')) {
$destinationPath = '/uploads/app/';
$file = $request->file('m_photo');
$filename = $file->getClientOriginalName();
$file->move(public_path() . $destinationPath, $filename);
$filename_to_save_in_db = $destinationPath . $filename;
}

Get the file with:
$file = $request->m_photo;
Or with:
$file = $request->file('m_photo');
https://laravel.com/docs/5.5/requests#retrieving-uploaded-files

You have forgot to put action in Your html Form :
put action="/smartphones/entry" or action="{{route('s_submit')}}"
<form method="POST" enctype="multipart/form-data" action="{{route('s_submit')}}">
{{ csrf_field() }}
<div class="form-group">
<label for="m_photo" class="col-md-4 control-label">Main photo</label>
<div class="col-md-6">
<input id="m_photo" type="file" class="form-control-file space" name="m_photo" required>
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
Create images folder in public folder
in your controller
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
public function s_submit(Request $request) {
if($request->hasFile('m_photo')){
$filenameWithExt=$request->file('m_photo')->getClientOriginalName();
$filename=pathinfo($filenameWithExt,PATHINFO_FILENAME);
$extension=$request->file('m_photo')->getClientOriginalExtension();
$fileNameToStore=$filename.'_'.time().'.'.$extension;
request()->m_photo->move(public_path('images'), $fileNameToStore);
}
else{
$fileNameToStore='noimage.jpg';
}
}

Try this:
public function s_submit()
{
request()->validate([
'm_photo' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$imageName = time().'.'.request()->m_photo->getClientOriginalExtension();
request()->m_photo->move(public_path('images'), $imageName);
return back()
->with('success','You have successfully upload image.')
->with('m_photo',$imageName);
}
Blade:
{!! Form::open(array('route' => 's_submit','files'=>true)) !!}
<div class="form-group">
<label for="m_photo" class="col-md-4 control-label">Main photo</label>
<div class="col-md-6">
{!! Form::file('m_photo', array('class' => 'form-control-file space')) !!}
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
{!! Form::close() !!}

For future visitors, the accepted answer is the right answer.
I wanted to share one more thing.
I also faced similar issue and I had set the upload_max_filesize and post_max_size variables to 20M, which was quite enough.
But I still faced the issue. So, I increased to 500M, then it worked.
It was really strange because I was uploading a file of less than 1 MB size.

Related

403 Forbidden after using #csrf in laravel 8 form

I am new to programming especially laravel. I am trying to make a CRUD and have already added example data in prequel (using Docker). I can see the data, but when I´m trying to create new posts with a form I get Code 419 page expired. I know that´s normal and the solution is to add #csrf to the form. But after doing this I get 403 Forbidden. I tried a lot but can´t find a solution to fix it.
I would be really happy if someone could help me fix my problem.
Here is my create.blade.php
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-12">
<div class="card">
<div class="card-header">{{ __('Alle Gerichte') }}</div>
<div class="card-body">
<form action = "/recipe" method="POST">
#csrf
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name">
</div>
<div class="form-group">
<label for="beschreibung">Beschreibung</label>
<textarea class="form-control" id="beschreibung" name="beschreibung" rows="5"></textarea>
</div>
<input class="btn btn-primary mt-4" type="submit" value="absenden">
</form>
<a class="btn btn-primary btn-sm mt-3 float-right" href="/recipe"><i class="fas fa-circle-up"></i>Zurück</a>
</div>
</div>
</div>
</div>
</div>
#endsection
hi is that you have created validation rules
in StoreRecipeRequest
do that
public function authorize()
{
return true;
}
Controller Code will be like this:
public function store(StoreRecipeRequest $request)
{
//dd($request);
$recipe = new Recipe( [
'name' => $request->name,
'beschreibung' => $request->beschreibung,
]);
$recipe->save();
return redirect('/recipe');
}
Also if it's not solved. Then let's try it.
public function store(StoreRecipeRequest $request)
{
$recipe = new Recipe();
$recipe->name = $request->name;
$recipe->beschreibung = $request->beschreibung;
$recipe->save();
return redirect('/recipe');
}
also, can you add in your Recipe Model?
protected $fillable = [
'name',
'beschreibung',
];

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');
}

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.

Laravel validation doesn't seem to work at all

I am trying to validate the form data as they do in laravel's default authentication. It worked few days ago but now it doesn't work. If user didn't make any mistakes in form and submit it, then it successfully save data in the db. If user submit an empty form without any data or did some mistake in the form it's not showing the error message. If i add controller function code in a try catch, exception is showing as 'Invalid data'
view(form)
<form class="form-horizontal" action="{{ route('save-service-page-content') }}" method="POST" enctype="multipart/form-data">
<div class="box-body">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('file') ? ' has-error' : '' }}">
<label for="image" class="col-sm-2 control-label">Service Image</label>
<input hidden id="service_image_file" name="file"/>
<div class="col-sm-10" id="demo-upload">
<div class="dropzone needsclick dz-clickable" id="serviceImageUpload">
<div class="dz-default dz-message">
<i class="fa fa-image fa-5x"></i>
<h3 class="sbold">Drop an image here to upload</h3>
<span>You can also click to open file browser</span>
</div>
</div>
#if ($errors->has('file'))
<span class="help-block"><strong>The service image is reuired</strong></span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('description') ? ' has-error' : '' }}">
<label for="inputEmail3" class="col-sm-2 control-label">Description</label>
<div class="col-sm-10">
<textarea rows="8" class="form-control" name="description" placeholder="Description goes here"></textarea>
#if ($errors->has('description'))
<span class="help-block"><strong>{{ $errors->first('description') }}</strong></span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('description_sin') ? ' has-error' : '' }}">
<label for="inputEmail3" class="col-sm-2 control-label">හැදින්වීම</label>
<div class="col-sm-10">
<textarea rows="8" class="form-control" name="description_sin" placeholder="හැදින්වීම සිංහලෙන්"></textarea>
<small class="form-text text-muted">හැදින්වීම ඇතුලත් කරන්න. (හැදින්වීම සිංහල බසින් ඇතුලත් කලොත් පමණක් එය ඉංග්‍රීසි බස වෙනුවට සිංහල බසින් දිස්වනු ඇත.)</small>
#if ($errors->has('description_sin'))
<span class="help-block"><strong>මෙම හැදින්වමෙහි අක්ෂර සහ ඉලක්කම් පමණක් ඇතුලත් විය යුතුය </strong></span>
#endif
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer clearfix">
<button type="submit" class="btn btn-default">Cancel</button>
<button type="submit" class="btn btn-info pull-right">Post</button>
</div>
</form>
Controller
namespace App\Http\Controllers;
use App\Service_page_content;
use App\Service;
use File;
use Image;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class ServiceContent extends Controller
{
protected function validator(array $data)
{
return Validator::make($data, [
'file' => 'required',
'description' => 'nullable|alpha_num_spaces_brackets',
'description_sin' => 'nullable|alpha_num_spaces_brackets',
]);
}
public function save_page_content(Request $request)
{
$this->validator($request->all())->validate();
$service_page_content = new Service_page_content;
$service_page_content->description = $request->description;
$service_page_content->description_sin = $request->description_sin;
$file = $request->file;
$image_decode = base64_decode($file);
$image_data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $file));
$f = finfo_open();
$mime_type = finfo_buffer($f, $image_data, FILEINFO_MIME_TYPE);
$imageName = "service-page-content-".time().'.'.str_replace("image/","",$mime_type);
$image_resized = Image::make($image_data);
$image_resized->resize(1170, null, function ($constraint) {
$constraint->aspectRatio();
});
$image_resized->save(public_path("uploads/service_page_content_uploads/$imageName"));
$service_page_content->main_img_url = $imageName;
$service_page_content->save();
return redirect()->back()->with('success', ['Data Saved']);
}
}
I don't know if I'm doing it correctly on return Validator::make($data,...... or $this->validator($request->all())->validate();
I have written a custom validation rule that allows alpha numeric, spaces, brackets, '.' and ',' in AppServiceProvider boot function. It also worked few days ago. Now nothing seems to work.
It worked few days ago. Ignore the file upload part it is working perfectly I'm using Dropzone.js for it. May be I'm missing something. Any help would be appreciated !
You can validate directly on the array without calling the Validator facade.
protected function validator(Request $request)
{
return $request->validate([
'file' => 'required',
'description' => 'nullable|alpha_num_spaces_brackets',
'description_sin' => 'nullable|alpha_num_spaces_brackets',
]);
}
public function save(Request $request){
$this->validator($request);
}

Nothing happen when uploading image laravel

when I am trying to upload an image there is no error being shown or anything coming out. All it does was return me back to the create1.blade.php. When I try to use dd, it also doesn't show anything as well(maybe I put it wrongly or something not sure, still learning about it)
Here are my codes:
Controller:
public function create1(){
return view('create1');
}
public function store1(Request $request){
$this->validate($request, [
'input_img' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if ($request->hasFile('input_img')) {
$image = $request->file('input_img');
$name = time().'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/images');
$image->move($destinationPath, $name);
$this->save();
return redirect()->back()->with('success','Image Upload successfully');
}
}
create1.blade.php
<form class="form-horizontal" method="post" action="{{ url('/userUpload')}}">
{{ csrf_field() }}
<div class="form-group">
<label for="imageInput" class="control-label col-sm-3">Upload Image</label>
<div class="col-sm-9">
<input data-preview="#preview" name="input_img" type="file" id="imageInput">
<img class="col-sm-6" id="preview" src="" ></img>
</div>
</div>
<div class="form-group">
<div class="col-md-6-offset-2">
<input type="submit" class="btn btn-primary" value="Save">
</div>
</div>
</form>
You just forgot to put enctype="multipart/form-data" in your <form> tag!
This is allow to upload the file!
For example:
<form class="form-horizontal" method="post" action="{{ url('/userUpload')}}" enctype="multipart/form-data">
Hope this fixed your issue!
The issue is here:
<form class="form-horizontal" method="post" action="{{ url('/userUpload')}}">
here you are missing enctype="multipart/form-data". Put it in form like:
<form class="form-horizontal" method="post" action="{{ url('/userUpload')}}" enctype="multipart/form-data">
and try again.

Categories