LARAVEL Blade Templates & Views 2 — Questions and Answers
Question 1: Which Blade directive iterates over an array or collection?
- @loop
- @iterate
- @foreach (Correct answer)
- @each
Correct answer: @foreach
@foreach($items as $item) ... @endforeach loops over an array or collection, equivalent to PHP's foreach.
Question 2: What is the $loop variable automatically available inside Blade @foreach loops?
- A helper object with metadata like index, count, first, last, and depth (Correct answer)
- A counter that only tracks the current iteration number
- A boolean that becomes true when the loop finishes
- A reference to the array being iterated
Correct answer: A helper object with metadata like index, count, first, last, and depth
Laravel injects a $loop object into every @foreach block with properties like $loop->index, $loop->first, $loop->last, $loop->count, and $loop->depth.
Question 3: Which Blade directive defines an anonymous component inline in a view?
- @component (Correct answer)
- @make
- @create
- @widget
Correct answer: @component
@component('path.to.component') ... @endcomponent renders a Blade component with its slot content.
Question 4: What is the correct syntax to pass data to a component using the @component directive?
- @component('name', ['key' => 'value']) (Correct answer)
- @component('name')->with(['key' => 'value'])
- @component('name', key='value')
- @component('name').pass(['key' => 'value'])
Correct answer: @component('name', ['key' => 'value'])
Data is passed to a Blade component as the second argument to @component() as a PHP associative array.
Question 5: What is the correct Blade directive to implement a switch/case structure?
- @switch with @case and @endswitch (Correct answer)
- @select with @option and @endselect
- @match with @when and @endmatch
- @choose with @option and @endchoose
Correct answer: @switch with @case and @endswitch
Blade provides @switch, @case, @break, @default, and @endswitch directives mirroring PHP's switch statement.
Question 6: Which Blade directive includes a view only if that view file actually exists?
- @include('view') ?? null
- @includeIf('view') (Correct answer)
- @tryInclude('view')
- @safe_include('view')
Correct answer: @includeIf('view')
@includeIf('view.name') silently skips rendering if the specified view file does not exist, preventing errors.
Question 7: Which Blade directive allows you to include a view conditionally based on a boolean expression?
- @includeWhen($bool, 'view') (Correct answer)
- @includeIf($bool, 'view')
- @conditionalInclude('view', $bool)
- @renderWhen($bool, 'view')
Correct answer: @includeWhen($bool, 'view')
@includeWhen($condition, 'view.name') renders the included view only when the first argument evaluates to true.
Which Blade directive iterates over an array or collection?