Support the ongoing development of Laravel.io →
Database Eloquent Validation

Consider the following models.

class Camp extends Model
{
    protected $fillable = ['name', 'description', 'fee', 'min_age', 'max_age'];

    public function registrations()
    {
        return $this->hasMany('App\Registration');
    }
}
class Camper extends Model
{
    protected $fillable = ['first_name', 'last_name', 'birthdate'];
    protected $dates = ['birthdate'];

    public function registrations()
    {
        return $this->hasMany('App\Registration');
    }
}
class Registration extends Model
{
    public function camp()
    {
        return $this->belongsTo('App\Camp');
    }

    public function camper()
    {
        return $this->belongsTo('App\Camper');
    }
}

My goal is to allow new Registrations to be inserted/saved only if the related Camper birthdate is logically within the Camps min_age and max_age range. What is the best way to approach this type of validation? Ideally I would like the validation mechanism to behave similarly to form validation. The request to create this Registration will only contain the Camp id and the Camper id.

Last updated 2 years ago.
0

You can create custom validation rule. You can do that within service provider, e.g. in AppServiceProvider :

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Carbon\Carbon;
use Validator;

class AppServiceProvider extends ServiceProvider
{

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Validator::extend('age_match', function($attribute, $value, $parameters, $validator) {
            $camper = \App\Models\Camper::find($parameters[0]);
            $camp   = \App\Models\Camp::find($parameters[1]);

            $now = Carbon::now();
            $age = $now->diffInYears($camper->birthdate);

            return $age >= $camp->min_age && $age <= $camp->max_age;
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {        
    }
}

Latter, validation is something like:

....
$a = $request->all();
$validator = Validator::make($a, [
        'camp_id' => 'required|numeric',
        'camper_id' => 'required|numeric|age_match:' .$a['camper_id'] . ',' . $a['camp_id'],
]);
...
Last updated 8 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

elikmiller elikmiller Joined 11 May 2016

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.