Laravel validation with lang for input names - php

I have one class named Validator that handles all validations that I need to do, and one class that extends my class with my rules and names for the error.
The problem is, I'm trying to use 'Lang' to get a translated message but it don't work and I don't know why.
Validation class:
<?php namespace App\Services\Validators;
abstract class Validator {
protected $data;
public $errors;
public static $rules;
public static $names;
public function __construct($data = null)
{
$this->data = $data ?: \Input::all();
}
public function passes()
{
$validation = \Validator::make($this->data, static::$rules, array(), static::$names);
if ($validation->passes()) return true;
$this->errors = $validation->messages();
return false;
}
}
My class that extends the validator:
use Lang;
class PrestadorSiteValidator extends Validator {
public static $rules = array(
'nome' => 'required',
'nome_fantasia' => 'required',
'email' => 'required|confirmed',
'identificador' => 'required',
'pais_id' => 'required',
'codigo_postal' => 'required',
'estado' => 'required',
'cidade' => 'required',
'rua' => 'required',
'bairro' => 'required',
);
public static $names = array(
'nome' => Lang::get('site.nome'),
'nome_fantasia' => 'Nome Fantasia',
'email' => 'Email',
'identificador' => 'CNPJ',
'pais_id' => 'País',
'codigo_postal' => 'Código Postal',
'estado' => 'Estado',
'cidade' => 'Cidade',
'rua' => 'Rua',
'bairro' => 'Bairro',
);
}
The error that I get:
syntax error, unexpected '(', expecting ')'
When I try to use:
'nome' => Lang::get('site.nome'),
Can someone please help me? :)

You cannot execute code in a PHP variable definition statement, so, instead of:
public static $names = array(
'nome' => Lang::get('site.nome'),
);
You must do something like
public static $names = array(
'nome' => 'site.nome',
);
EDIT:
To do what you need to do, the way you are doing it, you can, in your abstract validator, override an important method:
<?php namespace App\Services\Validators;
abstract class Validator {
protected function explodeRules($rules)
{
foreach(static::$names as $key => $value)
{
if (starts_with($value, 'lang::'))
{
static::$names[$key] = Lang::get(str_replace("lang::", "", $value));
}
}
return parent::explodeRules($rules);
}
}
Then use it:
public static $names = array(
'nome' => 'lang::site.nome',
'nome_fantasia' => 'Nome Fantasia',
'email' => 'Email',
'identificador' => 'CNPJ',
'pais_id' => 'País',
'codigo_postal' => 'Código Postal',
'estado' => 'Estado',
'cidade' => 'Cidade',
'rua' => 'Rua',
'bairro' => 'Bairro',
);
Not a very clean way of doing it, but it should work.

Related

Per row validation while importing CSV file

I'm Importing a CSV file to a livewire component and trying to run some validation for each row of the file but I'm having problems doing this. It seems that my validation is doing nothing.
Here is how my Livewire component looks like:
namespace App\Http\Livewire\Modals;
use Validator;
use Livewire\Component;
use App\Http\Traits\Csv;
use App\Models\AccountUser;
use Livewire\WithFileUploads;
use Illuminate\Support\Facades\Auth;
class ImportExtensions extends Component
{
use WithFileUploads;
public $clientID;
public $showModal = false;
public $upload;
public $columns;
public $fieldColumnMap = [
'first_name' => '',
'last_name' => '',
'email' => '',
'password' => '',
'extension' => '',
'user_type' => '',
];
protected $rules = [
'fieldColumnMap.first_name' => 'required|max:255',
'fieldColumnMap.last_name' => 'required|max:255',
'fieldColumnMap.email' => 'required|max:255',
'fieldColumnMap.password' => 'required|max:255',
'fieldColumnMap.extension' => 'required|max:255',
'fieldColumnMap.user_type' => 'required|max:255',
];
protected $validationAttributes = [
'fieldColumnMap.first_name' => 'First Name',
'fieldColumnMap.last_name' => 'Last Name',
'fieldColumnMap.email' => 'Email',
'fieldColumnMap.password' => 'Password',
'fieldColumnMap.extension' => 'Extension',
'fieldColumnMap.user_type' => 'User Type',
];
public function updatingUpload($value)
{
Validator::make(
['upload' => $value],
['upload' => 'required|mimes:txt,csv'],
)->validate();
}
public function updatedUpload()
{
$this->columns = Csv::from($this->upload)->columns();
$this->guessWhichColumnsMapToWhichFields();
}
public function import()
{
// Validate that you are importing any data
$this->validate();
$importCount = 0;
Csv::from($this->upload)
->eachRow( function ($row) use (&$importCount){
$eachRow = $this->extractFieldsFromRow($row);
//Validate the data of each Row to make to make sure you don't import duplicate records
$this->validateOnly(collect($eachRow), [
'fieldColumnMap.first_name' => 'required|max:255',
'fieldColumnMap.last_name' => 'required|max:255',
'fieldColumnMap.email' => 'required|max:255|email|unique:account_users, email',
'fieldColumnMap.extension' => 'required|numeric|unique:account_users, extension',
'fieldColumnMap.password' => 'required|max:255',
'fieldColumnMap.user_type' => 'required|in:user,admin',
]);
//If validation fails, it should skip the create extension part and run the next row
//If validation pass, then create the Extension
AccountUser::create([
'user_id' => Auth::user()->id,
'account_id' => $this->clientID,
'first_name' => $eachRow['first_name'],
'last_name' => $eachRow['last_name'],
'email' => $eachRow['email'],
'password' => $eachRow['password'],
'extension' => $eachRow['extension'],
'user_type' => $eachRow['user_type'],
]);
$importCount++;
});
$this->reset();
$this->emit('refreshExtensions');
$this->notify('Successfully Imported '.$importCount.' Extensions');
}
Also, how can I make so that if the validation fails it goes to the next row instead of trying to create the extension.
Thanks.
I was able to create custom rules for just this. if one row fails validation, I just throw an error. So, basically either all rows pass or all fails.
Here is how it looks like now:
public function import()
{
// Validate that you are importing any data
$this->validate();
$importCount = 0;
Csv::from($this->upload)
->eachRow( function ($row) use (&$importCount){
$eachRow = $this->extractFieldsFromRow($row);
$validatedData = Validator::make([
'first_name' => $eachRow['first_name'],
'last_name' => $eachRow['last_name'],
'email' => $eachRow['email'],
'password' => $eachRow['password'],
'extension' => $eachRow['extension'],
'user_type' => $eachRow['user_type'],
],[
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email|unique:account_users',
'extension' => 'required|numeric|unique:account_users',
'password' => 'required|max:255',
'user_type' => 'required|in:user,admin',
],);
if($validatedData->fails()){
$this->notify(['error','Oops something went wrong!']);
}else{
AccountUser::create([
'user_id' => Auth::user()->id,
'account_id' => $this->clientID,
'first_name' => $eachRow['first_name'],
'last_name' => $eachRow['last_name'],
'email' => $eachRow['email'],
'password' => $eachRow['password'],
'extension' => $eachRow['extension'],
'user_type' => $eachRow['user_type'],
]);
$importCount++;
}
});
$this->reset();
$this->emit('refreshExtensions');
if($importCount!=0) $this->notify(['success','Successfully Imported '.$importCount.' Extensions']);
}

laravel + mongo + gpaphql get children array

i have data in mongodb
it is a road object that has a property and an array of points that it consists of:
my model in laravel
<?php
namespace App\Models;
use App\Traits\Uuids;
use GraphQL\Type\Definition\Type;
use Rebing\GraphQL\Support\Facades\GraphQL;
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class Road extends Eloquent
{
//use HasFactory;
use Uuids;
protected $connection = 'mongodb';
protected $collection = 'roads';
protected $fillable = ['id', 'roadId', 'code', 'name', 'points'];
#public $timestamps = false;
public $incrementing = false;
public function fields() : array
{
return [
'id' => [
'type' => Type::string(),
'description' => 'The identifier of the road',
],
'roadId' => [
'type' => Type::nonNull(Type::int()),
'description' => 'ID road of external database',
],
'code' => [
'type' => Type::string(),
'description' => 'code of document',
],
'name' => [
'type' => Type::nonNull(Type::string()),
'description' => 'road name',
],
'points' => [
'name' => 'points',
'description' => 'points of road',
'type' => GraphQL::type('RoadPoints'),
'is_relation' => false
]
];
}
}
here we refer to a new type of "point on the road"
GraphQL type 'RoadPoints':
<?php
namespace App\GraphQL\Types;
use App\Models\Address;
use App\Models\RoadPoints;
use GraphQL\Type\Definition\Type;
use Rebing\GraphQL\Support\Facades\GraphQL;
use Rebing\GraphQL\Support\Type as GraphQLType;
class RoadPointsType extends GraphQLType
{
protected $attributes = [
'name' => 'RoadPoints',
'description' => 'The points is defined by the format GeoJSON Point',
'model' => RoadPoints::class,
];
public function fields(): array
{
return [
'type' => [
'type' => Type::string(),
'description' => 'The format GeoJSON',
],
'pk' => [
'type' => Type::string(),
'description' => 'piket of point',
],
'coordinates' => [
'type' => Type::listOf(GraphQL::type('GeoJSON')),
'description' => 'The partner lat and lng',
]
];
}
}
laravel model of RoadPoints
model RoadPoints class :
<?php
namespace App\Models;
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class RoadPoints extends Eloquent
{
protected $fillable = ['type', 'pk', 'coordinates'];
protected $casts = [
'coordinates' => 'array'
];
}
graphql RoadQuery :
<?php
namespace App\GraphQL\Queries;
use App\Models\Road;
use Closure;
use GraphQL\Type\Definition\Type;
use Rebing\GraphQL\Support\Query;
use App\Services\RoadService;
use GraphQL\Type\Definition\ResolveInfo;
use Rebing\GraphQL\Support\Facades\GraphQL;
class RoadQuery extends Query
{
private $roadService;
public function __construct(RoadService $roadService)
{
$this->roadService = $roadService;
}
protected $attributes = [
'name' => 'Road',
'description' => 'Query to Road data and points.'
];
public function type(): Type
{
return Type::listOf(GraphQL::type('Road'));
}
public function args(): array
{
return [
'id' => ['name' => 'id', 'type' => Type::string()],
'roadId' => ['name' => 'roadId', 'type' => Type::int()],
'code' => ['name' => 'code', 'type' => Type::string()],
'name' => ['name' => 'name', 'type' => Type::string()],
'lat' => ['name' => 'lat', 'type' => Type::float()],
'lng' => ['name' => 'lng', 'type' => Type::float()]
];
}
public function resolve($root, $args, $context, ResolveInfo $resolveInfo, Closure $getSelectFields)
{
$fields = $resolveInfo->getFieldSelection($depth = 3);
return $this->roadService->find($args, $fields);
}
}
result:
why pk and coordinates is null ?
Please tell me how to correctly select all objects in the array (points).
error in model
change
'type' => GraphQL::type('RoadPoints'),
to
'type' => Type::listOf(GraphQL::type('RoadPoints')),

laravel undefined variable: itinerary

I can't seem to find the variable itinerary from my update function in my controller. What seems to be the problem for this?
Error says: Undefined variable: itinerary (View: C:\xampp\htdocs\project_name\resources\views\Agent\edit.blade.php)
AgentsController update function
public function update(Request $request, $p_id){
$this->validate($request, [
'packageName' => 'required',
'adultPrice' => 'required',
'childPrice' => 'required',
'infantPrice' => 'required',
'excessPrice' => 'required',
'type' => 'required',
'inclusions' => 'required',
'additionalInfo' => 'required',
'reminders' => 'required',
'photo' => 'required',
'tags' => 'required',
'noOfDays' => 'required',
'day' => 'required',
'time' => 'required',
'destination' => 'required'
]);
$packages = Packages::find($p_id);
$packages->packageName = $request->input('packageName');
$packages->adultPrice = $request->input('adultPrice');
$packages->childPrice = $request->input('childPrice');
$packages->infantPrice = $request->input('infantPrice');
$packages->excessPrice = $request->input('excessPrice');
$packages->type = $request->input('type');
$packages->inclusions = $request->input('inclusions');
$packages->additionalInfo = $request->input('additionalInfo');
$packages->reminders = $request->input('reminders');
$packages->photo = $request->input('photo');
$packages->tags = $request->input('tags');
$packages->save();
$itinerary = Itinerary::find($p_id);
if($itinerary->p_id == $packages->p_id){
$itinerary->noOfDays = $request->input('noOfDays');
$itinerary->day = $request->input('day');
$itinerary->time = $request->input('time');
$itinerary->destination = $request->input('destination');
$itinerary->save();
return redirect('Agent/Packages')->with('success', 'Updated');
}
}
edit.blade.php where the error is located
{{!!Form::open(array('class' => 'form-horizontal', 'method' => 'post', 'action' => array('AgentsController#update', $packages->p_id, $itinerary->p_id)))!!}}
Itinerary.php Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Itinerary extends Model{
public $fillable = [
'p_id',
'noOfDays',
'day',
'time',
'destination'
];
protected $primaryKey = 'i_id';
}
?>
Edit function
public function edit($p_id){
$packages = Packages::find($p_id);
$itinerary = Itinerary::find($p_id);
return View::make('\Agent\Edit', ['packages' => $packages, 'itineraries' => $itinerary]);
}
The way you pass the data is wrong.
Documentation
There are few ways you can pass. Examples :
1 -
return View::make('Agent.edit', ['packages' => $packages, 'itinerary' => $itinerary]);
2 - return View::make('Agent.edit')->with(['packages' => $packages, 'itinerary' => $itinerary]);
3 - return View::make('Agent.edit')->with('packages', $packages)->with('itinerary', $itinerary);
In your edit.blade.php, try remplacing your $itinerary variable by $itineraries (plural).

Laravel 5.1 Combine Form Request and Validator

I'm using form requests class. Work fine:
class EventFormRequest extends FormRequest
{
public function rules()
{
return [
'event' => 'required|min:10|max:255',
'event_description' => 'required|min:3|max:255',
'url' => 'url',
'date' => 'required|date',
'start_time' => 'required',
'location.street' => 'required|max:255',
'location.house_number' => 'required|min:1|max:5',
'location.place' => 'required|max:255'
];
}
}
But now, I have to add complexer rules, such as combined with Validator. Below the new rules() method of my EventFormRequest class:
public function rules()
{
$v = \Validator::make($this->request->all(),
[
'event' => 'required|min:10|max:255',
'event_description' => 'required|min:3|max:255',
'url' => 'url',
'date' => 'required|date',
'start_time' => 'required',
'location.street' => 'required|max:255',
'location.house_number' => 'required|min:1|max:5',
'location.place' => 'required|max:255'
]);
$v->sometimes('category_id', 'required|numeric', function($input) {
return $input->event_type == 'known';
});
return ($v->fails() ? $v->messages() : []); // validator validates the rules, but returns the messages
}
You see, category_id is required if the event type is 'known'. In the form request rules() method, I cannot return the applied rules as array (see example 1) from the validator, but only the messages().
I'm inspired from here: http://laravel.com/docs/5.1/validation#conditionally-adding-rules
class EventFormRequest extends FormRequest
{
public function rules()
{
$rules = [
'event' => 'required|min:10|max:255',
'event_description' => 'required|min:3|max:255',
'url' => 'url',
'date' => 'required|date',
'start_time' => 'required',
'location.street' => 'required|max:255',
'location.house_number' => 'required|min:1|max:5',
'location.place' => 'required|max:255'
];
if ($this->request->get('event_type') == 'known') {
$rules['category_id'] = 'required|numeric';
}
return $rules;
}
}

ZF2 form with fieldset and doctrine not working

I have a problem with a form, fieldset and doctrine.
This is my edit form. In this form I add the User Fieldset and add another field "password" (that I use only in this form).
EditUserForm:
class EditUserForm extends Form implements InputFilterProviderInterface
{
public function __construct($name = null, $options = [])
{
parent::__construct($name, $options);
$this->setAttribute('method', 'post');
$this->setHydrator(new ClassMethods(false));
$this->setObject(new User());
$this->add([
'name' => 'user',
'type' => 'Application\Form\UserFieldset',
'options' => [
'use_as_base_fieldset' => true
]
]);
$this->add([
'name' => 'password',
'type' => 'Zend\Form\Element\Password',
'attributes' => [
'id' => 'password'
]
]);
}
public function getInputFilterSpecification()
{
return [
'password' => [
'required' => true
],
];
}
}
UserFieldset:
class UserFieldset extends Fieldset implements InputFilterProviderInterface
{
public function __construct($name = null, $options = [])
{
parent::__construct($name, $options);
$this->setHydrator(new ClassMethods(false));
$this->setObject(new User());
$this->add([
'name' => 'name',
'type' => 'Zend\Form\Element\Text',
'attributes' => [
'id' => 'name'
]
]);
$this->add([
'name' => 'surname',
'type' => 'Zend\Form\Element\Text',
'attributes' => [
'id' => 'surname'
]
]);
}
public function getInputFilterSpecification()
{
return [
'name' => [
'required' => true
],
'surname' => [
'required' => true
],
];
}
}
Why if I try to var_dump(form->getData()) does the entity does not have the password field?
object(Application\Entity\User)[114]
private 'name' => string 'john' (length=4)
private 'surname' => string 'smith' (length=5)
private 'password' => null
thanks.
The password needs to be part of the UserFieldset as you're setting the UserFieldset as base-fieldset. If you choose a base-fieldset, only this fieldset will be hydrated recursively.

Categories