skip to Main Content

I have route:

Route::resource('posts', PostController::class);

Within URL (1): domain.com/posts will show all posts.
Within URL (2): domain.com/posts?status=trashed will show all soft deleted posts.
How I want to create a beautiful URL which replace the URL (2)?
Such as domain.com/posts/status/trashed, or domain.com/posts-trashed
How I write the route?

I want to create a beautiful URL which replace the URL domain.com/posts?status=trashed

2

Answers


  1. To create a more user-friendly URL for showing trashed posts instead of using a query parameter like domain.com/posts?status=trashed, you can define a custom route that handles this scenario. You can do this by adding a route with a specific URI pattern and then updating your controller to handle the request appropriately.

    Here’s how you can achieve this:

    Define a custom route in your routes/web.php file:

    Route::get('posts/trashed', [PostController::class, 'trashed'])->name('posts.trashed');
    

    This route maps the URL domain.com/posts/trashed to a trashed method in your PostController. You can choose any URI segment you like, but in this example, I’m using trashed.

    In your PostController, create a trashed method to handle the request:

    public function trashed()
    {
        $trashedPosts = Post::onlyTrashed()->get();
    
        return view('posts.trashed', compact('trashedPosts'));
    }
    

    In this example, the trashed method retrieves the soft-deleted posts and returns them to a view. You should customize this method according to your application’s requirements.

    Create a view file (e.g., resources/views/posts/trashed.blade.php) to display the trashed posts.
    Now, you can access the trashed posts by visiting the URL domain.com/posts/trashed. This provides a more user-friendly URL structure compared to using query parameters.

    Login or Signup to reply.
  2. In this case, you can create two routes, namely:

    Route::get('posts/status/trashed',[PostController::class,'trashed'])->name('posts.trashed');
    Route::resource('posts', PostController::class);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search