Model as a variable

I use switch to execute the code I want depending on the model. Is there a way to immediately substitute the model into the code from the variable that comes to me to avoid repeating the code 3 times?

switch ($data['model_type']) {
    case Review::class:
        $record = Review::query()
            ->where('id', $data['model_id'])
            ->whereNotNull('published_at')
            ->first();
        break;
    case Question::class:
        $record = Question::query()
            ->where('id', $data['model_id'])
            ->whereNotNull('published_at')
            ->first();
        break;
    case Answer::class:
       $record = Answer::query()
            ->where('id', $data['model_id'])
            ->whereNotNull('published_at')
            ->first();
        break;
    default:
        return $this->jsonError('404', 404);
}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can put the query in a variable in your switch and execute the duplicate code after the switch:

switch ($data['model_type']) {
            case Review::class:
                $query = Review::query();
                break;
            case Question::class:
                $query = Question::query();
                break;
            case Answer::class:
               $query = Answer::query();
                break;
            default:
                return $this->jsonError('404', 404);
        }

$record = $query->where('id', $data['model_id'])
        ->whereNotNull('published_at')
        ->first();

Method 2

Something like this shoud works:

if(!in_array($data['model_type'], [
    Review::class, 
    Question::class, 
    Answer::class]
){
    return $this->jsonError('404', 404);
}


$record = $data['model_type']::query()
            ->where('id', $data['model_id'])
            ->whereNotNull('published_at')
            ->first();


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x