I have created a ViewModel which has two Eloquent models as properties. I want to create a new ViewModel that has two non-Eloquent models as properties but uses the same property names to populate the mock-up Eloquent models after instantiation.
The idea is that I can create this ViewModel "on-the-fly" and its properties aka Eloquent Models.
Is and How is it possible to create models that use the pre-defined eloquent models in my project/package without actually having any relationship to the table besides it's schema::table properties? The ImageItem and PageInfo Models are Eloquent models and are used as directed, but I want to use their class templates to create dynamic objects that are not relational to the database. I'm going to scrap these objects out once the page is rendered they're gone.
Here is an example of my code:
Basic view model that gets passed to view as compact('page')
class LandingPageViewModel extends Model
{
ImageItem $img;
PageInfo $info;
__construct($img = NULL, $info = NULL){
if(!$img && !$info){
$img = ImageItem::where("key","=","notfound").first();
$info = PageInfo::where("key","=","notfound").first();
}
else{
$this->img = $img;
$this->info = $info;
}
}
}
This is where is gets a little blurry for me
public ImageItem(){
__construct(){
parent::__construct($attributes);
}
}
public PageInfo(){
__construct(){
parent::__construct($attributes);
}
}
In the controller let's say I have a function that creates an error page based off error codes and I return the LandingPageViewModel to the shared view that contains non-eloquent objects
function getErrorPage($params){
//do some looping through params and assign value to properties based on key/column names of eloquent models stored in my db
$mockImage = new ImageItem();
$mockInfo = new PageInfo();
foreach($params as $k => $v){
if($k == Schema::getColumnListing('image_item')){
$mockImage->column['name'] = $v;
}
etc....
$page = new LandingViewModel($mockImage,$mockInfo);
return view("landing.index",compact('page');
}
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire