How to compare a value from the search bar to the one from the database in laravel - 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'));
}

Related

i want to get a video id so that it can help me get comments related to that video in my site, it only displays a video but not comments

The biggest issue here is how to get these comments using the videoid in my bladeview -- my blade
<div id="videoid">{{$id->id}}</div>
<div id="videotitle">{{$id->title}}</div>
#php($comments = \App\comments::where('video_id','{{$id->id}}')->get() )
<div id="displaycomment">
#foreach($comments as $comment)
<div id="username">
<div id="con"><h6>{{$comment->id }}</h6></div>
<div id="con"><h6>{{$comment->user_id }}</h6></div>
<div id="con">{{$comment->created_at }}</div>
</div>
<div id="comment">{{$comment->comment }}</div>
#endforeach
</div>
My controller works well --
mycontroller
public function watch($id)
{
return view('video/watch', compact('id'));
}
This is your blade. Thought there's no need to query from the view but rather from the controller.
<div id="videoid">{{ $video->id }}</div>
<div id="videotitle">{{ $video->title }}</div>
<div id="displaycomment">
#foreach($comments as $comment)
<div id="username">
<div id="con"><h6>{{$comment->id }}</h6></div>
<div id="con"><h6>{{$comment->user_id }}</h6></div>
<div id="con">{{$comment->created_at }}</div>
</div>
<div id="comment">{{$comment->comment }}</div>
#endforeach
</div>
Then from your controller you can fetch your data and pass them to the view using Laravel's magic method:
public function watch($video_id)
{
$video = Video::whereId($video_id)->first();
$comments = \App\comments::where('video_id',$video_id)->get()
return view('video/watch',[
'video'=>$video,
'comments'=>$comments
]);
}
in controller
public function watch($id)
{
$video = Video::with('comments')->find($id);
$comments = \App\comments::where('video_id','{{$video->id}}')->get()
return view('video/watch', compact('video','comments'));
}
in view
<div id="videoid">{{$video->id}}</div>
<div id="videotitle">{{$video->title}}</div>
<div id="displaycomment">
#foreach($comments as $comment)
<div id="username">
<div id="con"><h6>{{$comment->id }}</h6></div>
<div id="con"><h6>{{$comment->user_id }}</h6></div>
<div id="con">{{$comment->created_at }}</div>
</div>
<div id="comment">{{$comment->comment }}</div>
#endforeach
</div>
You seem to be missing a key part of using Eloquent.
Relationships.
// Video model:
public function comments()
{
return $this->hasMany(Comment::class);
}
// Comment model:
public function video()
{
return $this->belongsTo(Video::class);
}
// Controller code: (Switched to [Route-model binding][2])
public function watch(Video $video)
{
return view('video.watch', [
'video' => $video
]);
}
// Update routes for Route-model-binding
Route::get('/watch/{video}', 'VideoController#watch')->name('video.watch');
// View:
<div id="videoid">{{$video->id}}</div>
<div id="videotitle">{{$video->title}}</div>
<div id="displaycomment">
#foreach ($video->comments as $comment)
<div id="username">
<div id="con">
<h6>{{$comment->id }}</h6>
</div>
<div id="con">
<h6>{{ $comment->user_id }}</h6>
</div>
<div id="con">$comment->created_at</div>
</div>
<div id="comment">$comment->comment</div>
#endforeach
</div>
Route-model binding

How to configure a search box in 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 }}

How to include a sidebar in Laravel to show on all pages

I want to show a sidebar that displays data from the database across all my pages in Laravel, but I keep getting this error:
Undefined variable: products (View:
C:\xampp\htdocs\shop\resources\views\pages\sidebar.blade.php) (View:
Sidebar
#extends('layouts.app')
<nav class=" d-none d-md-block bg-light sidebar">
<div class="sidebar-sticky">
<form>
<div class=" input-group">
<input class="form-control" type="text" placeholder="Search...">
<button type="submit" class="btn btn-primary" value="search">Search</button>
</div>
</form>
#foreach($products as $product)
<span id="catName">{{ $product->name }}</span>
<h2>No category to show</h2>
#endforeach
</div>
</nav>
Controller
public function index()
{
$product = Product::get();
return view('pages.sidebar', ['products' => $product]);
}
Route
Route::resource('sidebar','SidebarController');
app.blade.php
<div class="col-md-4 col-lg-4 col-sm-12">
#include('pages.sidebar')
</div>
You can either do #include() or your can return it via a controller, you cannot do both. I think you might be a little mixed up with the structure of your project.
If you are using #include it isn't going to hit a controller. So in theory, you would need to include ['products' => $products] on every controller method.
Here is how I would do it:
sidebar.blade.php:
<nav class=" d-none d-md-block bg-light sidebar">
<div class="sidebar-sticky">
<form>
<div class=" input-group">
<input class="form-control" type="text" placeholder="Search...">
<button type="submit" class="btn btn-primary" value="search">Search</button>
</div>
</form>
#foreach($products as $product)
<span id="catName">{{ $product->name }}</span>
<h2>No category to show</h2>
#endforeach
</div>
</nav>
app.blade.php:
<div class="col-md-4 col-lg-4 col-sm-12">
#include('pages.sidebar')
</div>
Create a new file (or use an existing one) for a home page inside the pages folder, we will call it home.blade.php
home.blade.php:
#extends('layouts.app')
Change the view you are returning in the controller to new home.blade.php file.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
public function index()
{
$product = Product::get();
return view('pages.home', ['products' => $product]);
}
}
I finally have to use view composer to solve this problem. Thank you

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() }}

Cant Display my Reply under the Comment Laravel 5.7

I can't display my reply under each comment. Here is my code...
Comment model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
public function commentable()
{
return $this->morphTo();
}
public function user()
{
return $this->belongsTo('App\User');
}
public function comments()
{
return $this->morphMany('App\Comment', 'commentable');
}
}
Post model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = [
'user_id', 'topic', 'body', 'category',
];
public function user()
{
return $this->belongsTo('App\User');
}
public function comments()
{
return $this->morphMany('App\Comment', 'commentable');
}
}
Comment controller
<?php
namespace App\Http\Controllers;
use App\Comment;
use App\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class CommentController extends Controller
{
public function store(Request $request, $post)
{
$comment = new Comment;
$comment->body = $request->body;
$comment->user_id = Auth::user()->id;
$post = Post::find($post);
$post->comments()->save($comment);
return back();
}
public function replyStore(Request $request, $comment)
{
$comment = new Comment;
$comment->body = $request->body;
$comment->user_id = Auth::user()->id;
$comment = Comment::find($comment);
$comment->comments()->save($comment);
return back();
}
}
Routes
Route::post('/comment/store/{post}', 'CommentController#store')->name('comment.add');
Route::post('/reply/store/{commentid}', 'CommentController#replyStore')->name('reply.add');
View
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-12">
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<div class="card">
<div class="card-header">{{$post->topic}}
Create New Post
</div>
<div class="card-body">
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
<h3>{{$post->topic}}</h3>
<p>{{$post->body}}</p>
</div>
</div>
<form action="/comment/store/{{$post->id}}" method="post" class="mt-3">
#csrf
<div class="form-group">
<label for="">Comment :</label>
<textarea class="form-control" name="body" id="" rows="3"></textarea>
<br>
<input type="submit" value="Comment" class="btn btn-secondary">
</div>
</form>
<div class="row mt-5">
<div class="col-md-10 mx-auto">
<h6 style="border-bottom:1px solid #ccc;">Recent Comments</h6>
#foreach($post->comments as $comment)
<div class="col-md-12 bg-white shadow mt-3" style="padding:10px; border-radius:5px;">
<h4>{{$comment->user->name}}</h4>
<p>{{$comment->body}}</p>
<button type="submit" class="btn btn-link" onclick="toggleReply({{$comment->id}})">
Reply
</button>
<div class="row">
<div class="col-md-11 ml-auto">
{{-- #forelse ($replies as $repl)
<p>{{$repl->body}}</p>
#empty
#endforelse --}}
</div>
</div>
</div>
<form action="/reply/store/{{$comment->id}}" method="post"
class="mt-3 reply-form-{{$comment->id}} reply d-none">
#csrf
<div class="form-group">
<textarea class="form-control" name="body" id="" rows="3"></textarea>
<br>
<input type="submit" value="Reply" class="btn btn-secondary">
</div>
</form>
#endforeach
</div>
</div>
</div>
</div>
</div>
#endsection
#section('js')
<script>
function toggleReply(commentId) {
$('.reply-form-' + commentId).toggleClass('d-none');
}
</script>
#endsection
I have created the normal table with parent_id but I don't know how to display the replies for each comment. Please, anyone who can help me with this - I am stranded here and the error coming from the second controller function which is replystore() saying it doesn't recognize the comments() method. Please help me out to display the reply.

Resources