i have made profile update page , if user's account_type = 1 i mustn't use tax_number , company_name and tax_administration but user's account_type = 1 i must use like this validate :
for example 'tax_number' => 'required|max:10'
how can i do it the short way ?
may you help me ?
My Code :
<?php
namespace App\Http\Requests;
use App\Models\User;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class ProfileRequest 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(User $user)
{
if ( $this->isMethod('POST') ) {
return [
'name' => 'required|min:2|max:100',
'surname' => 'required|min:2|max:100',
'email' => ['required','min:6','max:50',Rule::unique('users', 'email')->ignore(auth()->id())],
'phone' => 'required|min:6|max:14',
'image' => 'sometimes|nullable|image|mimes:jpeg,png,jpg|max:5120',
'id_no' => 'required|max:16',
'address' => 'required|min:6|max:250',
'country' => 'required|max:100',
'city' => 'required|max:100',
'county' => 'required|max:100',
'gender' => 'required',
'tax_number' => 'required|max:10|min:10',
'compamy_name' => 'required|max:100|min:2',
'tax_administration' => 'required|max:200',
];
}
}
public function messages()
{
return [
'name.required' => 'İsim Zorunludur.',
'name.max' => 'İsim Maksimum 100 Karakter Olmalıdır.',
'surname.required' => 'Soyisim Zorunludur.',
'surname.max' => 'Soyisim Maksimum 100 Karakter Olmalıdır.',
'email.required' => 'Email Zorunludur.',
'email.max' => 'Email Maksimum 50 Karakter İçermelidir.',
'email.unique' => 'Email Daha Önce Kullanılmıştır.',
'password.required' => 'Şifre Zorunludur.',
'password.max' => 'Şifre Maksimum 12 Karakter Olmalıdır.',
'password.confirmed' => 'Şifreler Birbiriyle Uyuşmamaktadır.',
'phone.required' => 'Telefon Zorunludur.',
'phone.max' => 'Telefon Maksimum 15 Karakter Olmalıdır.',
'image.max' => 'Resim Maksimum 2 MB Boyutunda Olmalıdır.',
'image.mimes' => 'Resim JPEG , JPG ve PNG Formatında Olmalıdır.',
'image.image' => 'Resim Bir Fotoğraf Olmalıdır.',
'id_no.required' => 'Vatandaşlık Numarası Zorunludur.',
'id_no.max' => 'Vatandaşlık Numarası Maksimum 16 Karakter Olmalıdır.',
'address.required' => 'Adres Zorunludur.',
'address.max' => 'Adres Maksimum 250 Karakter Olmalıdır.',
'country.required' => 'Ülke Zorunludur.',
'country.max' => 'Ülke Maksimum 100 Karakter Olmalıdır.',
'county.required' => 'Şehir Zorunludur.',
'county.max' => 'Şehir Maksimum 100 Karakter Olmalıdır.',
'gender.required' => 'Cinsiyet Zorunludur.',
'tax_number.required' => 'Vergi Numarası Zorunludur.',
];
}
}
Thanks in advance.
public function rules(User $user)
{
$rules = [
// general rules
];
if (1 === $user->account_type) {
// add rules for account_type = 1
// e.g.
$rules['tax_number'] = 'required|max:10';
} else {
// add rules
}
return $rules;
}
Related
I need your help for a project Im doing at the moment.
I am using Laravel for programming and Im getting this error: 'Call to a member function validate() on array'
This is my store method
public function store()
{
$data = $this->check();
switch ($data) {
case (0):
return redirect()->back()->with('error', 'Dieses Produkt ist nicht vorhanden');
case (1):
return redirect()->back()->with('error', 'Das Produkt mit dieser Liefer-Nummer ist bereits vorhanden');
default:
Product::create($data)->save();
return redirect('/');
}
}
this is the check method
public function check()
{
$i = 0;
foreach(Validation::all() as $valid)
{
$validation[$i] = [
'id' => $valid->id,
'Produkt' => $valid->Produkt,
'PHmax' => $valid->PHmax,
'PHmin' => $valid->PHmin,
'Wassermax' => $valid->Wassermax,
'Wassermin' => $valid->Wassermin,
'Dichtemax' => $valid->Dichtemax,
'Dichtemin' => $valid->Dichtemin,
];
$i = $i + 1;
}
$data = [
'LieferNr' => request()->LieferNr,
'Produkt' => request()->Produkt,
'PH' => request()->PH,
'Wasser' => request()->Wasser,
'Dichte' => request()->Dichte,
'Bearbeiter' => request()->Bearbeiter,
];
$bigdata = Product::all();
foreach(Validation::all() as $valid){
foreach($bigdata as $bigdata){
if($data['LieferNr'] == $bigdata->LieferNr){
return 1;
}
}
if(in_array($data['Produkt'], $validation[0]) || in_array($data['Produkt'], $validation[1] ))
{
$PHmax = $valid->PHmax;
$PHmin = $valid->PHmin;
$Wassermax = $valid->Wassermax;
$Wassermin = $valid->Wassermin;
$Dichtemax = $valid->Dichtemax;
$Dichtemin = $valid->Dichtemin;
return $data->validate([
'LieferNr' => ['required', 'min:5', 'max:5'],
'Produkt' => ['required'],
'PH' => ['required', 'numeric', "min:$PHmin", "max:$PHmax"],
'Wasser' => "required|numeric|min:$Wassermin|max:$Wassermax",
'Dichte' => "required|numeric|min:$Dichtemin|max:$Dichtemax",
'Bearbeiter' => ['required'],
]);
}
else
{
return 0;
}
}
}
The error occurs when i do $data->validate(...)
I am quite new to Laravel and i would be happy if you can help me :)
I see your problem
It is because you are calling validate on array $data
return $data->validate([
'LieferNr' => ['required', 'min:5', 'max:5'],
'Produkt' => ['required'],
'PH' => ['required', 'numeric', "min:$PHmin", "max:$PHmax"],
'Wasser' => "required|numeric|min:$Wassermin|max:$Wassermax",
'Dichte' => "required|numeric|min:$Dichtemin|max:$Dichtemax",
'Bearbeiter' => ['required'],
]);
Instead, do following
use Illuminate\Support\Facades\Validator;
$validator = Validator::make($data, [
'LieferNr' => ['required', 'min:5', 'max:5'],
'Produkt' => ['required'],
'PH' => ['required', 'numeric', "min:$PHmin", "max:$PHmax"],
'Wasser' => "required|numeric|min:$Wassermin|max:$Wassermax",
'Dichte' => "required|numeric|min:$Dichtemin|max:$Dichtemax",
'Bearbeiter' => ['required'],
]);
if($validator->fails()){
return 0;
}
I use the Request validation but I don't get message from request. Look my code and see my mistake. Only important is store function which work good if all fields is fullfiled but if any field not filled i don't get my custom message from request. For not filled field I don't give error just laravel home page.
This is my request file
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class CarRequest 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()
{
return [
'car_type' => 'required',
'mark' => 'required',
'model' => 'required',
'fuel' => 'required',
'circuit' => 'required',
'chassis' => 'required|numeric',
'bill_type' => 'required',
'first_registration' => 'required|date',
'km' => 'required|numeric',
'structure' => 'required',
'motor_vehicle_check' => 'required|boolean',
'warranty' => 'required|boolean',
'year' => 'required|date',
'import_vehicle' => 'required|boolean',
'know_damage' => 'required',
'car_accessories' => 'required',
'email' => 'required|email'
];
}
public function messages()
{
return [
'car_type.required' => 'A car_type is required',
'mark.required' => 'A mark is required',
'model.required' => 'A model is required',
'fuel.required' => 'A fuel is required',
'circuit.required' => 'A circuit is required',
'chassis.required' => 'A chassis is required',
'bill_type.required' => 'A bill_type is required',
'first_registration.required' => 'A first_registration is required',
'km.required' => 'A km is required',
'structure.required' => 'A structure is required',
'motor_vehicle_check.required' => 'A motor_vehicle_check is required',
'warranty.required' => 'A warranty is required',
'year.required' => 'A year is required',
'import_vehicle.required' => 'A import_vehicle is required',
'know_damage.required' => 'A know_damage is required',
'car_accessories.required' => 'A car_accessories is required',
'email.required' => 'A email is required'
];
}
}
And this is my controller code
<?php
namespace App\Http\Controllers;
use App\Car;
use App\CarImages;
use App\Http\Requests\CarRequest;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Illuminate\Support\Facades\Config;
class CarController extends Controller
{
public function index()
{
$cars = Car::with(['images'])
->orderByDesc('car.created')
->get();
return response()->json($cars, 200);
}
public function search($name){
$cars = Car::where('mark', '=' , $name)->get();
return $this->response($cars);
}
public function create()
{
//
}
public function show($id)
{
$car = School::with(['images'])->find($id);
if (!$car) {
return response()->json(['message' => 'No Car found'], 404);
}
return response()->json($car, 200);
}
public function store(CarRequest $request)
{
$car = Car::create([
'car_type' => $request->input('car_type'),
'mark' => $request->input('mark'),
'model' => $request->input('model'),
'fuel' => $request->input('fuel'),
'circuit' => $request->input('circuit'),
'chassis' => $request->input('chassis'),
'bill_type' => $request->input('bill_type'),
'first_registration' => $request->input('first_registration'),
'km' => $request->input('km'),
'structure' => $request->input('structure'),
'motor_vehicle_check' => $request->input('motor_vehicle_check'),
'warranty' => $request->input('warranty'),
'year' => $request->input('year'),
'import_vehicle' => $request->input('import_vehicle'),
'know_damage' => $request->input('know_damage'),
'car_accessories' => $request->input('car_accessories'),
'email' => $request->input('email')
]);
return response()->json([
'message' => 'Your car has been successfully added',
'car' => $car
],201);
}
public function destroy($id)
{
$car = Car::destroy($id);
return response()->json($id);
}
}
I use the Request validation but I don't get message from request.
When expecting a json response, don't forget to add this header when making your requests (client side):
Accept: Application/json // <--
If I want set in my custom message example km must be numberic , how do that in messages function?
You need to specify your message for every rule like this. Let's do it for the km validation:
MyCustomRequest.php
public function rules()
{
return [
// ...
// 'first_registration' => 'required|date',
'km' => 'required|numeric', // <---
// 'structure' => 'required',
// ...
];
}
Given that km has two validations, just add one element more in the messages() function specifying the rule you want to modify:
MyCustomRequest.php
public function messages()
{
return [
// ...
'km.required' => 'A km is required',
'km.numeric' => 'The km needs to be numeric dude!', // <---
// ...
];
}
Regarding this last subject, check the documentation.
As I see you have done all things correctly. The only you missed is a little one in your store() method :
$validator = $request->validated();
right at beginning of the method's body
For some reason I am not getting any validation errors when saving multiple records. I can grab the errors using print_r($user->errors()); but they are not automatically injected into the form like when adding a single user. According to the docs "Validating entities before saving is done automatically when using the newEntity(), newEntities()." I am not sure if there is a specific way to set up the form to make it return validation for multiple records or if you have to do special validation in the model for inputs that have indexes or what?
view:
<div class="page-wrap">
<div class="form">
<h1>Join Now</h1>
<?php
echo $this->Form->create(null, ['controller' => 'users', 'action' => 'addMultiple']);
echo $this->Form->input('1.full_name');
echo $this->Form->input('1.username');
echo $this->Form->input('1.email');
echo $this->Form->input('1.password');
echo $this->Form->input('1.password_confirmation', array('type' => 'password'));
if ($current_user['role'] === 1 && isset($logged_in)) {
echo $this->Form->input('1.role', ['type' => 'select', 'options' => ['1' => 'Admin', '2' => 'Editor', '3' => 'Author', '4' => 'Reader'], 'default' => '4']);
}
echo $this->Form->input('2.full_name');
echo $this->Form->input('2.username');
echo $this->Form->input('2.email');
echo $this->Form->input('2.password');
echo $this->Form->input('2.password_confirmation', array('type' => 'password'));
if ($current_user['role'] === 1 && isset($logged_in)) {
echo $this->Form->input('2.role', ['type' => 'select', 'options' => ['1' => 'Admin', '2' => 'Editor', '3' => 'Author', '4' => 'Reader'], 'default' => '4']);
}
echo $this->Form->button(__('Sign Up'));
echo $this->Form->end();
?>
</div>
</div>
Controller:
public function addMultiple()
{
$users = $this->Users->newEntities($this->request->data());
if ($this->request->is('post')) {
foreach($users as $user) {
if( empty($this->request->session()->read('Auth.User')) || $this->request->session()->read('Auth.User.role') !== 1 ) {
$user->role = 4;
}
if ($this->Users->save($user)) {
$this->Flash->success(__('You have been added.'));
} else {
$this->Flash->error(__('You could not be added. Please, try again.'));
}
}
}
}
Table:
public function initialize(array $config)
{
parent::initialize($config);
$this->table('users');
$this->displayField('id');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->hasMany('MembershipOrders', [
'foreignKey' => 'user_id',
'joinType' => 'INNER'
]);
$this->hasMany('MembershipOrders', [
'foreignKey' => 'affiliate_token',
'joinType' => 'INNER'
]);
}
public function validationDefault(Validator $validator)
{
$validator
->notEmpty('full_name', 'A full name is required')
->add('full_name', 'notBlank', [
'rule' => 'notBlank',
'message' => __('A full name is required'),
]);
$validator
->notEmpty('username', 'A username is required')
->add('username', [
'notBlank' => [
'rule' => 'notBlank',
'message' => __('A username is required'),
]
]);
$validator
->notEmpty('email', 'An email is required')
->add('email', [
'notBlank' => [
'rule' => 'notBlank',
'message' => __('A full name is required'),
],
'unique' => [
'rule' => 'validateUnique',
'provider' => 'table',
'message' => __('That email has already been used.'),
]
]);
$validator
->notEmpty('old_password', 'You must enter your old password is required')
->add('old_password', 'notBlank', [
'rule' => 'notBlank',
'message' => __('Your old password is required'),
]);
$validator
->notEmpty('password', 'A password is required')
->add('password', 'notBlank', [
'rule' => 'notBlank',
'message' => __('A full name is required'),
]);
$validator
->notEmpty('password_confirmation', 'Password confirmation is required')
->add('password_confirmation',
'comareWith', [
'rule' => ['compareWith', 'password'],
'message' => 'Passwords do not match.'
]);
$validator
->notEmpty('role', 'A role is required')
->add('role', 'inList', [
'rule' => ['inList', ['1', '2', '3', '4']],
'message' => 'Please enter a valid role'
]);
return $validator;
}
You can use 'addNestedMany()' : http://book.cakephp.org/3.0/en/core-libraries/validation.html#nesting-validators
You have to pass the entity object to the Form->create(... function, instead of passing nullas the following:
echo $this->Form->create($user, .....
This is my model Riders:
<?php
namespace backend\models;
use Yii;
class Riders extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'riders';
}
public function rules()
{
return [
[['cagories_category_id', 'rider_firstname', 'rider_no_tlpn', 'rider_ucinumber', 'countries_id', 'rider_province', 'rider_city', 'rider_dateofbirth', 'rider_gender'], 'required'],
[['user_id', 'countries_id'], 'integer'],
[['rider_dateofbirth', 'cagories_category_id'], 'safe'],
[['rider_gender', 'rider_status'], 'string'],
[['rider_firstname', 'rider_lastname', 'rider_nickname', 'rider_province', 'rider_city'], 'string', 'max' => 45],
[['rider_email', 'rider_sponsor', 'rider_birthcertificate_url', 'rider_parental_consent_url'], 'string', 'max' => 100],
[['rider_no_tlpn'], 'string', 'max' => 15],
[['rider_ucinumber'], 'string', 'max' => 11]
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'rider_id' => 'rider_id',
'cagories_category_id' => 'Category Name',
'user_id' => 'User Team',
'rider_firstname' => 'Rider Firstname',
'rider_lastname' => 'Rider Lastname',
'rider_nickname' => 'Rider Nickname',
'rider_email' => 'Rider Email',
'rider_no_tlpn' => 'Rider No Tlpn',
'rider_ucinumber' => 'Rider Ucinumber',
'countries_id' => 'Country Name',
'rider_province' => 'Rider Province',
'rider_city' => 'Rider City',
'rider_sponsor' => 'Rider Sponsor',
'rider_dateofbirth' => 'Rider Dateofbirth',
'rider_gender' => 'Rider Gender',
'rider_birthcertificate_url' => 'Rider Birthcertificate Url',
'rider_parental_consent_url' => 'Rider Parental Consent Url',
'rider_status' => 'Rider Status',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getRegistrations()
{
return $this->hasMany(Registrations::className(), ['riders_rider_id' => 'rider_id']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getCagoriesCategory()
{
return $this->hasOne(Categories::className(), ['category_id' => 'cagories_category_id']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'user_id']) -> from(user::tableName() . 'ud');
}
/**
* #return \yii\db\ActiveQuery
*/
public function getUserDesc()
{
return $this->hasOne(UserDesc::className(), ['desc_id' => 'user_id']) -> from(['ud' => userDesc::tableName()]);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getCountries()
{
return $this->hasOne(Countries::className(), ['id' => 'countries_id']);
}
}
This my Controller actionIndex:
$searchModel = new RidersSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$totalCount = Yii::$app->db->createCommand('SELECT COUNT(*) FROM riders WHERE user_id = :user_id',
[':user_id' => Yii::$app->user->identity->id])->queryScalar();
$dataProvider = new SqlDataProvider([
'sql' => 'SELECT * FROM riders WHERE user_id = :user_id',
'params' => [':user_id' => Yii::$app->user->identity->id],
'totalCount' => $totalCount,
'key' => 'rider_id',
'pagination' => [
'pageSize' => 10,
],
'sort' => [
'attributes' => [
'cagories_category_id',
'rider_id',
'rider_firstname',
'rider_email:email',
'rider_no_tlpn',
]
]
]);
$models = $dataProvider->getModels();
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
This is my view index:
<?= GridView::widget([
'dataProvider' => $dataProvider,
// 'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'label' => 'Category Name',
'attribute'=>'cagories_category_id',
'value' => 'cagoriesCategory.category_name', <---Can't work again
],
[
'label' => 'BIB',
'attribute'=>'rider_id',
],
'rider_firstname',
'rider_email:email',
'rider_no_tlpn',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
Before I use sqldataprovider, it can call from model function have relation, after use sqldataprovider can't work. How to get relation table value???
then before use it, i can to merge rider_firstname and rider_lastname with return $model->rider_firstname . " " . rider_lastname; after use sqldataprovider can't work too??
SqlDataProvider returns data as an array so You can't able to access related object with $dataProvider->models()
either you have to use ActiveDataProvider or change your Sql of SqlDataProvider with join condition
sql='sql' => 'SELECT * FROM riders inner join '. Categories::tableName() .' as c on c.category_id=riders.cagories_category_id WHERE user_id = :user_id'
While testing, system always returning me required customized message. For example i want the validator to check if the passwords match. But error message shows me "Password Validation is required" instead of "Passwords does not match".
Here is my validation function and rules.
protected function getRegisterValidator()
{
$message = array(
'same' => ':attribute ve :other tekrarları birbirini tutmalı.',
'between' => ':attribute en az :min en fazla :max karakterden oluşabilir.',
'min' => ':attribute en az :min karakter içermelidir.',
'max' => ':attribute maksimum :max karakterden oluşabilir.',
'alpha_num' => 'girilen :attribute alfanumerik olmalıdır.',
'unique' => 'Bu :attribute ile zaten önceden kayıt olunmuş.',
'email' => ':attribute geçerli bir mail adresi değil.',
'captcha' => 'Doğrulama karakterlerini yanlış girdiniz.',
'required' => ':attribute alanı boş olamaz.'
);
return Validator::make(Input::all(),array(
'Kurum' => 'required',
'Ad' => 'required',
'Soyad' => 'required',
'Görev' => 'required',
'Email' => 'required|email|unique:user',
'Email Tekrarı'=> 'required|same:Email',
'Şifre' => 'required|between:8,12',
'Şifre Tekrarı' => 'required|same:Şifre',
'Doğrulama' => 'captcha|required'
), $message);
}
Thanks in advance.
try this
$message = [
'şifre.required' => 'Şifre alanı boş bırakılamaz',
'şifre.same' => 'Şifre alanları eşleşmiyor',
];
"şifre" is input name.
I found the solution. The space between field names like "Şifre Tekrarı" or "Email Tekrarı" leading an error and laravel validator cannot compare the values between "Şifre" and "Şifre Tekrarı" fields.
The solution is setting field names without spaces in your HTML file (or blade), and it does not involve anything with Turkish characters.
protected function getRegisterValidator()
{
$message = array(
'same' => ':attribute ve :other tekrarları birbirini tutmalı.',
'between' => ':attribute en az :min en fazla :max karakterden oluşabilir.',
'min' => ':attribute en az :min karakter içermelidir.',
'max' => ':attribute maksimum :max karakterden oluşabilir.',
'alpha_num' => 'girilen :attribute alfanumerik olmalıdır.',
'unique' => 'Bu :attribute ile zaten önceden kayıt olunmuş.',
'email' => ':attribute geçerli bir mail adresi değil.',
'captcha' => 'Doğrulama karakterlerini yanlış girdiniz.',
'required' => ':attribute alanı boş olamaz.'
);
return Validator::make(Input::all(),array(
'Kurum' => 'required|min:3|max:60',
'Ad' => 'required|min:3|max:30',
'Soyad' => 'required|min:3|max:30',
'Görev' => 'required|min:1|max:60',
'Email' => 'required|email|unique:user|same:Email_Tekrarı',
'Email_Tekrarı'=> 'required',
'Şifre' => 'required|between:8,12|same:Şifre_Tekrarı',
'Şifre_Tekrarı' => 'required',
'Doğrulama' => 'captcha|required'
), $message);
}
Important note :
If you are showing error messages with these field names like "Email_Tekrarı" (i mean there is a _ character included) the error message ignores "_" character and shows error message as like "Email Tekrarı field is required".
Works smoothly.
Thank you for your patience.