Laravel 5.1 Combine Form Request and Validator - php

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

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 5 Update Validation email needs to be unique

I'm trying to update a user, as an admin.
I'm changing the username, but it says email must be unique.
How do I fix this.
public function update($id, PutUser $request)
{
if (auth()->id() == $id) {
return redirect()->back()->withFlashDanger('Permission Denied, You can not edit own profile here.');
}
$user = User::find($id);
$user->update((array_merge($request->validated(), ['county' => request('county')])));
//Update model_has_roles model with assignees_roles
return redirect()->route('users.index')->withFlashSuccess(trans("alerts.users.updated"));
}
This is the request class
public function authorize()
{
return true;
}
public function rules()
{
$user_id = $this->input('id');
return [
'name' => 'required|string',
'username' => 'required',
'email' => 'required|email|unique:users,email'.$user_id,
'gender' => 'required',
'phone' => 'sometimes|numeric',
'address' => 'sometimes|string',
'country_id' => 'required',
];
}
}
I keep getting a failed email validation. 'Email has already been taken'. Any idea
You are missing a comma after the email label in your validation:
return [
'name' => 'required|string',
'username' => 'required',
'email' => 'required|email|unique:users,email,'.$user_id,
'gender' => 'required',
'phone' => 'sometimes|numeric',
'address' => 'sometimes|string',
'country_id' => 'required',
];
Since Laravel 5.3 (I believe), you can also use rule builders for more descriptive validation rules. Those are better to read and interpret for humans so it would result in a lower error rate:
use Illuminate\Validation\Rule;
return [
'email' => [
'required',
Rule::unique('users', 'email')->except($user_id),
]
];
https://medium.com/#tomgrohl/why-you-should-be-using-rule-objects-in-laravel-5-5-c2505e729b40

Can't get data to save in MySQL using Laravel

