Как сделать запросы правильно в laravel?
У меня есть страница с пятью секциями. В каждой секции мне из БД нужно вывести заголовок и текст не обарачивая при этом всю секцию в foreach. Как сделать скрипт универсальным и правильным?
Сейчас работает так:
public function section()
{
$section = Section::whereIn('section', ['s1', 's2', 's3', 's4', 's5'])->get();
$s1 = $section->where('section','=','s1');
$s2 = $section->where('section','=','s2');
$s3 = $section->where('section','=','s3');
$s4 = $section->where('section','=','s4');
$s5 = $section->where('section','=','s5');
return view('index', [
's1' => $s1,
's2' => $s2,
's3' => $s3,
's4' => $s4,
's5' => $s5
]);
}
В шаблоне вывожу примерно так:
<section id="one">
@foreach ($s1 as $el) {{ $el->title }} @endforeach
</section>
<section id="two">
@foreach ($s2 as $el) {{ $el->title }} @endforeach
</section>
<section id="three">
@foreach ($s3 as $el) {{ $el->title }} @endforeach
</section>
Ответы (1 шт):
Автор решения: E_K
→ Ссылка
Метод keyBy() заполнит ключи, элементов коллекции, указанным свойством.
public function section()
{
$sections = Section::whereIn('section', ['s1', 's2', 's3', 's4', 's5'])->get()->keyBy('section');
return view('index', compact('sections'));
}
Получить доступ к нужному элементу можно с помощью метода get() или $sections['s1']
<section id="one">
{{ $sections->get('s1')->title }}
</section>
<section id="two">
{{ $sections->get('s2')->title }}
</section>
<section id="three">
{{ $$sections->get('s3')->title }}
</section>