John Davidson

php - Laravel import model in function

0 comments
Message:


I'm trying to import the model in function and call create function of the specific model.
I know which model to call from Route::currentRoute();, so it must look like


$model = Route::currentRouteName() // return like 'Blog/Post'

$create = new App\Models\$model::create($request->input());

Any ideas on how to do it in that way?



My Answer:
> You can achieve this by using the `resolve` method to dynamically resolve the model class based on the route name. Here's an example of how you can import the model in a function and call the `create` function of the specific model:

php
use Illuminate\Support\Facades\Route;

function createModel($request)
{
$routeName = Route::currentRouteName();
$modelName = 'App\\Models\\' . ucfirst(str_replace('/', '\\', $routeName));

$model = app()->make($modelName);
$model->create($request->all());

// You can also return the created model if needed
return $model;
}


In this example, we first get the current route name using `Route::currentRouteName()`. Then, we construct the fully qualified model class name by converting the route name to the proper namespace format. Finally, we use the `app()->make()` method to dynamically resolve the model class and call the `create` function with the request data.

You can call this `createModel` function from your controller or wherever you need to create a new model instance based on the current route.

Rate this post

3 of 5 based on 1364 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us