Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

garrettmassey's avatar

Building an Eloquent Query based on data in model instance

I am building a system where administrators can create "questions" as part of an automatic quiz. It is really more of an audit so that administrators can create items to see if data in the table exists or is a certain value for all data.

here is an example of a question model instance:

 #original: array:9 [▼
     "id" => 1
     "name" => "User has an email"
     "question_condition" => "NOT"
     "question_condition_val" => "null"
     "method" => "contact"
     "property" => "email"
     "created_at" => null
     "updated_at" => null
]

What I want to do is get this instance, and then use the data to construct an eloquent query. The example above would give me this eloquent query:

$user->contact()->email

Then, I can use conditionals based on the question_condition and question_val fields like so:

if($question->condition == "NOT") {
    if( /*$user->contact->email */ != $question->condition_val) {
	    //the user has satisfied the condition set by the question
        return 1;
    }
    else {
        return 0;
    }
}

What I have been trying to do is use PHP's Variable functions to access the method listed in the $question instance, but that doesn't seem to work.

So is there a way to use a variable to access a method on an eloquent model? The model always stays the same, but the method changes based on the $question.

0 likes
5 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Do you mean this?

$method = $array['method'];
$property = $array['property'];
$stuff = $user->{$method}()->{$property};
1 like
garrettmassey's avatar

@Sinnbeck I had to alter it a bit for my specific instances, but the use of

$user->{$method}->{$property};

worked fantastically! Can you explain what the {$method} and {$property} does in the curly braces?

Sinnbeck's avatar

@garrettmassey it just uses the variable content as a method or property.

I believe it would work without the {} as well

And just for the record

$user->{$method}->{$property};
//equals 
$user->contact->email;

$user->{$method}()->{$property};
//equals
$user->contact()->email;
1 like
garrettmassey's avatar

@Sinnbeck Awesome! I was trying it originally with square brackets, not curly, and I think that may have been my issue. This will save me a ton of time developing the feature out. Thank you so much!

Please or to participate in this conversation.