Data Search in laravel
Comment (0)
Admin
266
Step 1: Install Laravel Fresh Project
composer create-project laravel/laravel example-app
Step 2: Add Dummy Story
php artisan migrate
php artisan tinker
Story::factory()->count(20)->create()
Step 3: Create Controller
app/Http/Controllers/SearchController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Story;
class SearchController extends Controller
{
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function searchStories(Request $request)
{
$validated = $request->validate([
'search' => 'required',
]);
$search = $request->search;
$stories = Story::where('title', 'like', '%' . $search . '%')->get();
return view('website.search_result',compact('stories'));
}
}
Step 4: Create Routes
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\SearchController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::controller(SearchController::class)->group(function(){
Route::get('search-stories', 'searchStories')->name('search.stories');
});
Step 5: Create View File
<!DOCTYPE html>
<html>
<head>
<title>Laravel 9 Autocomplete Search from Database by ijwel.xyz</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.1/bootstrap3-typeahead.min.js"></script>
</head>
<body>
<form action="{{ route('search.stories') }}" method="get" >
@csrf
<div class="wrap-view">
<div class="search-view">
<input type="text" name="search" required class="searchTerm-view" placeholder="What are you looking for?">
<button type="submit" class="searchButton-view">
<i class="icofont-search-1"></i>
</button>
</div>
</div>
</form>
</body>
</html>
Hope it will help.....
Thanks!
Comments (0)
Your Comment