dtp791357 2019-01-19 18:30
浏览 45
已采纳

Laravel在自定义刀片指令中使用数据库中的变量

Summary

A custom blade directive does not use the current value in the database without clearing the view cache first. Since that value can be changed by the user and affects the view I need the directive to always pull the current value from the DB, not use the cached one (this works for directives like @auth, so why not my custom one?).

Background

I have written a custom directive using this tutorial, it does basically the same thing shows different content depending on a value stored in the database. The problem I'm running into is if the variable changes from false to true for example, the directive is stuck with the old value, it doesn't update it when it is changed in the DB. It does work when I clear the view cache, but I want it to always use the current value stored in the database.

Code

\Blade::directive('signup_done', function () {
    $condition = false;

    if (\Auth::check()) {
        if (\Auth::user()->signup_done) $condition = true;
    }

    return "<?php if ($condition) { ?>";
});

Expected vs actual results

signup_done is false by default for each user, if it changes to true I want the directive to output true, but it's stuck in false until I clear the view cache.

  • 写回答

1条回答 默认 最新

  • dskld5423 2019-01-19 20:25
    关注

    Blade is caching the return string of your custom directive, but if that string is a PHP code, it will be evaluated when the cached view is accessed. What you can do is to include the entire conditional logic in the return string, as in:

    \Blade::directive('signup_done', function () {
        return "<?php if (\Auth::check() && \Auth::user()->signup_done) { ?>";
    });
    

    It may not be the best solution, but is the one that should work.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里