Can't upload files using livewire - laravel

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

Related

Bleaching the page when submitting the form with livewire

In login form i used livewire and when i out focus of phone field my webpage its been white
please help me thanks <3
view code:
<form wire:submit.prevent="login">
<fieldset class="form-label-group form-group position-relative has-icon-left">
<input wire:model.debounce.500ms="phone" type="text" class="form-control" id="phone" placeholder="شماره تماس">
<div class="form-control-position">
<i class="feather icon-phone"></i>
</div>
<label for="phone">شماره تماس</label>
</fieldset>
#error('phone') <span class="text-danger">{{ $message }}</span> #enderror
<button type="submit" class="btn btn-primary float-left btn-inline" wire:click.prevent="login">ورود</button>
</form>
controller code:
class Login extends Component
{
public $phone;
protected $rules = [
'phone' => ['required', 'regex:/^09(1[0-9]|3[1-9]|2[1-9])-?[0-9]{3}-?[0-9]{4}$/', 'exists:users,phone']
];
public function updatedPhone($name)
{
$this->validate($name);
}
public function login(Request $request)
{
$validData = $this->validate();
$user = User::wherePhone($validData['phone'])->first();
dd($user);
$request->session()->flash('auth', [
'user_id' => $user->id,
'remember' => $request->has('remember'),
]);
$code = ActiveCode::generateCode($user);
$user->notify(new ActiveCodeNotification($code, $user->phone));
dd('done');
}
public function render()
{
return view('livewire.auth.login')
->layout('livewire.auth.layouts.layouts');
}
}
Your updatePhone method is supposed to receive $value from input binded with wire:model so you have to pass a key-value to validate method:
public function updatePhone($value)
{
$this->validate($this->rules); // protected prop with key-value rules defined
}

laravel and validation with request

