How to configure a search box in laravel - laravel

I am trying to put a search box in my home.blade but it is not working properly.
Here bellow is my home view
#extends('layouts.app')
#section('content')
<form action="{{ route('home') }}">
<div class="p-1 bg-light rounded rounded-pill shadow-sm mb-4">
<div class="input-group">
<input type="search" name="search" placeholder="Here the animal serial number..." aria-describedby="button-addon1" class="form-control border-0 bg-light">
<div class="input-group-append">
<button id="button-addon1" type="submit" class="btn btn-link text-primary"><i class="fa fa-search"></i></button>
</div>
</div>
</div>
</form>
#foreach($animal as $animal)
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">
<h3>Details for the animal</h3>
</div>
<div class="card-body">
<div class="col-12">
<p><strong>Id: </strong>{{ $animal->id }}</p>
<p><strong>Animal: </strong>{{ $animal->type->category }}</p>
<p><strong>Gender: </strong>{{ $animal->gender }}</p>
<p><strong>Place Of Birth: </strong>{{ $animal->user->address->city }}</p>
<p><strong>Farm: </strong>{{ $animal->user->name }}</p>
<p><strong>Date: </strong>{{ $animal->created_at }}</p>
</div>
</div>
</div>
</div>
</div>
</div>
#endforeach
#if(request()->has('search') && request()->get('search') != '')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">
<h3>Details for the animal</h3>
</div>
<div class="card-body">
<div class="col-12">
<p><strong>Id: </strong>{{ $animal->id }}</p>
<p><strong>Animal: </strong>{{ $animal->type->category }}</p>
<p><strong>Gender: </strong>{{ $animal->gender }}</p>
<p><strong>Place Of Birth: </strong>{{ $animal->user->address->city }}</p>
<p><strong>Farm: </strong>{{ $animal->user->name }}</p>
<p><strong>Date: </strong>{{ $animal->created_at }}</p>
</div>
</div>
</div>
</div>
</div>
</div>
#endif
#endsection
and my controller
public function index()
{
$animal =Animal::all();
if (request()->has('search') && request()->get('search') != ''){
$animal = $animal->where('serial_number', 'like', "%" .request()->get('search')."%");
}
return view('home', compact('animal'))->with('message', 'Below is the result');
}
It bringing me an error like this
'Property [id] does not exist on this collection instance. (View: /Users/macair13/MeatracProject/resources/views/home.blade.php)'
meaning the animal I have passed in my controller is not worrking.

There are a few problems to work through.
1) You have a variable name collision -
#foreach($animal as $animal)
This will overwrite your collection of animals ($animal) with the first individual animal in that collection. On the next iteration foreach will try to iterate over each element of that single animal. And those elements (like id) don't themselves have properties like id, so you get the error you are seeing.
You should change your variable names to avoid the collision, for example convention would be to use $animals, plural, to indicate it is a collection of more than one. So:
Controller
$animals = Animal::all();
// ...
return view('home', compact('animals')) ...
View
#foreach($animals as $animal)
2) The search code in your controller:
$animal = $animal->where(...);
does not actually get the results. You need to append get(), as shown in the docs:
$animal = $animal->where(...)->get();
3) As #Rwd pointed out in the comments, your view has 2 separate chunks of content, one which looks like it should display a collection of animals (the top one with foreach), and a second which looks like it should display just the search results. Similar to problem 1 above, you have a name collision here - both sections are using $animal. After the foreach loop has finished, $animal is the last animal in the collection of all animals - not your search result.
If I am understanding correctly, you probably want use 2 separate variable names, maybe $animals at the top to list all animals, and then maybe $result to show a single search result.
If that is true, you need to update as follows:
Controller
// For the top list of all animals
$animals = Animal::all();
// For the single search result
$result = false;
if (request()->has('search') && request()->get('search') != ''){
$result = $animal->where(...)->get();
}
// Return them both, separately
return view('home', ['animals' => $animals, 'result' => $result])...;
View
#foreach($animals as $animal)
// ...
#if($result)
{{ $result->id }}

Related

Foreach loop returns all results

I have a column of album covers. I want to take me to the album details after click on the cover. Actually it takes me to the album details but it shows all results, not only this one which was clicked.
AlbumDetailsController
public function index(): View
{
return View("details.index", [
'albums' => Album::paginate(1)
]);
}
AlbumDetails Blade view
#extends('layouts.app')
#section('content')
<div class="container">
#foreach ($albums as $album)
<h1 class="my-4">{{ $album->name }}</h1>
<div class="row">
<div class="col-lg-6 mb-4">
<div class="card h-100">
<div class="card-body">
<h4 class="card-title">
</h4>
{{ $album->artist }}
</div>
</div>
</div>
<div class="col-lg-6 mb-4">
<div class="card h-100">
<img src="{{asset('storage/' . $album->image_path)}}" alt="" class="img-fluid card-img-top">
<div class="card-body">
<h4 class="card-title">
{{ $album->artist }}
</h4>
{{ $album->description }}
</div>
</div>
</div>
</div>
#endforeach
#endsection
I've tried to solve this in differents ways but everything is not working. I think problem is with my controller but I'm really don't know how to modify it to show only this item which was clicked.

