3

In my PHP code, I noticed that I can access my value only with a foreach. Can anyone explain why?

return view('pages.temp_page_course', [
        'page' => $this->course($slug),
    ]);


public function course($slug)
{
    $course = Course::where('slug', $slug)->get();
    return $course;
}

With this code, I can access the value.

@foreach($page as $key => $course)
    {{ $course->title }}
@endforeach

How do I access the value without doing a foreach?

Thank you very much

1
  • can we see course()? Commented May 4, 2017 at 23:38

2 Answers 2

8

$course = Course::where('slug', $slug)->get(); will fetch an array of courses.

Try first() instead, $course = Course::where('slug', $slug)->first(); will fetch only 1 and will remove the need for the loop.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes ! Thank you very much, I understand better. It's work fine!
@E_p yes, I had to wait
2

Replace get() with toArray(), that will load results into $course as an array so you can access it as an array

public function course($slug)
{
    $course = Course::where('slug', $slug)->toArray();
    return $course;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.