Jeremy
Jeremy

Reputation: 1952

How to access the value without foreach in PHP/Laravel?

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

Upvotes: 3

Views: 13413

Answers (2)

castis
castis

Reputation: 8223

$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.

Upvotes: 8

Jason Joslin
Jason Joslin

Reputation: 1144

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;
}

Upvotes: 2

Related Questions