How to compare a value from the search bar to the one from the database in laravel

I am trying to use the search box in my Laravel project but I keep getting the same error since morning
Here is my Search controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class SearchController extends Controller
{
public function index()
{
return view('search.index');
}
public function Search(Request $request)
{
$serial_number= $request->input('search');
$results =DB::table('animals')->where(function ($query) use ($serial_number) {
$query->where('serial_number','LIKE',"%$serial_number%");
})->latest()->get();
return view('search',compact('results'));
}
}
My routes
Route::get('/search','SearchController#index')->name('search');
Route::post('/search','SearchController#search')->name('search');
and finally my view
#extends('layouts.app')
#section('content')
<form action="{{ route('search') }}" method="POST">
<div class="p-1 bg-light rounded rounded-pill shadow-sm mb-4">
<div class="input-group">
<input type="search" name="search" placeholder="Here the animal serial number..." aria-describedby="button-addon1" class="form-control border-0 bg-light">
<div class="input-group-append">
<button id="button-addon1" type="submit" class="btn btn-link text-primary"><i class="fa fa-search"></i></button>
</div>
</div>
</div>
</form>
#if($results)
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">
<h3>Details for the animal</h3>
</div>
<div class="card-body">
<div class="col-12">
<p><strong>Id: </strong>{{ $results->id }}</p>
<p><strong>Animal: </strong>{{ $results->type->category }}</p>
<p><strong>Gender: </strong>{{ $results->gender }}</p>
<p><strong>Place Of Birth: </strong>{{ $results->user->address->city }}</p>
<p><strong>Farm: </strong>{{ $results->user->name }}</p>
<p><strong>Date: </strong>{{ $results->created_at }}</p>
</div>
</div>
</div>
</div>
</div>
</div>
#endif
#endsection
For me, I think that the problem is in the controller on that line $result which makes the view give the error
419|Page Expired or "Facade\Ignition\Exceptions\ViewException
Undefined variable: results (View:
/Users/macair13/MeatracProject/resources/views/search/index.blade.php)"
You need to include the CSRF token or exclude that URL from the CSRF token check.
<form ...>
#csrf
...
</form>
Laravel 6.x Docs - CSRF
Also you are not passing a results variable to your 'search' view from the Controller's index method. You will need to check if $results isset in your view or pass it to your view.
public function view (Request $request)
{
$search=$request['search'] ?? "";
if($search !=""){
//where
$data=File::where('id','like','%'.$request->search.'%')
->orwhere('name','like','%'.$request->search.'%')
->orwhere('file','like','%'.$request->search.'%')->get();
}
else{
$data = File::all();
}
$p = compact('data','search');
return view('upload_data')->with($p);
// $data = File::all();
// return view('upload_data',compact('data'));
}

Undefined variable: product in blade view

<div class="row">
#foreach($product as $data)
<div class="col-lg-4 col-md-6 mb-4">
<div class="card h-100">
<img src="{{ asset('image/product_image/'.$data->product_image) }}" alt="photo">
<div class="card-body">
<h4 class="card-title">
{{ $data->product_name }}
</h4>
<h5>{{ $data->product_price }}</h5>
<p class="card-text">{{ $data->product_description }}</p>
</div>
<div class="card-footer">
<small class="text-muted">★ ★ ★ ★ ☆</small>
</div>
</div>
</div>
#endforeach
<!-- /.row -->
</div>
First collect what you want in the controller. It could be something like this:
$product = Product::all();
And then you must send the product variable to the view. Something like this:
return view('path.to.view', compact('product'));
By the way. it's better to use plural form products.
You can add the code in the blade to retrieve all the products from the product model
<div class="row">
#php
$product = App\Product::all();
#endphp
#foreach($product as $data)
<div class="col-lg-4 col-md-6 mb-4">
<div class="card h-100">
<img src="{{ asset('image/product_image/'.$data->product_image) }}" alt="photo">
<div class="card-body">
<h4 class="card-title">
{{ $data->product_name }}
</h4>
<h5>{{ $data->product_price }}</h5>
<p class="card-text">{{ $data->product_description }}</p>
</div>
<div class="card-footer">
<small class="text-muted">★ ★ ★ ★ ☆</small>
</div>
</div>
</div>
#endforeach
<!-- /.row -->
</div>
Your code should be like this
Controller's index method,
public function index()
{
$product = Product::all();
return view('path', compact('product'));
}

