I'm new to Laravel and have some understanding problems how can I implement a search function to my app.
What I have tried so far.
I created a model that gets the data from the db (this is working)
class Post extends Model
{
public static function scopeSearch($query, $searchTerm)
{
return $query->where('city', 'like', '%' .$searchTerm. '%')
->orWhere('name', 'like', '%' .$searchTerm. '%');
}
}
My controller looks like this:
use App\Post;
class PostsController extends Controller
{
public function index(Request $request)
{
$searchTerm = $request->input('searchTerm');
$posts = Post::all()
->search($searchTerm);
return view('posts.index', compact('posts', 'searchTerm'));
}
public function show($id)
{
$post = Post::find($id);
return view('posts.show', compact('post'));
}
}
With php artisan tinker the model is working. I'm getting the db query.
On the front-end I have a simple input field with a submit button:
<div class="container">
<div class="col-sm-8">
<form action="posts.index" method="GET">
{{csrf_field()}}
<div class="input-group">
<input type="text" class="form-control" name="searchTerm" placeholder="Search for..." value="{{ isset($searchTerm) ? $searchTerm : '' }}">
<span class="input-group-btn">
<button class="btn btn-secondary" type="submit">Search</button>
</span>
</div>
</form>
</div>
</div>
But, now, how can I retrieve the data from the controller if I input something in the search input field? The code is only working when I get all the posts. I need to include somehow the serachTerm from the controller
@extends('layouts.master')
@section('content')
<div class="col-sm-8 blog-main">
@foreach($posts as $post)
<div class="card" style="margin-bottom: 10px">
<div class="card-block">
<h3 class="card-title">{{ $post->Name1 }}</h3>
<small>Created at: {{ $post->created_at->toFormattedDateString() }}</small>
<p class="card-text">With supporting text below as a natural lead-in to additional content.</p>
<a href="{{$post->id}}" class="btn btn-primary">Details</a>
</div>
</div>
@endforeach
</div>
@endsection