3

I have A Model In Laravel stored in variable as String.

$model = "App\Models\City";

What I want is

$model::find(1) to fetch the City with ID of 1

But It's not working as it is expected. However, when I do

City::find(1)

Not using the $model variable. I can fetch my expected result.

Anyone?

10
  • is you primary key called id or something else Commented Aug 4, 2017 at 5:39
  • @linktoahref I also did that but it only returns null. Commented Aug 4, 2017 at 5:41
  • 1
    From the string name of a class, can I get a static variable? Commented Aug 4, 2017 at 5:41
  • @usrNotFound I already set $primaryKey in my model to update my primary Key Commented Aug 4, 2017 at 5:41
  • 1
    Can you show us your error? Commented Aug 4, 2017 at 5:45

3 Answers 3

5

You could resolve the class out of service container

$model = app("App\Models\City");
$model::find(1);
Sign up to request clarification or add additional context in comments.

Comments

3

You can use this, you can refer How can I call a static method on a variable class? for more.

$city = call_user_func($class . '::find', 1);

1 Comment

This will give error you need to remove Scope Resolution Operator (::)
3

You can use call_user_func

Try this:

$model = "App\Models\City";
$id =1
$city = call_user_func(array($model, 'find'), $id);

1 Comment

how is it different then @Krish Roofe answer. Oh! i see you have parameter for value

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.