To achieve the behavior you're looking for, you can use Laravel's resolve function or the app helper to instantiate a model from its class name. This way, you don't need to manually instantiate the model every time. Here's how you can do it:
-
Using the
resolvefunction:
use Modules\MyModule\Entities\User;
class YourController extends Controller
{
protected $modelClass;
public function __construct()
{
$this->modelClass = User::class;
}
public function someMethod($id)
{
$modelInstance = resolve($this->modelClass);
$model = $modelInstance->newQuery()->find($id);
if (!$model) {
// Handle the case where the model is not found
return response()->json(['message' => 'Model not found'], 404);
}
// Apply your manipulations and further operations here
// ...
return response()->json($model);
}
}
-
Using the
apphelper:
use Modules\MyModule\Entities\User;
class YourController extends Controller
{
protected $modelClass;
public function __construct()
{
$this->modelClass = User::class;
}
public function someMethod($id)
{
$modelInstance = app($this->modelClass);
$model = $modelInstance->newQuery()->find($id);
if (!$model) {
// Handle the case where the model is not found
return response()->json(['message' => 'Model not found'], 404);
}
// Apply your manipulations and further operations here
// ...
return response()->json($model);
}
}
In both examples, the resolve function or app helper is used to instantiate the model class dynamically. This approach allows you to specify the model class once and reuse it throughout your controller methods without manually instantiating the model each time.
This should help you achieve the desired behavior similar to how Laravel handles model instantiation in factories and other parts of the framework.