【发布时间】:2015-05-10 14:50:02
【问题描述】:
我有一个为我处理 404 错误的自定义控制器。这是因为我有页面存储在数据库中,所以当 404 发生时,它首先检查数据库以查看是否有该 url 的页面,如果没有,则它应该返回 404。我的控制器还在构造函数中获取其他信息页面需要,因此我不只使用 abort();这是我的代码:
<?php namespace App\Http\Controllers;
use App\Menu_item;
use Session;
use Auth;
use View;
use App\Page;
class FrontendController extends Controller {
public function __construct()
{
$this->data = array();
$this->data['main_menu'] = $this->get_menu_items(1);
$this->data['mobile_main_menu'] = $this->get_menu_items(2);
$this->data['quick_links'] = $this->get_menu_items(3);
$this->data['information'] = $this->get_menu_items(4);
$this->data['message'] = Session::get('message');
$this->data['user'] = Auth::user();
}
public function page($url)
{
$page = Page::where('url', '=', $url)->first();
if(!is_null($page)) {
$this->data['page'] = $page;
return View::make('pages/cms_page', $this->data);
} else {
return response()->view('errors/404', $this->data)->header('404', 'HTTP/1.0 404 Not Found');
}
}
function get_menu_items($menu_id, $parent_id=0)
{
$items = Menu_item::where('menu_id', '=', $menu_id)->where('parent_id', '=', $parent_id)->orderBy('sort_order', 'asc')->get();
foreach($items as $item) {
$item->children = $this->get_menu_items($menu_id, $item->id);
}
return $items;
}
}
如果我在开发人员工具中查看响应,但页面报告状态为 200 ok。如何抛出正确的 404 并仍然呈现我的视图?
【问题讨论】:
-
你可以使用
abort(404);代替渲染你的视图,这个中止会自动渲染errors/404.blade.php -
并且还要处理标题。
-
但是我不能运行构造函数代码可以吗?
-
@SafoorSafdar OP 说他不能使用
abort()