I cannot set correctly validation in Laravel.
Among other functions I have this in the Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Exports\RimborsiExport;
use DB;
use App\Customers;
use App\Claims;
use App\Refunds;
use App\Services;
use App\Http\Requests\RefundsPost;
use Excel;
use DataTables;
use Redirect;
use Response;
class RefundsController extends Controller
{
public function storeRefundsData(RefundsPost $request){
dd($request);
//$validated = $request->validated();
$customers = Customers::create($request->all());
return back()->with('status', 'Dati Cliente inseriti correttamente');
}
}
I have also defined a custom Request type
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class RefundsPost extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
$rules = [
'contr_nom' => 'required|max:255',
'contr_cog' => 'required',
'polizza' => 'required',
'email' => 'required',
'targa' => 'required',
'iban' => 'required|iban',
'int_iban' => 'required',
];
return $rules;
}
public function messages()
{
return [
'contr_nom.required' => "Il Nome Contraente e' obbligatorio",
'contr_cog.required' => "Il Cognome Contraente e' obbligatorio",
'polizza.required' => "Il numero di polizza e' obbligatorio",
'email.required' => "Una mail e' obbligatoria per le comunicazioni",
'targa.required' => "La targa e' obbligatoria",
'data_sin.required' => "La data sinistro e' obbligatoria",
'iban.required' => "Il numero IBAN e' obbligatorio",
'int_iban.required' => "L'intestatario dell' IBAN e' obbligatorio",
'dossier.required' => "Il numero di dossier e' obbligatorio",
'cliente.required' => "Il cliente e' obbligatorio",
'stato.required' => "Lo stato del rimborso e' obbligatorio",
'date_ref.required' => "La data della richiesta e' obbligatoria",
];
}
}
and i have this blade with the form inside
<div class="container-fluid">
<form method="POST" action="{{ route('storeRefundsData') }}" novalidate>
{{ csrf_field() }}
<h5 class="mb-3">Anagrafica</h5>
<div class="row">
<div class="col-md-6 mb-3">
<label for="contr_nom">Nome Contraente</label>
<input type="text" class="form-control #error('contr_nom') is-invalid #enderror" id="contr_nom" name="contr_nom" value="{{old('contr_nom')}}">
#error('contr_nom')
<div class="invalid-feedback">{{ $message }}</div>
#enderror
</div>
<div class="col-md-6 mb-3">
<label for="contr_cog">Cognome Contraente</label>
<input type="text" class="form-control #error('contr_cog') is-invalid #enderror" id="contr_cog" name="contr_cog" value="{{old('contr_cog')}}">
#error('contr_cog')
<div class="invalid-feedback">{{ $message }}</div>
#enderror
</div>
</div>
<div class="row">
<div class="col-md-6 mb-3">
<label for="polizza">Numero Polizza <span class="text-muted"></span></label>
<input type="text" class="form-control #error('polizza') is-invalid #enderror" id="polizza" name="polizza" value="{{old('polizza')}}">
#error('polizza')
<div class="invalid-feedback">{{ $message }}</div>
#enderror
</div>
<div class="col-md-6 mb-3">
<label for="email">Email <span class="text-muted"></span></label>
<input type="email" class="form-control #error('email') is-invalid #enderror" id="email" name="email" placeholder="tu#esempio.it" value="{{old('email')}}">
#error('email')
<div class="invalid-feedback">{{ $message }}</div>
#enderror
</div>
</div>
<div class="row">
<div class="col-md-6 mb-3">
<label for="targa">Targa veicolo</label>
<input type="text" class="form-control #error('targa') is-invalid #enderror" id="targa" name="targa" placeholder="Inserisci la targa" value="{{old('targa')}}">
#error('targa')
<div class="invalid-feedback">{{ $message }}</div>
#enderror
</div>
</div>
<h5 class="mb-3">Dati bancari</h5>
<div class="row">
<div class="col-md-6 mb-3">
<label for="iban">IBAN <span class="text-muted"></span></label>
<input type="text" class="form-control #error('iban') is-invalid #enderror" id="iban" name="iban" placeholder="Inserisci il tuo IBAN" value="{{old('iban')}}">
#error('iban')
<div class="invalid-feedback">{{ $message }}</div>
#enderror
</div>
<div class="col-md-6 mb-3">
<label for="int_iban">Intestatario IBAN <span class="text-muted"></span></label>
<input type="text" class="form-control #error('int_iban') is-invalid #enderror" id="int_iban" name="int_iban" placeholder="Inserisci l'intestatario dell'IBAN" value="{{old('int_iban')}}">
#error('int_iban')
<div class="invalid-feedback">{{ $message }}</div>
#enderror
</div>
</div>
<hr class="mb-4">
<!-- <button class="btn btn-primary btn-lg btn-block" type="submit">Continue to checkout</button>-->
<input type="submit" class="btn btn-primary btn-lg btn-block" value="Salva">
#if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
#endif
</form>
</div>
I cannot understand why when i click on form submit button to create a new row in the db, it seems that even it doesn't enter Controller function.
If I use Request instead of custom type RefundsPost it works and store data in the db but obviously without validation.
How can i fix?
Thx a lot
Not sure if this solves your problem, but I have rewritten your functions the way I would do it. You can specify what http method the rules are for, in this case I specified the rules for POST requests.
RefundsPost -> rules:
public function rules() {
$rules = [];
switch($this->method()) {
case 'POST':
{
$rules = [
'contr_nom' => 'required|max:255',
'contr_cog' => 'required',
'polizza' => 'required',
'email' => 'required',
'targa' => 'required',
'iban' => 'required|iban',
'int_iban' => 'required',
];
}
default:
break;
}
return $rules;
}
and in the storeRefundsData function, you should use $request->validated() and use the attributes it return after validation when you proceed the insertion.
RefundsController -> storeRefundsData:
public function storeRefundsData(RefundsPost $request) {
$attributes = $request->validated();
$customers = Customers::create($attributes);
if (!($customers instanceof Customers)) {
// could not create customer
return ['result' => false];
}
$customers = $customers->fresh(); // if you need to retrieve the objects id
return ['result' => true];
}
Unfortunately, I cannot comment.
However, out of curiosity the rule iban is custom I believe right?
If so, can you try the following:
public function rules()
{
return [
'contr_nom' => ['required', 'max:255'],
'contr_cog' => ['required'],
'polizza' => ['required'],
'email' => ['required'],
'targa' => ['required'],
'iban' => ['required', new Iban],
'int_iban' => ['required'],
];
}
Of course, don't forget to import the rule class at the top:
use App\Rules\Iban;
Try it and let us know, cheers!

Laravel Image Upload not saving to public folder

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!

Call to a member function getClientOriginalName() on null upload file PDF

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();

How to use custom validation attributes on an array of inputs

