【问题标题】:Query working in home but not working in other page (Laravel 5.4)查询在家工作但不在其他页面工作(Laravel 5.4)
【发布时间】:2019-06-10 16:49:43
【问题描述】:

我有 2 个页面:home.blade 和 listpost.blade

这是对菜单 navbar.blade 的简单查询:

$query = category::where('enable', '=', ENABLE_CATEGORY);

home.blade 中有效,但在 listpost.blade 中无效。尽管两个页面都使用 @include(navbar)


这是HomeController(返回查看home.blade)和ListPostController(返回查看listpost.blade)。两者都使用该查询,但只有 HomeController(返回视图 home.blade)在工作。在 ListPostController 中,使用 category::all() 有效,但 where() 无效。

为什么以及如何解决这个问题?

home.blade and listpost.blade

Query in service

【问题讨论】:

  • 您在哪里定义 ENABLE_CATEGORY?是否因为该变量不存在或未设置为与其他刀片中的相同?你真的应该在控制器中执行这些查询并将结果传递给视图。
  • ENABLE_CATEGORY = 1 它在 home.blade 中工作
  • 如果在两个刀片中将 ENABLE_CATEGORY 替换为 1 会怎样。那么它们都有效吗?
  • 我被替换了,只有 home.blade 工作。 listpost.blade 不工作。

标签: php laravel laravel-5.4


【解决方案1】:

我假设两个刀片都有不同的 ENABLE_CATEGORY 值。

MVC 框架中控制器的作用是与模型对话并将适当的数据发送到视图(刀片)。您的视图不应与数据库对话并获取数据。

试试这样的:

BaseController.php

class BaseController extends Controller {
    protected $ENABLED = 1;
}

HomeController.php

class HomeController extends BaseController {
    public function show()
    {
        $categories = Category::where('enable', $this->ENABLED);
        return view('home')->with('categories');
    }
}

ListController.php

class ListController extends BaseController {
    public function show()
    {
        $categories = Category::where('enable', $this->ENABLED);
        return view('listpost')->with('categories');
    }
}

【讨论】:

  • 我试过了,还是没修好。我将 ENABLE_CATEGORY 替换为 1 并且只有 home.blade 正在工作。在 constants.php 中 ENABLE_CATEGORY = 1
  • 您可以为您的家庭、列表帖子和导航栏刀片发布代码吗?
【解决方案2】:

我修好了!我忘了@extends('news.master')

master.blade.php

@include('news.block.navbar')
@yield('content')

listpost.blade.php

@extends('news.master')
@section('content')
@endsection

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-22
    • 1970-01-01
    • 2017-10-25
    • 2017-10-17
    • 1970-01-01
    相关资源
    最近更新 更多