Laravel model without db
Solution 1
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
andDesign 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.
Solution 2
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.

Comments
-
Dusan Plavak 10 months
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
-
dspitzle almost 6 yearsDaVe's response makes sense, as that's how new records are created from form input: you create a new instance and work with it until you save it to the database.
-
Sebastian almost 2 years@dspitzle I disagree, as what you're stating depends on how you usually create objects. We tend to make all attributes
$fillable
(empty$guarded
-array), and useModel::create([...$attributes])
to create model instances. We hardly use thenew Model()
syntax.