Laravel 7 passing collection to anonymous components


Posted by JingTeng on 2020-10-26

Before Laravel 7, we use component directives(@component) to reduce duplicate codes:

@component('components.card')
@endcomponent

We can write some html and CSS codes, and reuse it.
If we want to generate some cards whitch have same syle but different data, we can use for-loop and pass collection, like this:

@for ($i = 0; $i < 3; $i++)
    @component('components.card', ['post' => $data[$i] ] )
    @endcomponent
@endfor

However, Laravel 7 canceled component directives(@component). So, you should use Blade component tag(x-[componentName]) to display your comoponet

<x-cards/>

Like Vue.Js, in blade component you can pass data by attributes.

You may pass data to Blade components using HTML attributes. Hard-coded, primitive values may be passed to the component using simple HTML attributes. PHP expressions and variables should be passed to the component via attributes that use the : character as a prefix:

<x-cards type="error" :message="$message"/>
//in card component
<div class="alert alert-{{ $type }}">
    {{ $message }}
</div>

寫死的資料可以直接用 type="error" 傳遞,如果需要傳遞陣列資料則需要 : 前置號。
例如:

<h2>熱門文章</h2>
<div class="flex flex-col">
    @for ($i = 0; $i < 5; $i++)
        <x-cards :post="$data[$i]"/>
    @endfor
</div>
//in card component
<div >
    <h4 class="pb-2 border-b-2">{{ $post['title'] }}</h4>
</div>


#Laravel7 #blade







Related Posts

2048 專案

2048 專案

Day 80

Day 80

一起來泡 SPA 嗎?

一起來泡 SPA 嗎?


Comments