>我正在尝试创建一个刀片指令,用于检查用户是否已登录并具有已激活的帐户。在我们的数据库中,我们有一个 0 的user_status列:挂起,9 个活动。
应用服务提供商.php
public function boot()
{
Blade::directive('active', function () {
$condition = false;
// check if the user is authenticated
if (Auth::check()) {
// check if the user has a subscription
if(auth()->user()->getStatus() == 9) {
$condition = true;
} else {
$condition = false;
}
}
return "<?php if ($condition) { ?>";
});
Blade::directive('inactive', function () {
return "<?php } else { ?>";
});
Blade::directive('endactive', function () {
return "<?php } ?>";
});
}
欢迎光临.php
@active
<p>User is active</p>
@inactive
<p>User is inactive</p>
@endactive
我已经在我的用户模型上包含了这个getStatus(.php函数。
public function getStatus() {
return $this->user_status;
}
我还可以使用Trait MustActivateAccount,其中包括此功能:
/**
* Determine if the user has activated account.
*
* @return bool
*/
public function hasActivatedAccount()
{
return $this->user_status == 9;
}
此刀片指令在添加到页面时显示此错误:
外观\点火\异常\视图异常 语法错误,意外的")">
我是否未在 AppServiceProvider.php 文件中正确转义,如果是,在哪里以及如何转义?
我遇到了同样的问题,结果是必须设置为字符串的布尔$condition
变量。$condition = "true";
而不是$condition = true
.
这是有道理的,因为布尔值不会echo
出来。因此,它将是<?php if() { ?>
而不是<?php if(true) { ?>
.
请参阅下文(当前版本 6.18.41):
// check for Providers
Blade::directive('provider', function () {
// check if the user has the correct type
$condition = Auth::user()->type === "provider" ? "true" : "false"; // ... and not boolean
return "<?php if (" . $condition . ") { ?>";
});
Blade::directive('endprovider', function () {
return "<?php } ?>";
});
。并运行:php artisan view:clear
可以在刀片模板中尝试此操作
@if(Auth()->user()->user_status == 9)
<p>User is active</p>
@else
<p>User is inactive</p>
@endif