mercredi 10 mai 2023

How can i fetch random order from One-to-Many relationships in laravel 10

I have a One-to-Many relationship

  • The "Question" table has many Options,
  • The "Options" table belongtsTo "Question" table.

I’am trying to fetch, in the same time, random order for my question and random order for options.

I’ am getting the Questions in random order, but I don’t know how to get a random order for the options as well.

Here below you have my code :

My controller:

    public function showQ(){
        return view('my_view',[
            
            'Questions' => Question::inRandomOrder()->with('Option')->get(),
            
        ]);

In the view

    @foreach($Questions as $question)
      
       

       @foreach($Questions -> Option as $option)
           
          
       
       @endforeach

    @endforeach
    

Question model

  public function Option(): HasMany {
        return $this -> hasMany(Option::class);
    }

Option model

  public function Question(): BelongsTo {
        return $this-> belongsTo(Question::class);
    }

Is there any one to clarify the issues?




Aucun commentaire:

Enregistrer un commentaire