How to work with pagination in Laravel Algolia search

Pagination is not working. It shows empty page on clicking 2 page.It is not fetching the second page from the search query. And also token is not showing on
2nd page url. Is this is the reason then how to add csrf_token to pagination
Route.
I am using algolia to search
Route::get('posts/search','PostController#search')->name('posts.search');
Controller
public function search(Request $request){
if($request->has('q')) {
$request->flashOnly('q');
$results = Post::search($request->q)->paginate(5);
} else {
$results = [];
}
return view('posts.search')->with('results', $results);
}
View
#extends('layouts.app')
#section('content')
<div class="container">
<h1>Search for Posts</h1>
<form action="{{ route('posts.search') }}" method="get">
{{ csrf_field() }}
<div class="input-group">
<input type="text" name="q" class="form-control input-lg" placeholder="Search for a post..." value="{{ old('q') }}"/>
<span class="input-group-btn">
<button class="btn btn-default btn-lg" type="submit">Search</button>
</span>
</div>
</form>
<hr />
#foreach ($results as $post)
<div class="row" style="margin-top: 20px;">
<div class="col-md-8">
<h3>{{ $post->title }}</h3>
</div>
<div class="col-md-4">
#if ($post->published)
<h4><span class="label label-success pull-right">PUBLISHED</span><h4>
#else
<h4><span class="label label-default pull-right">DRAFT</span><h4>
#endif
</div>
</div>
<div class="row">
<div class="col-md-12">
<p>
{{ str_limit($post->content, 250) }}
</p>
</div>
</div>
#endforeach
#if (count($results) > 0)
<hr />
<div class="text-center">
{{ $results->links() }}
</div>
#endif
#endsection
Try this one may be help
// Making sure the user entered a keyword.
if($request->has('q')) {
// Using the Laravel Scout syntax to search the posts table.
$results = Post::search($request->get('q'))->paginate(15);
}
Update my answer sometimes help this
return view('posts.search',['results' => $results]);
Try :
{{$results->appends(request()->query())->links()}}
insted of
{{ $results->links() }}

How do I get the second last record of a table in laravel

I want the second last record from my table and search already and
I tried this:
$news2 = News::orderBy('created_at', 'desc')->skip(1)->take(1)->get();
but nothing works.
I get this error:
Property [datum] does not exist on this collection instance. (View: C:\xampp\htdocs\j4ylara\resources\views\user\start.blade.php)
If I want the last one everything works it perfectly.
$news1 = News::all()->last();
and my view is the same
<div class="col-12 col-md-6 news">
<div class="news-content">
<div class="date"><i class="far fa-calendar-alt"></i> {{ $news1->datum }}</div>
<h4 class="news-title">{{ $news1->newstitel }}</h4>
<p class="news-text">{{ $news1->newsbeschreibung }}</p>
<a href="#" class="btn btn-primary">
mehr lesen »
</a>
</div>
</div>
</div>
<div class="row no-gutters news-wrapper">
<div class="col-12 col-md-6 news-image">
<img class="img-fluid" src="https://picsum.photos/385/370/?random">
</div>
<div class="col-12 col-md-6 news">
<div class="news-content">
<div class="date"><i class="far fa-calendar-alt"></i>{{ $news2->datum }}</div>
<h4 class="news-title">{{ $news2->newstitel }}</h4>
<p class="news-text">{{ $news2->newsbeschreibung }}</p>
<a href="#" class="btn btn-primary">
mehr lesen »
</a>
</div>
</div>
</div>
try this
$news2 = News::orderBy('created_at', 'desc')->skip(1)->take(1)->first();
this return only one result if you need more you need used foreach inside blade
The error you are receiving is from the view, you are probably calling to a "datum" property for an object and one of them does not exist:
(View: C:\xampp\htdocs\j4ylara\resources\views\user\start.blade.php)
The query looks good to me
try to use getModel() instead of get() to get query result
Try it:
$news2 = News::orderBy('created_at', 'desc')->offset(1)->take(1)->first();
get() returns collection of News. You must use first()
I GET IIIIIIIIIIIT AHHHHHHHHHH :)
$row = News::count();
$newsid = $row -2;
$news1 = News::all()->last();
$news2 = News::orderBy('created_at', 'desc')->skip($newsid)->take($newsid)->first();
return view('user/start', compact('news1', 'news2', 'newsid'));

Resources