【问题标题】:Laravel 5.4 - controller logic to show the status of a blog post on viewLaravel 5.4 - 控制器逻辑显示博客文章的状态
【发布时间】:2018-07-07 13:10:03
【问题描述】:

Laravel 新手,只是遇到了这个我无法解决的问题。

我设置了一个帖子控制器来查询所有博客帖子。在数据库上,我有一个整数列并命名为“状态”,0 为非活动,1 为活动。问题是如何以及在何处放置逻辑以检查状态是 0 还是 1,并在视图中显示“非活动”或“活动”。提前致谢。

public function index()
{

    $posts = Post::where('user_id', 1)->orderBy('id', 'desc')->paginate(5);

    return view('post.index')->withPosts($posts);
}

这里是风景

<table class="table"> 
        <tr>
            <th>Date Created</th>
            <th>Title</th>
            <th>Status</th>
        </tr>
    @foreach ($posts as $post)
        <tr>
            <td>{{datePretty($post->created_at) }}</td>
            <td><a href="/posts/{{ $post->id }}">{{ $post->title }}</a></td>
            <td></td>
        </tr>


        <br>

    @endforeach
</table>

【问题讨论】:

    标签: php laravel-5 controller


    【解决方案1】:

    您可以在刀片模板中包含该逻辑:

    @foreach ($posts as $post)
        <tr>
            <td>{{datePretty($post->created_at) }}</td>
            <td><a href="/posts/{{ $post->id }}">{{ $post->title }}</a></td>
            <td>@if($post->status) active @else inactive @endif</td>
        </tr>
    
    
        <br>
    
    @endforeach
    

    【讨论】:

    • 是否可以在控制器中折腾逻辑,以便尽可能保持视图干净?
    • 在视图中包含display logic 很好。如果您真的想将其保留为控制器,您有 2 个选项:遍历帖子数组并添加活动/非活动或修改您的 sql 查询以根据状态值返回非活动/活动(使用 case 语句)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-06
    • 1970-01-01
    • 2016-05-18
    相关资源
    最近更新 更多