Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel model without db

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

like image 603
Dusan Plavak Avatar asked Jul 04 '14 13:07

Dusan Plavak


2 Answers

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.

like image 172
daVe Avatar answered Sep 19 '22 22:09

daVe


Your Question:

So is there any way how to create "offline" model and connect it with "online" data?


Our Take:

  • 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 ;-)


Notes:

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.

like image 37
LaravelMG Avatar answered Sep 19 '22 22:09

LaravelMG