简体   繁体   中英

404 page not working for some routes in laravel 5.4

I have a route like this:

web.php

Route::get('post/{slug}', [
    'as'   => 'post.single',
    'uses' => 'PageController@getSingle',
]);

PageController.php

public function getSingle($slug)
{
    //some db stuff and returning an array to view
    return view('single', array('var1' => $var, 'var2' => $var2));
}

A post has a slug which is stored in the database. If a post exists with slug, example: first-post Then the route mysite.com/post/first-post works as expected. But if a post doesn't exists, example: second-post Then the route mysite.com/post/second-post gives me an error:

**ErrorException**
Trying to get property of non-object

I want it to show a 404 error page (404 page is already configured) mysite.com/hellohello gives and 404 page, so it's working as expected.

Any suggestion what should I do?

Eloquent has a neat firstOrFail method which either returns the first entity it finds, or if there is none throws an ModelNotFoundException which laravel converts to a 404 page.

public function getSingle($slug)
{
    $var = YourModel::where('slug', $slug)->firstOrFail();
    return view('single', compact('var'));
}

I think you should update your function like: And you can not close bracket in return view

public function getSingle($slug)
{

    //some db stuff and returning an array to view
    return view('single', array('var' => $var));
}

UPDATE after OP change the question content :

public function getSingle($slug)
{
    //some db stuff and returning an array to view
    $var = SOMEDBRESULT1;
    $var2 = SOMEDBRESULT2;
    return view('single', array('var1' => $var, 'var2' => $var2));
}

You can learn about how to get first record from db with laravel 5.4.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM