Search code examples
phplaravel-7

How can i pass the title of the blog instead of the id in readmore in laravel


The route used to open the single blog:

Route::get('/blog/{title}', 'EdificController@showblog');//single blog view

The main blog blog route that lists all the blogs

Route::get('/blog', 'EdificController@blog')->name('blog');//blog view

The controller( front-end) to show the single blog

public function showblog( $title)
     $blog = Blog::find($title);
        return view('edific.show-blog', compact('blog', 'blogcomments', 'blogreplies'));
}

The code to call the single blog via the read more:

<a href="/blog/{{$blog->title}}" class="post-meta">Read More</a>

when i click the link i get the error

Trying to get property 'image' of non-object (View: C:\laragon\www\edi-fic-1.0.0\resources\views\edific\show-blog.blade.php)

What I want is that instead of calling the id e.g 1 (http://127.0.0.1:8000/blog/**1**) it should open using the title of the blog.The id should not be seen


Solution

  • Your route seems to be fine, need changes in controller and blade file

    You need to check if blog's title is valid or not, the reason you are getting image error is because there is no blog ($blog is null) with the title you are passing, so you need to change the function

    public function showblog( $title)
         $blog = Blog::where('title', $title)->first();
         if (!$blog)
            abort(404);
    
        return view('edific.show-blog', compact('blog', 'blogcomments', 'blogreplies'));
    }
    

    In above code I have changed $blog = Blog::find($title); to $blog = Blog::where('title', $title);. Because find function searches for primary key, it is a rare case that your title is your primary key, it should be id

    Also it it better to use named routes Change our route

    Route::get('/blog/{title}', 'EdificController@showblog');
    

    to

    Route::get('/blog/{title}', 'EdificController@showblog')->name('blogs.show');
    

    Then call it by route function

    <a href="{{ route('blogs.show', $blog->title) }}" class="post-meta">Read More</a>
    

    If above function does not work, try this

    <a href="{{ route('blogs.show', ['title' => $blog->title]) }}" class="post-meta">Read More</a>