I'm creating an API which passes me the model name as parameter. So what I want is to create a new instance of that model class and get the required data accordingly. The error which I am facing right now is that it is not generating the namespace even though I have added the model use above. I tried adding "" before the variable new but still didn't work. Also I tried ReflectionClass to initialize class instance but still it is not finding the class. I'd be really grateful if someone can help me out here.

5 Answers
- if you already imported it using
useat the top than you dont need to put"\\"use
new $className
- else simply use the full namespace
'App\\Models\\'.$className( without Models for laravel 7- )
new 'App\\Models\\'.$className
Edit : added \\ for not escaping ' you can added it only before the ' didnt cause an issue in the code i showed because there is no \ right before the '
5 Comments
Just give full path of your Model class as below:
$className = $request->model_type;
$class_path = 'App\\'.$className; // take a full path of your Model class.
$class = new $class_path;
return $class;
1 Comment
You must use complete namespace:
$class = 'App\'.$className
1 Comment
This is correct code of snippet you've added.
And it should work with full namespace path:
if($request->has('model_type')){
$class = '\\App\\Models\\' . (string) $request->model_type;
return new $class;
}
1 Comment
Firstly, I believe the answers posted already are pretty good to resolve your issue.
Nonetheless, I personally feel that you're doing it the wrong way.
- You would rarely need to pass model names in your 'API' routes.
Why? - This would essentially lead to a tight coupling between your route parameters and your model names. This forces you to change your "route signature" whenever you change your model names.
- You typically are expected to use 'id'/'slug'/'custom column' (preferably a primary key) to allow you to identify your models. i.e:
Ex 1: Resource Routes api/events/{event}/tickets/{ticket}
Ex 2: Customizing The Key
api/posts/{post:slug}
With this approach:
A. You can make use of Route Model Binding.
B. You immediately know which route parameter corresponds with which model. i.e:
// use Illuminate\Http\Request;
// use App\Models\Event;
// use App\Models\Ticket;
// Incase you use 'id' as you model's primary key.
function update(Request $request, $event, $ticket)
{
$eventModel = Event::find($event);
$ticketModel = Ticket::find($ticket);
}
Lastly, You can still quite easily validate route parameters since they are also part of the Request object. i.e:
$request->validate([
"event" => "required|numeric|exists:events",
"ticket" => "required|numeric|exists:tickets",
]);

