Create Controller
$ php artisan make:controller SearchController
INFO Controller [app/Http/Controllers/SearchController.php] created successfully.
Edit app/Http/Controllers/SearchController.php
<?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}%")
->get();
// Return the search view with the results compacted
return view('search', compact('results'));
}
}
Build the view for the search results
@extends('layouts.app')
<!-- Page content begins -->
@section('content')
<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>
</form>
@if ($results->isNotEmpty())
@foreach ($results as $result)
<div class="post-list">
<p>{{ $result->title }}</p>
</div>
@endforeach
@else
<div>
<h2>No posts found</h2>
</div>
@endif
</div></div></div>
@endsection
add the route and import the Search Controller to
- Log in to post comments