I have been using Laravel more and more lately (full post on that coming soon) and have really been enjoying the Eloquent ORM. I plan to extend the ORM so that it includes an "upsert" method but in the short term I had a need to check for the existence of a key and then conditionally update or insert a record into the model. There are some very easy ways to do this using Fluent (also built-in to Laravel) but I wanted to stick with a completely Eloquent-based solution so here is what I came up with:
You could reduce the number of lines in that code by using the ternary operator but I find the syntax above much easier to read and better for example purposes.
In my model I have my $key set to the email column in my database which is why I am passing that to the find() method.
As I mentioned above I plan to put together a full post about Laravel soon so stay tuned!