如何向Laravel Blade组件条件传递error变量
当然可以,而且有几种更优雅的实现方式,不用在组件调用时写冗余的@error代码:
方法一:组件内部直接处理错误逻辑(最推荐)
直接把错误判断逻辑写到密码字段组件的Blade模板里,不用再手动传error参数。
假设你的组件文件是resources/views/components/store/password-field.blade.php,修改成这样:
<div class="form-group"> <label for="{{ $name }}">{{ $label }}</label> <input type="password" name="{{ $name }}" id="{{ $name }}" placeholder="{{ $placeholder }}" class="@error($name) is-invalid @enderror" > <!-- 自动显示错误信息 --> @error($name) <div class="invalid-feedback">{{ $message }}</div> @enderror </div>
之后调用组件时,只需要传基础参数就行,错误会自动处理:
<x-store.password-field label="Password" name="password" placeholder="••••••••" />
方法二:保留自定义错误的灵活性(类组件方式)
如果需要偶尔传自定义错误信息,同时默认自动获取验证错误,可以用类组件实现:
- 创建组件类
app/View/Components/Store/PasswordField.php:
<?php namespace App\View\Components\Store; use Illuminate\View\Component; class PasswordField extends Component { public $label; public $name; public $placeholder; public $error; public function __construct($label, $name, $placeholder, $error = null) { $this->label = $label; $this->name = $name; $this->placeholder = $placeholder; // 优先使用传入的自定义错误,否则自动获取验证错误 $this->error = $error ?? ($this->getValidationError($name) ?? ''); } protected function getValidationError($name) { return session('errors')->first($name); } public function render() { return view('components.store.password-field'); } }
- 组件模板
resources/views/components/store/password-field.blade.php修改为:
<div class="form-group"> <label for="{{ $name }}">{{ $label }}</label> <input type="password" name="{{ $name }}" id="{{ $name }}" placeholder="{{ $placeholder }}" class="{{ $error ? 'is-invalid' : '' }}" > @if($error) <div class="invalid-feedback">{{ $error }}</div> @endif </div>
调用时两种方式都支持:
<!-- 自动获取验证错误 --> <x-store.password-field label="Password" name="password" placeholder="••••••••" /> <!-- 传入自定义错误 --> <x-store.password-field label="Password" name="password" placeholder="••••••••" error="密码长度不能少于8位" />
方法三:调用时直接绑定错误值(简洁写法)
如果你只想在调用时简化代码,Laravel支持用属性绑定直接传递错误:
<x-store.password-field label="Password" name="password" placeholder="••••••••" :error="$errors->first('password')" />
这里:error是Blade的属性绑定语法,$errors->first('password')会在有错误时返回消息,无错误时返回null,组件内判断是否显示即可。
内容的提问来源于stack exchange,提问作者Andrei RRR
相关产品推荐
相关产品推荐