I'm using Laravel to build a form that contains an array of inputs and I’m having difficulty in showing the translated attribute name when a validation error occurs. For simplicity sake I will post a simple example of my problem.
Form inside the view:
<form method="POST" action="{{ route('photo.store') }}" accept-charset="UTF-8" role="form">
<input name="_token" type="hidden" value="{{ csrf_token() }}">
<div class="row">
<div class="col-lg-12">
<div class="form-group{{ $errors->has('testfield') ? ' has-error' : '' }}">
<label class="control-label"
for="testfield">{{ trans('validation.attributes.testfield') }}</label>
<input class="form-control" name="testfield" type="text" id="testfield"
value="{{ old('testfield') }}">
#if ($errors->has('testfield'))
<p class="help-block">{{ $errors->first('testfield') }}</p>
#endif
</div>
</div>
<div class="col-lg-12">
<div class="form-group{{ $errors->has('testfieldarray.0') ? ' has-error' : '' }}">
<label class="control-label"
for="testfieldarray-0">{{ trans('validation.attributes.testfieldarray') }}</label>
<input class="form-control" name="testfieldarray[]" type="text" id="testfieldarray-0"
value="{{ old('testfieldarray.0') }}">
#if ($errors->has('testfieldarray.0'))
<p class="help-block">{{ $errors->first('testfieldarray.0') }}</p>
#endif
</div>
</div>
<div class="col-lg-12">
<div class="form-group{{ $errors->has('testfieldarray.1') ? ' has-error' : '' }}">
<label class="control-label"
for="testfieldarray-1">{{ trans('validation.attributes.testfieldarray') }}</label>
<input class="form-control" name="testfieldarray[]" type="text" id="testfieldarray-1"
value="{{ old('testfieldarray.1') }}">
#if ($errors->has('testfieldarray.1'))
<p class="help-block">{{ $errors->first('testfieldarray.1') }}</p>
#endif
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<input class="btn btn-primary" type="submit" value="Gravar">
</div>
</div>
Rules function in the form request:
public function rules() {
$rules = [
'testfield' => array('required'),
];
foreach ($this->request->get('testfieldarray') as $key => $val) {
$rules['testfieldarray.' . $key] = array('required');
}
return $rules;
}
lang/en/validation.php
'attributes' => [
'testfield' => 'Test Field',
'testfieldarray' => 'Test Field Array',
],
The validation is performed correctly, as do the error messages. The only problem in the error messages is the name of the attribute displayed. In both array inputs, the attribute name inserted in the message is 'testfieldarray.0' and 'testfieldarray.1' instead of 'Test Field Array'. I already tried to add on the language file 'testfieldarray.0' => 'Test Field Array', 'testfieldarray.1' => 'Test Field Array', but the messages remain unchanged. Is there a way to pass the attribute names correctly?
Just see the example to add custom rules for integer type value check of array
Open the file
/resources/lang/en/validation.php
Then add the custom message.
// add it before "accepted" message.
'numericarray' => 'The :attribute must be numeric array value.',
Again Open another file to add custom validation rules.
/app/Providers/AppServiceProvider.php
So, add the custom validation code in the boot function.
public function boot()
{
$this->app['validator']->extend('numericarray', function ($attribute, $value, $parameters)
{
foreach ($value as $v) {
if (!is_int($v)) {
return false;
}
}
return true;
});
}
Now you can use the numericarray for integer type value check of array.
$this->validate($request, [
'input_filed_1' => 'required',
'input_filed_2' => 'numericarray'
]);
----------- Best of Luck --------------
1-if you split the validation in file request then add the method attributes and set the value of each key like this :
public function attributes()
{
return [
'name'=>'title',
];
}
2- but if don't split the validation of the request then you just need to make variable attributes and pass the value of items like this :
$rules = [
'account_number' => ['required','digits:10','max:10','unique:bank_details']
];
$messages = [];
$attributes = [
'account_number' => 'Mobile number',
];
$request->validate($rules,$messages,$attributes);
// OR
$validator = Validator::make($request->all(), $rules, $messages, $attributes);
Use custom error messages inside your parent method....
public function <metod>(Request $request) {
$rules = [
'testfield' => 'required'
];
$messages = [];
foreach ($request->input('testfieldarray') as $key => $val) {
$rules['testfieldarray.' . $key] = 'required';
$messages['testfieldarray.' . $key . '.required'] = 'Test field '.$key.' is required';
}
$validator = Validator::make($request->all(), $rules,$messages);
if ($validator->fails()) {
$request->flash();
return redirect()
->back()
->withInput()
->withErrors($validator);
}
}
}

Resources