简体   繁体   中英

how to retrieve data from laravel relationship?

Hello im trying to do a quiz app with laravel and im struggeling with retrieving my questions with category..

i have a unsightly solution with this but it's not dynamically..

public function startQuiz(Request $request){
  $questions = Question::all();

  foreach ($questions as $key => $question) {
    dd($question->where('categories_id', 'LIKE', 2)->get()); // i want to change the 2 to the real category id 
  }
}

i thought i could to that with the relationship like $question->category->id but wont work.

thats my model:

class Question extends Model
{
    protected $fillable = ['question_text', 'categories_id', 'correct_answer', 'options'];
    protected $casts = ['options' => 'array'];

    public function category(){
      return $this->belongsTo(Category::class, 'categories_id');
    }
}

class Category extends Model
{
    protected $fillable = ['name', 'slug'];

    public function question()
    {
        return $this->hasMany(Question::class, 'questions_id');
    }

i cant somehow pass the id and check it i dont know why.. thats my form where i pass the category:

@section('content-categories')
<div class="card">
  <div class="card-header">Choose Category to Start</div>
  <div class="card-body">
    @foreach($categories as $category)
      <form class="form-group" action="{{route('user.quiz', $category->slug)}}" method="post">
        @csrf
        <input type="submit" name="categoryTest" class="form-control" value="{{$category->name}}">
      </form>
    @endforeach
  </div>
</div>
@endsection

Edit: i think i know why i couldnt retrieve data with my relationship..i had an error with my relationship in Category Class, i have not a field for questions_id, i replaced it to:

    public function question()
    {
        return $this->hasMany(Question::class);
    } 

and now i could get the questions with:

public function startQuiz(Request $request){
      $questions = Question::all();
      $questionsCategory = [];
      if($request){
        foreach ($questions as $question) {
          if ($request->categoryTest == $question->category->name) {
            $questionsCategory = $question->where('categories_id', '=', $question->category->id)
                                          ->get();
            var_dump($questionsCategory);
          }
        }
      }
    }

Try replacing 'LIKE' with '=' . And remove dd(...) Like this:

foreach ($questions as $key => $question) { dd($question->where('categories_id', 'LIKE', 2)->get()); }

to:

foreach ($questions as $key => $question) { $question->where('categories_id', '=', 2)->get(); }

For your form listing probably you already have $categories = Categories::all() . Next to get all questions of this category after the submit you should first get the category and then questions for it. Let say you have category id in your form:

$categoryQuestions = Category::find($request->get('id'))->questions;

I see you are using category slug for your url, can also use it to find the category:

public function startQuiz(Request $request, string $slug){
   $questions = Category::whereSlug($slug)->first()->questions;
   ...
}

Bonus: In your service provider you can bind {category} directly to your model like this:

Route::bind('category', function($value) {
   return Category::whereSlug('slug', $value)->first();
});

And then your category will be available in controller methods:

public function startQuiz(Request $request, Category $category){
    $questions = $category->questions;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM