tuscan88
tuscan88

Reputation: 5829

Laravel headers not being sent

I have a custom controller that is handling 404 errors for me. This is because I have pages stored in the database so when a 404 occurs it checks the database first to see if there is a page for that url and if not then it should return the 404. My controller also gets other information in the constructor that is needed by the page hence why I don't just use abort(); Here is my code:

<?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;
    }
}

If I view the response in the developer tools though the page is reporting a status of 200 ok. How do I throw a proper 404 and still render my view?

Upvotes: 0

Views: 882

Answers (1)

ntzm
ntzm

Reputation: 4821

Change this:

return response()->view('errors/404', $this->data)->header('404', 'HTTP/1.0 404 Not Found');

To this:

return response()->view('errors/404', $this->data, 404);

The third argument of view() is the status code you want to include with the request.

API documentation

Upvotes: 1

Related Questions