Storm Spirit
Storm Spirit

Reputation: 1520

How to merge laravel query into simplier

I have table questions

enter image description here

and question_options

enter image description here

what I used is return Question::leftJoin('question_options', 'question_options.question_id', '=', 'questions.id')->get();

and it results like this

MY RESULT enter image description here

and I want to display like this that is simplify... not looping at all, just added option array

EXPECTED RESULT

[
    [
        'name'      =>  'legal_issue',
        'question'  =>  'Description of your current legal issue:',
        'label'     =>  'Please provide as much detail as possible',
        'type'      =>  'text',
    ], [
        'name'      =>  'green_card',
        'question'  =>  'Do you have a Green Card?',
        'label'     =>  'Green Card',
        'type'      =>  'radio',
        'option'    =>  [
                            'Yes', 'No'
                        ]
    ], [
        'name'      =>  'visa_type',
        'question'  =>  'Which type of VISA do you currently have?',
        'label'     =>  'Visa type',
        'type'      =>  'select',
        'option'    =>  [
                            'A-1/A-2','A-1/A-2','A-3 Visa','A-3 Visa','B-1 Visa','B-1 Visa','B-2 Visa','B-2 Visa','C-1 Visa','C-1 Visa','C-1/D Visa','C-1/D Visa','E-1/E-2 Visa','E-1/E-2 Visa','F-1/M-1 Visa','F-1/M-1 Visa','G-1/G-4 Visa','G-1/G-4 Visa','G-5 Visa','G-5 Visa','H-1/H-3 Visa','H-1/H-3 Visa','H-2A','H-2A','I Visa','I Visa','J-1 Visa','J-1 Visa','L-1 Visa','L-1 Visa','O-1/2 or P-1/3 Visa','O-1/2 or P-1/3 Visa','Q-1 Visa','Q-1 Visa','R-1 Visa','R-1 Visa','T Visa','T Visa','U Visa','U Visa'
                        ]
    ], ...
];

Upvotes: 0

Views: 45

Answers (1)

Guilherme Ferreira
Guilherme Ferreira

Reputation: 38

You can use laravel relationships on question model add de follow relationship:

public function options()
{
    return $this->hasMany('QuestionOptions', 'question_id', 'id');
}

then you can simple query it

Question::with('options')->get()

and it will return you a model collection.

once with model collection you can use toArray() method and you will get what you want.

you can learn more on laravel documentation:

https://laravel.com/docs/5.1/eloquent-relationships

and

https://laravel.com/docs/5.1/eloquent-collections

Upvotes: 1

Related Questions