Reputation: 4579
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
Upvotes: 15
Views: 42713
Reputation: 11
Remove extends Model at class
<?php
namespace App\Models;
class Person
{
public $name;
public $id;
//...
}
Upvotes: 0
Reputation: 8745
Sometimes we want to use Eloquent
, but without dealing a real database.
class Currency extends Model
{
use \Sushi\Sushi;
protected $rows = [
[
'code' => 'usd',
'title' => 'United states Dollar',
],
[
'code' => 'eur',
'title' => 'Euro',
],
];
}
https://github.com/calebporzio/sushi
Upvotes: 4
Reputation: 1028
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.
Upvotes: 10
Reputation: 188
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.
Upvotes: 11