I have model Meal which can contain model Ingredient and Ingredient has a lot of properties...
I have all ingredient in DB and also some meals....
But I want to create new meal but without storing it in DB.
so something like:
$meal = new Meal;
$meal->ingredients()->attach(5);
where 5 is id of ingredient in DB.
However this will fail because $meal is not stored in DB yet and attach() function trying to create a new record in meal_ingredient table....
So is there any way how to create "offline" model and connect it with "online" data?
Thanks
You should treat the object like a collection to work "offline". And remember to build the objects it they doesn't exist.
$ingredient = new Ingredient;
$ingredient->id = 5;
$meal = new Meal;
$meal->ingredients->add($ingredient);
So neither the Meal nor the Ingredient number 5 has to exists in DB.
So is there any way how to create "offline" model and connect it with "online" data?
Yes, you can use a sort of Laravel Model without a Database (offline as you phrase it). Please refer to jenssegers/laravel-model. Basically it's a class implementing ArrayAccess
, ArrayableInterface
, JsonableInterface
with some states and behaviours as needed.
Yes, there should be a way to connect "Online" Illuminate\Database\Eloquent\Model
with your "offline" Model: POO
and Design Pattern
are there to the rescue. Get your hands dirty, don't hesitate to delve into the source code!
We suggest you to roll your own "Offline" Model based on the source code of jenssegers/laravel-model
and extend "Online" Illuminate\Database\Eloquent\Model
(Decorator pattern or whatever!?) to make it have knowledge of the former. The plumbing is left to you, no spoon fed code so far ;-)
You may likely have to define some custom dependent (helper) classes of Illuminate\Database\Eloquent\Model
such as Illuminate\Database\Eloquent\Relations\BelongsToMany
and so on.
FIY, you can also find a relevant sample of extending Illuminate\Database\Eloquent\Model
here jarektkaczyk/Eloquent-triple-pivot using latest PHP features.
Happy coding.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With