laravel-ardent / ardent

Self-validating, secure and smart models for Laravel's Eloquent ORM
BSD 3-Clause "New" or "Revised" License
1.39k stars 211 forks source link

Best practice for validating relationships using Ardent? #174

Open JeroenVanOort opened 10 years ago

JeroenVanOort commented 10 years ago

I'm working on an application containing log messages and users. The respective models are LogMessage and User.

I can't seem to find how I should validate that each LogMessage always has a User attached using Ardent's validator. So far, I've tried two options but both don't seem to be particularly nice ones.

First of all, I could simply do some extra checks in the controller. However, this means I need a lot more code to feed back messages to the user if anything fails (which exactly what I'm trying to use Ardent for).

Second I could, using Ardent, validate the user_id field of LogMessage by making it a required integer that exists in the user table in the id field there. Going with this however, means I'd either have to do something like '$message->user_id = 42;' instead of '$message->user()->associate($user);' or I'd need to execute a forceSave() and then insert the relationship as usual (since the message doesn't have an id before saving and I therefore can't insert a relation on it) and retrieving any errors using save() when it's already too late. And, even more important, this wouldn't work at all with ManyToMany relations.

Since I've only been using Laravel recently and I'll be using it for a larger project in the near future I'd like to know how to use it properly. I hope you can help!

Jeroen

sjdaws commented 10 years ago

I created a fork/clone of Arent which does just that: https://github.com/lakedawson/vocal