How to pass array data to merge with @props in blade component?

16 Views Asked by At

The laravel document gives an example that you can pass the data one by one, but I was wondering if I can do it at once by passing a data array into a component.

In the example, it first defines @props with default value in the component

<!-- /resources/views/components/alert.blade.php -->
 
@props(['type' => 'info', 'message'])
 
<div {{ $attributes->merge(['class' => 'alert alert-'.$type]) }}>
    {{ $message }}
</div>

And use it by passing props one by one

<x-alert type="error" :message="$message" class="mb-4"/>

But if I already have all the props in an array, e.g.

$alert = [
    'type' => 'error',
    'message' => 'alert message',
    'class' => 'mb-4'
];

Is there any way I can pass all the props at once rather than one by one, and make it merge with @props in the component with something like

<x-alert :props="$alert" />

Because if the props array ($alert in this example) is dynamic, or with a lot of props, it is hard to list them one by one. Or is there any better way to handle such situation?

1

There are 1 best solutions below

0
Jenny On

You can do something like this

@php
$defaults = ['type' => 'info', 'message' => '', 'class' => ''];
$props = array_merge($defaults, $alert ?? []);
@endphp

<div {{ $attributes->merge(['class' => 'alert alert-'.$props['type'].' '.$props['class']]) }}>
    {{ $props['message'] }}
</div>