How to: validate the existence of a database relationship in Laravel 4?

15,341

I have the following code in a ExchangeRate class:

/**
 * Return the validator for this exchange rate.
 * 
 * @return Illuminate\Validation\Validator A validator instance.
 */
public function getValidator()
{
    $params = array(
        'from_currency_id' => $this->from_currency_id,
        'to_currency_id'   => $this->to_currency_id,
        'valid_from'       => $this->valid_from,
        'rate'             => $this->rate,
        'organization_id'  => $this->organization_id,
    );

    $rules = array(
        'from_currency_id' => ['required', 'exists:currencies,id'],
        'to_currency_id'   => ['required', 'exists:currencies,id', 'different:from_currency_id'],
        'valid_from'       => ['required', 'date'],
        'rate'             => ['required', 'numeric', 'min:0.0'],
        'organization_id'  => ['required', 'exists:organizations,id'],
    );

    return Validator::make($params, $rules);
}

Of course, this ExchangeRate class also have the associations defined:

public function from_currency()
{
    return $this->belongsTo('Currency', 'from_currency_id');
}

public function to_currency()
{
    return $this->belongsTo('Currency', 'to_currency_id');
}

And all this glued together works like a clock:

$validator = $exchangeRate->getValidator();

if ($validator->fails())
    throw new ValidationException($validator);
Share:
15,341
koosa
Author by

koosa

Updated on June 17, 2022

Comments

  • koosa
    koosa almost 2 years

    I have a model Product that belongs to a Trend:

    class Product extends Eloquent {
    
        public function trend()
        {
          return $this->belongsTo('Trend');
        }
    
    }
    

    And as part of my validation rules I would like to check that this relationship exists, and if not trigger an error using:

    $validator = Validator::make(Input::all(), $rules, $messages);
    
    if ($validator->fails())
    {
        ... some redirection code here
    

    is called. I have tried to use the validation exists like below, but it never fires.

    $rules = array(
        'brand_name'  => 'required|min:3',
        'blurb'       => 'required',
        'link'        => 'required',
        'trend'       => 'exists:trends'
    );
    

    I have also tried a few variations on the exists method, but nothing ever seems to fire. I know that the instance I am testing on definitely doesn't have a relationship set.

    What am I doing wrong here?

    EDIT: I see now from typing this out that I am validating the input and not the models values. How would I actually validate a model instance's properties instead?

  • Rubens Mariuzzo
    Rubens Mariuzzo over 10 years
    Let me know anything then.
  • koosa
    koosa over 10 years
    I ended up using a combination of this and this method