Laravel Rule::unique not working as expected - laravel

This is my migration:
Schema::create('coupons', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name')->unique();
});
And this is my custom request:
use Illuminate\Validation\Rule;
public function rules()
{
return [
'name' => [
'required', 'string',
Rule::unique('coupons')
->where(function ($q) {
$q->where('name', 'OFFER-2020');
})
]
}
I am trying to block requests where coupon name field already exists in database table. Since OFFER-2020 row already exists in coupons table, it should block the request instead it passes validation.
Update
My input was OFFER 2020. And OFFER-2020 is value after transformation. I thought laravel was checking unique with OFFER-2020. Instead it was checking with both OFFER 2020 and OFFER-2020 by a and query. And that's why my unique was not working.

If you input is OFFER-2020. You will only need to set the correct column name which is the second parameter of the unique rules. This will check the coupons table, for a row with the same name as the input.
Rule::unique('coupons', 'name')
To make your input slugified, you can utilise the form request method prepareForValidation(), this can transform your data.
function prepareForValidation() {
$this->merge(['name' => Str::slug($this->get('name'))]);
}
Why did the previous version fail? As you can see here in the Unique class. If you do not provide a column it will default to id. So you previous query would end up looking something similar to this.
select * from coupons where id = 'OFFER-2020' and name = 'OFFER-2020'

Related

How do I return the ID field in a related table in Laravel request

I have two related tables and I want to return all fields including the ID (key) field. My query below returns all fields except the ID. how do I return the ID field from one of the tables?
'programmes' => ProgrammeInstances::with('programmes')->get(),
the query below returns Unknown column 'programmes.programme_title' as it is looking for it in the table 'programme_instances'
'programmes' => ProgrammeInstances::with('programmes')->select('programmes.programme_title', 'programmeInstances.id', 'programmeInstances.name', 'programmeInstances.year')->get(),
Laravel provides multiple relationships, one of these is the hasMany() relationship which should return a collection where a User hasMany rows inside of your database
For example, inside your User model :
public function programmes() {
return $this->hasMany(Program::class);
}
Now in your controller, you can do :
public function edit($id) {
$programmes = User::find($id)->with('programmes')->get();
return view('user.edit')->with('programmes', $programmes);
}
And then you can loop over it inside your view
#forelse($programmes->programmes as $program)
// provide the data
#empty
// the user doesn’t have any programmes
#endforelse
a solution i found below - still not sure why ID isnt automatically returned when i get all fields, but works when i specify individual fields:
'programmes' => ProgrammeInstances::with('programmes')
->get()
->transform(fn ($prog) => [
'programme_title' => $prog->programmes->programme_title,
'id' => $prog->id,
'name' => $prog->name,
'year' => $prog->year,
]),

Laravel, unique columns

I need validate if field already exist, throws error, but with this code no errors are triggered
Laravel 7
table: departamento
column: id int incremental
column: departamento varchar(150)
column: idPais int
store method
$this->validate($request, ['departamento' => Rule::unique('departamento','idPais')->where('departamento',$request->depto)->where('idPais',$request->pais)]);
Try with this too
$rules = [
'depto' => [Rule::unique('departamento')->where(function ($query) use ($request) {
return $query->where('departamento','=', $request->depto)->where('idPais','=', $request->pais);
}),]
];
$this->validate($request,$rules);
with this code, throws this error
$rules = [
'depto' => [Rule::unique('departamento')->where(function ($query) use ($request) {
return $query->where('departamento','=', $request->depto)->where('idPais','=', $request->pais);
}),]
];
$this->validate($request,$rules);
Thanks!!!
EDIT:
My bad, I need check two fields , departamento and idPais, thanks.
This is happening because of your field name. The unique rule will try to find a record with that column name set to the request value (in your case, depto, but your column name is departamento). When you are customising the query you are not overriding it, you are adding on top of this default behaviour. From the laravel docs:
By default, the unique rule will check the uniqueness of the column matching the name of the attribute being validated. However, you may pass a different column name as the second argument to the unique method:
With that in mind, you could either change the unique rule to set the column to departamento and not depto as per below, or change the request to send departamento attribute instead of depto:
$rules = [
'depto' => [Rule::unique('departamento', 'departamento')->where(function ($query) use ($request) {
return $query->where('idPais','=', $request->pais);
}),]
];

exclude certain records from laravel scout/algolia

I am using laravel scout to upload records for searching in algolia. I have added the searchable trait to my model, and everything is working fine.
There is a case now where I don't want to add certain records to my index if they have set status I.E UNPUBLISHED.
is there away I can evaluate the status field and decide if I want the model to be uploaded to the index?
Just use $model_name->unsearchable() to remove it from your Algolia index.
See "Removing Records" in the documentation for more details: https://laravel.com/docs/5.3/scout#removing-records
You can use method toSearchableData() and in case the status is Unpublished, just return empty array and the record will be skipped.
Otherwise just return $this->toArray().
It will do the trick.
Say we have a Post model, with a boolean published attribute, and a model factory to seed our table as follows:
$factory->define(App\Post::class, function (Faker\Generator $faker) {
$tile = $faker->realText(50);
$date = $faker->dateTime;
return [
'title' => $tile,
'body' => $faker->realText(500),
'published' => $faker->boolean(80),
'created_at' => $date,
'updated_at' => $date
];
});
Let's say we will seed 10 records.
public function run()
{
factory(App\Article::class, 10)->create();
}
If we tried to exclude unpublished records within the toSearchableArray() method, as suggested:
public function toSearchableArray()
{
if (! $this->published) {
return[];
}
// ...
}
When seeding the posts table, instead of ignoring unpublished records by returning an empty array, scout will keep asking the model factory for a published model.
For example, if two of the seeded records were randomly unpublished, scout would index all 10 records (instead of 8) anyway, replacing the unpublished ones by a new model factory (with a published set attribute). Thus causing to have two inexistent (on our table) records in the algolia index. Quite confusing.
The "neatest" way around this I could come up with, was to listen to the saved/updated events (saving/updating won't cut it) in the model's boot method.
protected static function boot()
{
static::saved(function ($model) {
if (! $model->published) {
$model->unsearchable();
}
});
static::updated(function ($model) {
if (! $model->published) {
$model->unsearchable();
}
});
parent::boot();
}
Check out this question. This problem has been solved in the new version of Scout
Adding Index to Laravel Scout Conditionally (Algolia)

Laravel 5 eloquent: select specific column of relation

I have 2 models: Author and Post
In my Post model, I have an author function (One To Many (Inverse)):
public function author()
{
return $this->belongsTo('App\Author', 'author_id');
}
Now I want to export to Excel the following information:
id | title | author name
This is what I tried:
$posts = Post::with(array(
'author' => function ($query) {
$query->select('name');
}))->select('id', 'title')->get();
What I get is an empty author's name column.
What do I wrong?
Since Laravel 5.5 you can use eager loading retrieve multiple specific columns simply by using string
Post::with('author:id,name')->get()
Author::with('posts:id,author_id,title')->get()
Notice the id or foreign key (author_id) must included, or data will be null.
please try:
$posts = Post::with(['author' => function($query){
$query->select(['id','name']);
}])->get(['id','title', 'author_foreign_key_in_posts_table']);
Having that, you'll be able to get:
$posts->first()->author->name;
$posts->first()->id;
$posts->first()->title;
You may use iteration or whatever instead of first() for export.

Laravel 4: Unique Validation for Multiple Columns

I know this question has been asked earlier but i did not get relevant answer.
I want to know that how can i write a rule to check uniqueness of two columns. I have tried to write a rule like:
public $rules = array(
"event_id"=>"required",
"label"=>"required|unique:tblSection,label,event_id,$this->event_id",
"description"=>"required"
);
In my example i need to put validation so that one label could be unique for a single event id but may be used for other event id as well. For Example i want to achieve:
id event_id label description
1 1 demo testing
2 2 demo testing
In the rule defined above, somehow i need to pass current selected event_id so that it could check whether the label does not exist in the database table for selected event_id but i am getting syntax error like:
{"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException","message":"syntax error, unexpected '\"'","file":"\/var\/www\/tamvote\/app\/modules\/sections\/models\/Sections.php","line":39}}
Note: I don't want to use any package but simply checking if laravel 4 capable enough to allow to write such rules.
The answer from Mohamed Bouallegue is correct.
In your controller for the store method you do:
Model::$rules['label'] = 'required|unique:table_name,label,NULL,event_id,event_id,' .$data['event_id'];
where $data is your POST data.
And for the update method you do:
$model = Model::find($id);
Model::$rules['label'] = 'required|unique:table_name,label,NULL,event_id,event_id,'.$data['event_id'].',id,id'.$model->id;
where $data is your PUT/PATCH data, $model is the record you are editing and id is the table primary key.
I didn't try this before but I think if you get the event_Id before validating then you can do it like this:
'label' => 'unique:table_name,label,NULL,event_id,event_id,'.$eventId
//you should get the $eventId first
If you want to declare your validation rules statically you can do this as well. It's not the most efficient since it checks the database for each value.
protected $rules = [
'user_id' => 'unique_multiple:memberships,user_id,group_id',
'group_id' => 'unique_multiple:memberships,user_id,group_id',
]
/**
* Validates that two or more fields are unique
*/
Validator::extend('unique_multiple', function ($attribute, $value, $parameters, $validator)
{
//if this is for an update then don't validate
//todo: this might be an issue if we allow people to "update" one of the columns..but currently these are getting set on create only
if (isset($validator->getData()['id'])) return true;
// Get table name from first parameter
$table = array_shift($parameters);
// Build the query
$query = DB::table($table);
// Add the field conditions
foreach ($parameters as $i => $field){
$query->where($field, $validator->getData()[$field]);
}
// Validation result will be false if any rows match the combination
return ($query->count() == 0);
});
Like Sabrina Leggett mentioned, you need to create your own custom validator.
Validator::extend('uniqueEventLabel', function ($attribute, $value, $parameters, $validator) {
$count = DB::table('table_name')->where('event_id', $value)
->where('label', $parameters[0])
->count();
return $count === 0;
}, 'Your error message if validation fails.');
You can call your validator by adding the following line to your rules:
'event_id' => "uniqueEventLabel:".request("label")
If you need more fields, you could add a new where clause to the sql statement.
(Source: edcs from this answer)
As you I was looking for hours to do that but nothing worked, I test everything ... suddenly the randomness of the doc I came across this:
'email' => Rule::unique('users')->where(function ($query) {
return $query->where('account_id', 1);
})
https://laravel.com/docs/5.5/validation#rule-unique
and it works perfectly and moreover it is very flexible :)

Resources