For this rule I am getting an error syntax error, unexpected '.', expecting ')'
public static $rules = array(
'first_name' => 'required|alpha-dash',
'last_name' => ' required|alpha-dash',
'media_release' => 'required|boolean',
'birthday' => 'before:' . date('Y-m-d')
);
I can't figure out why this won't work. I'm running Laravel 4.2.12
try this:
'birthday' => 'date_format:Y-m-d|before:today',
bye
Just for future users:
Laravel 5 using form requests:
'birthday' => 'before:today', // Doesn't accept today date
'birthday' => 'before:tomorrow', // Accept today date
You can't use a function when defining class member variables. You'll have to move that part to your constructor:
<?php
class Foo {
public static $rules = array(
'first_name' => 'required|alpha-dash',
'last_name' => ' required|alpha-dash',
'media_release' => 'required|boolean'
);
public function __construct()
{
self::$rules['birthday'] = 'before:' . date('Y-m-d');
}
EDIT:
The above solution may not work in Laravel. You may have to use a "Custom Validator" instead:
http://laravel.com/docs/4.2/validation#custom-validation-rules
UPDATE:
Looks like Laravel 5 introduced a better solution. See the answer by Fernando, below.
I recommend you to add a before and an after statement for birthdays.
'birthday' => date_format:Y-m-d|before:today|after:1900-01-01
You'll avoid entries like 1111-1-1 because no one alive was born before the year 1900.
Related
I'm trying to seed using factories in Laravel 5.2
My code dies in the User factory:
$factory->define(App\User::class, function (Faker\Generator $faker) {
$countries = Countries::all()->pluck('id')->toArray();
return [
'name' => $faker->name,
'email' => $faker->email,
'password' => bcrypt(str_random(10)),
'grade_id' => $faker->numberBetween(1, 5),
'country_id' => $faker->randomElement($countries),
'city' => $faker->city,
'latitude' => $faker->latitude,
'longitude' => $faker->longitude,
'role_id' => $faker->numberBetween(1, 3),
'verified' => true,
'remember_token' => str_random(10),
'provider' => '',
'provider_id' => str_random(5)
];
});
Giving me this error:
A four digit year could not be found Data missing
I found the cause, but don't know how to fix it.
When I call the factory, I call it like that:
factory(User::class)->create(['role_id',2]);
If I call it like that:
factory(User::class)->create();
I get no more error.
But I really need to seed different kind of users...
Any idea???
have you tried using key value array in the create method:
factory(User::class)->create(['role_id' => 2]);
I might be late to the party, I was having the same problem and it turns out its because I provided a key without a value in the array returned.
get rid of 'provider' => ''.
As to the cause of the problem i really don't know but it has something to do with Carbon
I had the same issue when using mass assignment and it turned I had forgotten to wrap my array of inputs in the request helper function
That is I had
Model::create([form inputs]);
Instead of
Model::create(request([form inputs]);
Just incase someone comes across it.
I recently encounter the same problem, lately I found out that the only problem is I put an invalid value to the timestamp column type.
In my case I have column email_verified_at [timestamp]. I miss understood I put a string like company#example.com instead of date values, it should be now().
In my registration store function which is called after the user has typed in valid information I have a default array that is converted to JSON and stored in my DB with the user. All of a sudden I am getting the error:
Illegal Offset Type (line 50)
which the last object of my first array (it is multi dimensional). I deleted the object to see if the error was specific to that object but the error still persists. I don't understand where this error is coming from because I did't change anything in or around the registration system for a while.
This is the store() function being called after the registration form is submitted:
public function store()
{
$input = Input::only('username', 'email', 'password', 'password_confirmation');
$this->registrationForm->validate($input);
$user = User::create($input);
$arr = array(
[1] => array(
'name' => 'Apple',
'time' => '2:00 am',
'date' => '10.26.96',
'symptom' => false,),
[2] =>array(
'name' => 'Banana',
'time' => '3:56 pm',
'date' => '10.26.96',
'symptom' => false,),
[3] =>array(
'name' => Input::get('symptom'),
'time' => '4:45 pm',
'date' => '10.26.96',
'symptom' => true,
));
$user->json = json_encode($arr);
$user->save();
Auth::login($user);
return Redirect::home();
}
The error occurs in "line 50" which is in the last object of the first array 'symptom' => false,),
I have absolultley no idea how this happened. I even used time machine to load my project from a few days ago when I am certain it was fully functional and the error is still there. I will appreciate any help, please let me know if more information is needed.
array initialization syntax only accept key names as a plain scalar values, thus having ['foo'] syntax is incorrect in this case.
Laravel 4.1. I want to update a city, check the rules and it fails on unique check.
Rules:
public static $rules = [
'name' => 'required|alpha_dash|unique:cities',
'slug' => 'alpha_dash|unique:cities',
'seo_title' => 'required|max:60|unique:cities',
'seo_description' => 'required|max:160|unique:cities',
'rank' => 'integer',
'visible' => 'integer'
];
I know, I can smth like:
'name' => 'required|alpha_dash|unique:cities, name, ##',
where ## - id, but I cant dynamically set id to updated one.
'name' => "required|alpha_dash|unique:cities, name, $id", // doesnt work
'name' => "required|alpha_dash|unique:cities, name, $this->id", // doesnt work
Is there any way to do it normally ?
You can do it in separate ways.
An easy way is to use different rules based on different actions . When you will create the model, you will use the rules that you currently have.
When you will update the model, you will change the unique:cities to exists:cities
I usually do this with a validation service.
You create a base abstract Validator in services/ , which has a passes() function.
For each model, you create a ModelValidator , in your case CityValidator. Where you put your rules like :
public static $rules = [
'new'=>[
'name' => 'required|alpha_dash|unique:cities',
'slug' => 'alpha_dash|unique:cities',
'seo_title' => 'required|max:60|unique:cities',
'seo_description' => 'required|max:160|unique:cities',
'rank' => 'integer',
'visible' => 'integer'],
'edit'=>[
'name' => 'required|alpha_dash|exists:cities',
'slug' => 'alpha_dash|unique:cities',
'seo_title' => 'required|max:60|exists:cities',
'seo_description' => 'required|max:160|exists:cities',
'rank' => 'integer',
'visible' => 'integer'
]
];
The 3rd argument accepts a value to be ignored... If you want to do a WHERE clause, do it like:
'name' => array("required", "alpha_dash", "unique:cities,name,null,id,id,$this->id"...
The docs says:
Adding Additional Where Clauses
You may also specify more conditions that will be added as "where"
clauses to the query:
'email' => 'unique:users,email_address,NULL,id,account_id,1'
In the rule above, only rows with an account_id of 1 would be included in the unique check.
Learn by example:
email => unique:users,email_address,id,NULL,field_1,value_1,field_2,value_2,field_x,value_x
Generates the query:
SELECT
count(*) AS AGGREGATE
FROM
`entries`
WHERE
`email_address` = ?
AND `id` <> NULL
AND `field_1` = `value_1`
AND `field_2` = `value_2`
AND `field_x` = `value_x`
I found an elegant-ish way to do this using fadion/ValidatorAssistant:
<?php
use Fadion\ValidatorAssistant\ValidatorAssistant;
class CityValidator extends ValidatorAssistant {
// standard rules
public static $rules = [
'name' => 'required|alpha_dash',
'slug' => 'alpha_dash',
'seo_title' => 'required|max:60',
'seo_description' => 'required|max:160',
];
// some preparation before validation
protected function before()
{
// Inject the given city id into the unique rules
$this->rules['name'] .= 'unique:cities,name,' . $this->inputs['id'];
$this->rules['slug'] .= 'unique:cities,slug,' . $this->inputs['id'];
$this->rules['seo_title'] .= 'unique:cities,seo_title,' . $this->inputs['id'];
$this->rules['seo_description'] .= 'unique:cities,seo_description,' . $this->inputs['id'];
}
There's almost certainly a more elegant way to do this when you need several fields to be unique database-wide, but the above works very well for times when you only need one part to be unique.
I've seen a few example here on stack but they don't seem to cover this scenario.
I'm attempting this;
$flight_range = array(
array('range' => range(1,50), 'service' => 'Long Haul'),
array('range' => range(51,54), 'service' => 'Short Haul'),
....
);
but PHP won't let me. It returns;
Parse error: syntax error, unexpected '(', expecting ')' on line 02
This does not work either;
array(range(1,50), range(51,54) ...
The problem is with trying to assign a value of range().
I have 20+ sets of range values to assign.
Can anyone suggest an easy method for achieving these sorts of array values?
EDIT;
haike00, Jack and Sean are right.
Maybe my question should be how do i make $flight_range a member variable of a class;
private $flight_range = array(array('range' => range(1,50), 'service' => 'Long Haul'));
What is the problem with doing this in your constructor?
class MyClass {
private $flight_range;
public function __construct() {
$this->flight_range = array(
array(
'range' => range( 1, 50 ),
'service' => 'Long Haul'
)
);
}
}
Its working fine on my end.
$flight_range = array(
array('range' => range(1,50) , 'service' => 'Long Haul'), array('range' => range(51,54),'service' => 'Short Haul'));
print_r($flight_range);
Just copy and paste above code and run it.
Using the latest CakePHP build 1.3.6.
I'm writing a custom datasource for a external REST API. I've got all the read functionality working beautifully. I'm struggling with the Model::save & Model::create.
According to the documentation, the below methods must be implemented (see below and notice it does not mention calculate). These are all implemented. However, I was getting an "Fatal error: Call to undefined method ApiSource::calculate()". So I implemented the ApiSource::calculate() method.
describe($model) listSources() At
least one of:
create($model, $fields = array(), $values = array())
read($model, $queryData = array())
update($model, $fields = array(), $values = array())
delete($model, $id
= null)
public function calculate(&$model, $func, $params = array())
{
pr($model->data); // POST data
pr($func); // count
pr($params); // empty
return '__'.$func; // returning __count;
}
If make a call from my model
$this->save($this->data)
It is calling calculate, but none of the other implemented methods. I would expect it to either call ApiSource::create() or ApiSource::update()
Any thoughts or suggustions?
Leo, you tipped me in the right direction. The answer was in the model that was using the custom datasource. That model MUST define your _schema.
class User extends AppModel
{
public $name = 'User';
public $useDbConfig = 'cvs';
public $useTable = false;
public $_schema = array(
'firstName' => array(
'type' => 'string',
'length' => 30
),
'lastName' => array(
'type' => 'string',
'length' => 30
),
'email' => array(
'type' => 'string',
'length' => 50
),
'password' => array(
'type' => 'string',
'length' => 20
)
);
...
}
I'm guessing that if you implement a describe() method in the custom datasource that will solve the problem too. In this case it needed to be predefined to authorize the saves and/or creation.
From the API: http://api13.cakephp.org/class/dbo-source#method-DboSourcecalculate
"Returns an SQL calculation, i.e. COUNT() or MAX()"
A quick search in ~/cake finds 20 matches in 8 files. One of those is the definition in dbo_source.php
The other seven are:
dbo_source.test.php
code_coverage_manager.test.php
code_coverage_manager.php
dbo_db2.php
model.php
tree.php
containable.php
Without delving too deeply into this, I suspect your problem lies in Model::save
You'll probably have to define a calculate method to suit the structure of your custom datasource because Cake won't know how to do that.