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 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端