Reputation: 934
I have a table in migrations named currency_codes
with fields (id, source, code)
.
I also have a model name CurrencyCode.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class CurrencyCode extends Model
{
protected $table = 'currency_codes';
protected $fillable = ['source', 'code'];
}
Some data from database :
+------------------+
|id |source |code |
--------------------
|1 |USA |Usd |
|2 |UAE |AED |
|3 |CHINA |cny |
|4 |opskins |OP |
|5 |MyWeb |wp |
....................
....................
What I want: Each and every action (validation, insert, search)
with this code
field will be insensitive. I can control from controller with so many lines of code. Can I do this by eloquent model ?
Upvotes: 2
Views: 2806
Reputation: 8252
Your search queries and validation rules are case insensitive when you are using mysql.
e.g.:
$query->where('code', $code)
'code' => 'unique:currency_codes,code'
If you want your codes to always be stored in uppercase you can use a mutator.
From the docs:
To define a mutator, define a setFooAttribute method on your model where Foo is the "studly" cased name of the column you wish to access. So, again, let's define a mutator for the first_name attribute. This mutator will be automatically called when we attempt to set the value of the first_name attribute on the model:
class User extends Model
{
/**
* Set the user's first name.
*
* @param string $value
* @return void
*/
public function setFirstNameAttribute($value)
{
$this->attributes['first_name'] = strtolower($value);
}
}
So in your case:
/**
* Set the currency code.
*
* @param string $value
* @return void
*/
public function setCodeAttribute($value)
{
$this->attributes['code'] = strtoupper($value);
}
Upvotes: 1