2

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 ?

6
  • I don't understand your question, could you elaborate what you want to do?
    – Remul
    Feb 6, 2020 at 9:11
  • I want to query on code case insensitive. like: I will write where('code', '=', $inputCode) and it will search insensitively. any way to manipulate eloquent model?
    – tohasanali
    Feb 6, 2020 at 9:23
  • 1
    Did you try your query? If you are using mysql it should be case insensitive.
    – Remul
    Feb 6, 2020 at 9:29
  • well it works on mysql. whatif I want to check unique validation on that code field?
    – tohasanali
    Feb 6, 2020 at 9:48
  • 1
    Just tested it with the unique rule and it works for me, it is case insensitive.
    – Remul
    Feb 6, 2020 at 9:56

1 Answer 1

1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.