0

For example, I want data from 3 models to MyModel4.

$model1data = MyModel1::getList();
$model2data = MyModel2::getList();
$model3data = MyModel3::getList();

Purpose of getting these data is to prepare my create view, edit view and show view based on above models data.

Now the issue I am facing is I can get the data using MyModel1::getList(); and pass it to my controller's create method. The same data I want for my controller's show and edit method. And for that again I have to get data using MyModel1::getList();. I want to optimize my code for less interaction with database/reduce redundant processing.

So is there any shorter method by which I can write it in my controller or in my model to get these data once and use it multiple times without getting data repeatedly from another model?

I have tried defining the separate method in the model but unable to access using a variable.

public static function getRequiredData()
{
    $model1data = MyModel1::getList();
    $model2data = MyModel2::getList();
    $model3data = MyModel3::getList();
}

public static function prepareCreate()
{
    return (object)array("model1" => PublishPlan::getRequiredData().$model1data, "viewModes" => ViewMode::getList(), "planSchemes" => PlanSchemes::getList());
}

I am getting an error while accessing $model1data in the above method(prepareCreate).

Ronak Ahir
  • 31
  • 5
  • You can use view composer: https://laravel.com/docs/8.x/views#view-composers. – Rouhollah Mazarei Feb 09 '21 at 07:19
  • Is your primary goal is to reduce requests to the database? In that case I would suggest caching the results of the model queries. https://laravel.com/docs/8.x/cache – Jon White Feb 09 '21 at 07:32

1 Answers1

0

I think you should use a constructor for your issue.

public function __construct()
{
    $model1data = MyModel1::getList();
    $model2data = MyModel2::getList();
    $model3data = MyModel3::getList();
}

with the constructor, you can access the lists in all methods of the same controller.

but if you want to access the same list in all controllers, you should define a static variable in Model1, Model2, and Model3.