I'm trying to get the ticket data to save in the database and when I submit the form I get no error, but it does not insert the data into the database. Added my Route just adding random text because the post
Controller Code
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'title' => 'required|min:15',
'category' => 'required',
'priority' => 'required',
'message' => 'required|min:100',
]);
$ticket = new Ticket([
'user_id' => Auth::user()->id,
'category_id' => $request->input('category'),
'ticket_id' => strtoupper(str_random(10)),
'name' => $request->input('name'),
'title' => $request->input('title'),
'priority_id' => $request->input('priority'),
'message' => $request->input('message'),
]);
$ticket->status_id = '1';
$ticket->save();
return 'Success';
}
Model Code
class Ticket extends Model
{
protected $fillable = [
'user_id', 'category_id', 'ticket_id', 'name', 'title', 'priority_id', 'message', 'status_id',
];
public function category()
{
return $this->belongsTo(Category::class);
}
public function priority()
{
return $this->belongsTo(Priority::class);
}
public function status()
{
return $this->belongsTo(Status::class);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
}
Routes
Route::get('/', 'HomeController#index')->name('home');
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/compliance', 'HomeController#Compliance')->name('compliance');
Route::get('/messages', 'HomeController#Messages')->name('messages');
Route::get('/tickets', 'TicketsController#userTickets')->name('tickets');
Route::get('/tickets/create', 'TicketsController#create')->name('tickets/create');
Route::post('/tickets/store', 'TicketsController#store');
Thanks for all the help I figured it I had two mistakes in the controller this took me 2 days to figure it out LOL
$this->validate($request, [
'name' => 'required', // I removed this
'title' => 'required|min:15',
'category' => 'required',
'priority' => 'required',
'message' => 'required|min:100',
]);
and in the $ticket
$ticket = new Ticket([
'user_id' => Auth::user()->id,
'category_id' => $request->input('category'),
'ticket_id' => strtoupper(str_random(10)),
'name' => $request->input('name') // I replaced this with 'name' => Auth::user()->name,
'title' => $request->input('title'),
'priority_id' => $request->input('priority'),
'message' => $request->input('message'),
]);

Laravel 5.2 Modify Request After Form Validation Before Controller

I'm using laravel 5.2 and i'm using Form Request that given by laravel vendor to make my code clean, so i don't have many code on my controller :
public function store( CouponRequest $request )
{
DB::beginTransaction();
try {
$coupon = Coupon::create( $request->all() );
DB::commit();
return redirect()->route('admin.coupons.index');
} catch (\Exception $e) {
DB::rollback();
return redirect()->back()->withInput();
}
And this is my sample code about my request form :
public function rules()
{
switch ( strtolower( $this->method ) ) {
case 'post':
{
return [
'code' => 'required|unique:coupons,code',
'name' => 'required',
'start_year' => 'required',
'start_month' => 'required',
'start_day' => 'required',
'start_time' => 'required',
'finish_year' => 'required',
'finish_month' => 'required',
'finish_day' => 'required',
'finish_time' => 'required',
'using_time' => 'required',
'type' => 'required',
'free_shipment' => 'required',
'target' => 'required',
'target_user' => 'required'
];
}
case 'put':
{
return [
'code' => 'required',
'name' => 'required',
'start_year' => 'required',
'start_month' => 'required',
'start_day' => 'required',
'start_time' => 'required',
'finish_year' => 'required',
'finish_month' => 'required',
'finish_day' => 'required',
'finish_time' => 'required',
'using_time' => 'required',
'type' => 'required',
'free_shipment' => 'required',
'target' => 'required',
'target_user' => 'required'
];
}
default:
{
return [];
}
}
}
Where should i place this command? :
$start_date = Carbon::create( $request->start_year, $request->start_month, $request->start_day );
$start_date->setTimeFromTimeString( $request->start_time );
$finish_date = Carbon::create( $request->finish_year, $request->finish_month, $request->finish_day );
$finish_date->setTimeFromTimeString( $request->finish_time );
If i place this code before validation, i could be error when some field not filled well by users.
So what i want is to place this code after validation success, but i don't want to place it at my controller.
Is there FormRequest function that can be called after validation success to modify my request??
I think it's not good when there's much code at controller, so i want to minimalize my controller code.
I am going to attempt this using FormRequest. If the intention here is to both validate and assign start_date and finish_date, this is probably the plausible way of doing so in Laravel:
public function rules()
{
switch ( strtolower( $this->method ) ) {
case 'post':
{
return [
'code' => 'required|unique:coupons,code',
'name' => 'required',
'start_year' => 'required',
'start_month' => 'required',
'start_day' => 'required',
'start_time' => 'required',
'finish_year' => 'required',
'finish_month' => 'required',
'finish_day' => 'required',
'finish_time' => 'required',
'using_time' => 'required',
'type' => 'required',
'free_shipment' => 'required',
'target' => 'required',
'target_user' => 'required'
];
}
case 'put':
{
return [
'code' => 'required',
'name' => 'required',
'start_year' => 'required',
'start_month' => 'required',
'start_day' => 'required',
'start_time' => 'required',
'finish_year' => 'required',
'finish_month' => 'required',
'finish_day' => 'required',
'finish_time' => 'required',
'using_time' => 'required',
'type' => 'required',
'free_shipment' => 'required',
'target' => 'required',
'target_user' => 'required'
];
}
default:
{
return [];
}
}
}
/**
* #inheritDoc
*
* This method overrides Laravel's defeault FormRequest
* to create validator with `after()` hook
*/
protected function validator($validator)
{
$validator
->make(
$this->validationData(), $this->rules(), $this->messages(), $this->attributes()
)
->after(function($validator) {
if ($date = $this->getCarbonInstanceFromPrefix('start')) {
$request->start_date = $date;
} else {
$validator->errors()
->add('start_year', 'Invalid starting date and time');
}
if ($date = $this->getCarbonInstanceFromPrefix('finish')) {
$request->finish_year = $date;
} else {
$validator->errors()
->add('finish_year', 'Invalid finish date and time');
}
});
}
/**
* Retrieve carbon instance from current request, using prefix
*
* #param string $prefix
*
* #return Carbon|null
*/
protected function getCarbonInstanceFromPrefix($prefix = '')
{
try {
$date = Carbon::create(
$request->get($prefix . '_year'),
$request->get($prefix . '_month'),
$request->get($prefix . '_day')
);
$date->setTimeFromTimeString( $request->get($prefix . '_time') );
return $date;
} catch (\Exception $e) {
return null;
}
}
Quick Explanation
FormRequest essentially extends from Illuminate\Foundation\Http\FormRequest and can override the method where instance of Validator is created. By creating your custom validator, you can attach after() event to both validate each date inputs, and also assign additional parameter to request in one go.

Laravel validation with lang for input names

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.

Categories