Searching Posts in Laravel

Create Controller

$ php artisan make:controller SearchController

   INFO  Controller [app/Http/Controllers/SearchController.php] created successfully.

Edit app/Http/Controllers/SearchController.php


namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Post;

class SearchController extends Controller
     * Display a listing of the search results.
     * @return \Illuminate\Http\Response
    public function results(Request $request){
        // Get the search value from the request
       // $search = $request->input('search');
       $search = $request->search;
        // Search in the title and body columns from the posts table
        $results = Post::query()
            ->where('title', 'LIKE', "%{$search}%")
            ->orWhere('body', 'LIKE', "%{$search}%")
        // Return the search view with the results compacted
        return view('search', compact('results'));

Build the view for the search results

<!-- Page content begins -->
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-12">
    <form action="{{ route('search') }}" method="GET">
        <input type="text" name="search" required />
        <button type="submit">Search</button>

    @if ($results->isNotEmpty())
        @foreach ($results as $result)
            <div class="post-list">
                <p>{{ $result->title }}</p>
            <h2>No posts found</h2>

add the route and import the Search Controller to