Redirecting with a URI Fragment or hash in Laravel helps navigate users to specific sections of a page. Here’s a straightforward example:
Steps to Redirect with a URI Fragment or Hash
1. Define Your Route:
PHP – routes.php
Route::get('/posts/{post}', [PostController::class, 'show'])->name('posts.show');
Route::post('/posts/{post}', [PostController::class, 'update'])->name('posts.update');
2. In your controller
PHP – app/Http/Controllers/PostController.php
namespace App\Http\Controllers;
use App\Models\Post;
class PostController extends Controller
{
public function update(Post $post)
{
// Example logic to update the post
$post->title = 'Updated Title';
$post->save();
// Redirect with hash
return redirect()->route('posts.show', ['post' => $post, '#comments']);
}
public function show(Post $post)
{
return view('posts.show', compact('post'));
}
}
Explanation
- Route Definition: Create a route for displaying post details.
- Update Post Logic: Update the post and save the changes.
- Redirection with Hash: Use
redirect()->route()
to append the#comments
fragment.
This method ensures smooth navigation to the specified section of the page.
Summary
This simplified example demonstrates how to use a hash or URI fragment in a Laravel redirection, helping users jump to specific parts of a page easily.