search result issue in laravel 5.4 - php

I have search box which is work and show data with pagination but when i search for example for word sample which i have 3 posts with that title in first page of results I'm getting results like this:
https://ibb.co/hGGxwQ
But when i go to second page everything changes!
https://ibb.co/eZJMO5
This is my searchcontroller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
use Illuminate\Support\Facades\Input;
use Carbon\Carbon;
class SearchController extends Controller
{
public function index() {
$countTodayOrders = Post::whereRaw('Date(created_at) = CURDATE()')->count();
$yesterday_posts = Post::whereRaw('Date(created_at) = DATE_ADD(CURDATE(), INTERVAL -1 DAY)')->count();
$weekly_posts = Post::whereBetween( 'updated_at', [Carbon::today()->startOfWeek(), Carbon::today()->endOfWeek()] )->count();
$monthy_posts = Post::whereRaw('MONTH(created_at) = ?', Carbon::today()->month)->count();
$q = Input::get('q');
$posts = Post::where('title','LIKE','%'.$q.'%')->orWhere('body','LIKE','%'.$q.'%')->paginate('2');
$resultcount = Post::where('title','LIKE','%'.$q.'%')->orWhere('slug','LIKE','%'.$q.'%')->count();
return view('theme.search', compact('posts', 'resultcount', 'countTodayOrders', 'yesterday_posts', 'weekly_posts', 'monthy_posts', 'q'));
}
}
This is my search.Blade
#extends('layout.app')
#section('title')
Search results
#endsection
#section('content')
<div class="col-md-9 technology-left">
<div class="tc-ch wow fadeInDown" data-wow-duration=".8s" data-wow-delay=".2s">
<h2> Here is <b> {{ $resultcount }} </b> result for your query.</h2>
<hr/>
<!-- panel group -->
<div class="row form-group">
#foreach($posts as $post)
<div class="col-xs-12 col-md-6">
<div class="panel panel-default">
<div class="panel-image hide-panel-body">
<img src="{{ url('/storage') }}/{{ $post->image }}" class="img-responsive panel-image-preview" alt="{{ $post->title }}" />
</div>
<div class="panel-body">
<h4>{{ $post->title }}</h4>
<p>{{ substr(strip_tags($post->body), 0, 50) }}{{ strlen(strip_tags($post->body)) > 50 ? "..." : "" }}</p>
</div>
<div class="panel-footer text-center">
<span class="glyphicon glyphicon-share-alt"></span>
</div>
</div>
</div>
#endforeach
</div>
<!-- panel group -->
<div class="row text-center">
<div class="col-md-12">
{!! $posts->links() !!}
</div>
</div>
</div>
</div>
#endsection
My route
Route::any('/search', ['uses' => 'SearchController#index', 'as' => 'search.index']);
My search box
<!-- search box -->
<form action="/search" method="post" role="search">
{{ csrf_field() }}
<div class="input-group">
<input type="text" class="form-control" name="q" placeholder="Search..."> <span class="input-group-btn">
<button type="submit" class="btn btn-default">
<span class="glyphicon glyphicon-search"></span>
</button>
</span>
</div>
</form>
<!-- search box -->
Why is that?

The problem is most probably with your q parameter not getting passed in the page links.
Just add it In your controller like this:
$q = Input::get('q');
$posts = null;
if($q) {
$posts = Post::where('title','LIKE','%'.$q.'%')
->orWhere('body','LIKE','%'.$q.'%')
->paginate(2)
->appends('q', $q);
}
In your blade you should add an if statement to check if there are any posts
#if($posts and $posts->count())
// show posts
#else
// show a nothing found message
#endif

Related

Laravel Live Search Results Display Issue on the View

I'm trying to implement a live search in my laravel application.
Following is my index function in the controller (ParticipantController.php). Here if there is no search happens, then displaying the participants by default.
public function index(Request $request)
{
if($request->ajax()){
$data = User::orderBy('id','DESC')
->WHERE('role_id','=','3')
->where('email','LIKE','%'.$request->search."%")
->paginate(12);
return view('admins.participants.index',compact('data'))
->with('i', ($request->input('page', 1) - 1) * 12 );
}
else{
$data = User::orderBy('id','DESC')->WHERE('role_id','=','3')->paginate(12);
return view('admins.participants.index',compact('data'))
->with('i', ($request->input('page', 1) - 1) * 12 );
}
}
following is my view (only included the relevant part)
<div class="row mt-5 ">
<div class="col-md-12 mb-2 text-right">
<input type="text" class="form-controller" id="search" name="search"></input>
</div>
</div>
<div class="row mt-2 participant-row">
#foreach ($data as $key => $user)
<div class="col-md-3 d-flex align-items-stretch mb-4">
<div class="white-panel w-100 ">
<div class="card p-2 ">
<div class="row no-gutters ">
<div class="col-auto my-auto">
#if(empty($user->image_id))
<img src="/propics/default-avatar.png" class="img_participant">
#else
<?php if(file_exists('propics/'.$user->image_id.'')){
echo '<img src="/propics/'.$user->image_id.'" class="img_participant">
';
}else{
echo '<img src="/propics/default-avatar.png" class="img_participant">
';
}?>
#endif
</div>
<div class="col my-auto">
<div class="card-block px-2">
<div class="text-right">
<a class="btn btn-default btn_icon" href="{{ route('participants.edit',$user->id) }}"><i class="fas fa-edit"></i></a>
{!! Form::open(['method' => 'DELETE','route' => ['participants.destroy', $user->id],'style'=>'display:inline']) !!}
{!! Form::button('<i class="fas fa-trash-alt"></i>', ['class' => 'btn btn-default btn_icon','type'=>'submit','onclick'=>'return confirm("Are you sure want to remove this User?")']) !!}
{!! Form::close() !!}
</div>
<hr>
<h4 class="card-title participant_name alas">{{ $user->first_name }} {{ $user->last_name }}</h4>
<p class="card-text participant_email alas">{{ $user->email }}</p>
</div>
</div>
</div>
</div>
</div>
</div>
#endforeach
</div>
And set my route as (web.php),
Route::resource('/admins/participants','Admin\ParticipantController');
Following is my Javascript which I included at the bottom of my view
<script type="text/javascript">
jQuery('#search').on('keyup',function(){
$value=jQuery(this).val();
$.ajax({
type : 'get',
url:"{{ route('participants.index') }}",
data:{'search':$value},
success:function(data){
jQuery('.participant-row').html(data);
}
});
})
</script>
Now the issue is when I search for something, as the result, the current code provides me a whole new view inside the old view. It loads a new view (with the menus and all) inside the target div class whichi mentioned in my javascript code.

How can I get a single category of question in a quiz app using Laravel Eloquent

I want to select a single category of questions that the user can select with options. I have tried doing this with a resource I found online.
The category page:
#foreach($categories as $category)
<section>
<a href="#" class="image">
<img src="{{asset('images/pic09.jpg')}}" alt="" data-position="top center" />
</a>
<div class="content">
<div class="inner">
<header class="major">
<h3>{{$category->name}}</h3>
</header>
<p></p>
<ul class="actions">
<li>Learn more</li>
</ul>
</div>
</div>
</section>
#endforeach
Here is the TestController I'm using, the show controller is might to select questions and options with the category_id at random:
namespace App\Http\Controllers;
use App\Category;
use App\Http\Requests\StoreTestRequest;
use App\Option;
class TestsController extends Controller
{
public function show($id)
{
$categories = Category::find($id)->with(
['categoryQuestions' => function ($query) {
$query->inRandomOrder()
->with(
['questionOptions' => function ($query) {
$query->inRandomOrder();
}]
);
}]
)
->whereHas('categoryQuestions')
->get();
return view('client.test', compact('categories'));
}
public function store(StoreTestRequest $request)
{
$options = Option::find(array_values($request->input('questions')));
$result = auth()->user()->userResults()->create(
[
'total_points' => $options->sum('points')
]
);
$questions = $options->mapWithKeys(
function ($option) {
return [$option->question_id => [
'option_id' => $option->id,
'points' => $option->points
]
];
}
)->toArray();
$result->questions()->sync($questions);
return redirect()->route('client.results.show', $result->id);
}
}
web.php
// User
Route::group(['as' => 'client.', 'middleware' => ['auth']], function () {
Route::get('home', 'HomeController#redirect');
Route::get('dashboard', 'HomeController#index')->name('home');
Route::resource('/test', 'TestsController');
Route::get('results/{result_id}', 'ResultsController#show')->name('results.show');
Route::get('send/{result_id}', 'ResultsController#send')->name('results.send');
});
This is the Blade file from the resource I'm using:
#extends('layouts.home')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Test</div>
<div class="card-body">
#if(session('status'))
<div class="row">
<div class="col-12">
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
</div>
</div>
#endif
<form method="POST" action="{{ route('client.test.store') }}">
#csrf
#foreach($categories as $category)
<div class="card mb-3">
<div class="card-header">{{ $category->name }}</div>
<div class="card-body">
#foreach($category->categoryQuestions as $question)
<div class="card #if(!$loop->last)mb-3 #endif">
<div class="card-header">{{ $question->question_text }}</div>
<div class="card-body">
<input type="hidden" name="questions[{{ $question->id }}]" value="">
#foreach($question->questionOptions as $option)
<div class="form-check">
<input class="form-check-input" type="radio" name="questions[{{ $question->id }}]" id="option-{{ $option->id }}" value="{{ $option->id }}"#if(old("questions.$question->id") == $option->id) checked #endif>
<label class="form-check-label" for="option-{{ $option->id }}">
{{ $option->option_text }}
</label>
</div>
#endforeach
#if($errors->has("questions.$question->id"))
<span style="margin-top: .25rem; font-size: 80%; color: #e3342f;" role="alert">
<strong>{{ $errors->first("questions.$question->id") }}</strong>
</span>
#endif
</div>
</div>
#endforeach
</div>
</div>
#endforeach
<div class="form-group row mb-0">
<div class="col-md-6">
<button type="submit" class="btn btn-primary">
Submit
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
How can the Testcontroller be made to select questions and answer from a single category and save the result from the user's answers?
public function index()
{
$questions = Category::select('categories.name', 'question_result.points')
->join('questions', 'categories.id', '=', 'questions.category_id')
->join('question_result', 'questions.id', '=', 'question_result.question_id')
->join('results', 'question_result.result_id', '=', 'results.id')
->where('results.user_id', auth()->id())
->get();
return view('client.home', compact('questions'));
}

Ordering by count in Laravel

In my Laravel application, I have implemented Tagging of articles and events. This is accomplished by having two tables: tags and taggables. In my tag controller, I have an index method that grabs all the tags, a count of the tags and the same logic to count used tags.
It looks like this:
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$tags = Tag::orderByDesc('name')->get();
$tagCount = count($tags);
$usedTags = Tag::has('articles')->orHas('events')->orderBy('name')->get();
$usedTagsCount = count($usedTags);
return view('pages.tags.index', compact('tags', 'usedTags', 'tagCount', 'usedTagsCount'));
}
I pass all this data to my view which looks like this:
<div class="container">
<div class="row">
<!-- Search results -->
<div class="col-md-8">
<div class="padded-content-box">
<div class="header">
<div class="row">
<div class="col-xs-12 col-md-12">
<h1 class="heading">Tags</h1>
</div>
</div>
</div>
</div>
<div class="padded-content-box">
<div class="header">
<div class="row">
<div class="col-xs-12 col-md-12">
<h2 class="sub-heading">
All Tags ({{ $tagCount }})
</h2>
</div>
</div>
</div>
<div class="content">
<div class="tag-row">
<div class="tag-words-list">
#foreach($tags as $tag)
<a class="tag-word" title="{{ $tag->name }}" href="{{ URL::action('TagController#show', $tag->slug) }}">{{ $tag->name }}</a>
#endforeach
</div>
</div>
</div>
</div>
<div class="padded-content-box">
<div class="header">
<div class="row">
<div class="col-xs-12 col-md-12">
<h2 class="sub-heading">
Tags currently in use ({{ $usedTagsCount }})
</h2>
</div>
</div>
</div>
<div class="content">
#foreach($usedTags as $tag)
<p>
<a class="tag-word" title="{{ $tag->name }}" href="{{ URL::action('TagController#show', $tag->slug) }}">{{ $tag->name }}</a>
x {{ count($tag->articles) + count($tag->events) }}
</p>
#endforeach
</div>
</div>
</div>
<div class="col-md-4"></div>
</div>
</div>
As you can see, to show a count of tags used I just add the articles and events that have a given tag.
How would I count how many times each tag is used in both events and articles, then order them by the count. Essentially if a tag has been used the most it would be at the top of a list.
Update
As suggested I have changed my controller method to look like this:
public function index()
{
$tags = Tag::orderBy('name')->get();
$tagCount = count($tags);
$usedTags = Tag::has('articles')->orHas('events')->withCount('articles', 'events')->orderByRaw('articles_count + events_count DESC')->orderBy('name')->get();
$usedTagsCount = count($usedTags);
return view('pages.tags.index', compact('tags', 'usedTags', 'tagCount', 'usedTagsCount'));
}
This ensures that the tags are in count and alphabetical order.
Then in my view I changed the count code to this:
<p>
<a class="tag-word" title="{{ $tag->name }}" href="{{ URL::action('TagController#show', $tag->slug) }}">{{ $tag->name }}</a> x {{ $tag->articles_count + $tag->events_count }}
</p>
This way I get to remove some minor logic from the view.
Use withCount():
$tags = Tag::withCount('articles', 'events')
->orderByRaw('articles_count + events_count DESC')
->get();

How to link comments to each post by id with Laravel Blade

I have created a Post and Comment application. I am trying to link the comments to the id of the post. I am trying to use PHP in a Blade template to do this. I get the error that the variable post_id does not exist. I want to use the #if and #foreach of Blade. The problem seems to be in the #if statement.
Here is my HTML:
<div class="col-md-9">
<div class="row">
#foreach($posts as $post)
<div class="col-md-12 post" id="post{{ $post->id }}">
<div class="row">
<div class="col-md-12">
<h4>
{{ $post->title }}
</h4>
</div>
</div>
<div class="row">
<div class="col-md-12 post-header-line">
<span class="glyphicon glyphicon-user"></span> by {{ $post->user->firstName }} {{ $post->user->lastName }} | <span class="glyphicon glyphicon-calendar">
</span> {{ $post->created_at }} | <span class="glyphicon glyphicon-comment"></span><a href="#">
3 Comments</a>
</div>
</div>
<div class="row post-content">
<div class="col-md-2">
<a href="#">
<img src="/images/random/postimg.jpg" alt="" class="img-responsive postImg">
</a>
</div>
<div class="col-md-10">
<p>
{{ $post->post }}
</p>
</div>
</div>
<div class="row add-comment">
<div class="form-group">
<input type="text" name="addComment" placeholder="Add your comment" class="form-control" v-model="comment">
</div>
<input id="addComment" type="submit" name="submitComment" value="Submit Comment" class="btn btn-default" v-on:click="submitComment" data-id="{{ $post->id }}">
</div>
#if($post->comment->post_id == $post->id)
#foreach($post->comment as $comment)
<div class="row">
<div class="col-md-12 mb-r">
<div class="card example-1 scrollbar-ripe-malinka">
<div class="card-body">
<h4 id="section1"><strong>By: {{ $comment->user->firstName }} {{ $comment->user->lastName }}</strong></h4>
<p>{{ $comment->comment }}</p>
</div>
</div>
</div>
</div>
#endforeach
#endif
</div>
#endforeach
</div>
</div>
Here is my PostController:
public function index(){
$posts = Post::with('comment', 'user')->orderBy('id', 'desc')->limit(20)->get();
return view('post.posts')->with('posts', $posts);
}
You don't need #if statement, remove it. $post->comment is a collection, that 's why your are not getting post_id. if you want to check, then check inside foreach.
#foreach($post->comment as $comment)
<div class="row">
<div class="col-md-12 mb-r">
<div class="card example-1 scrollbar-ripe-malinka">
<div class="card-body">
<h4 id="section1"><strong>By: {{ $comment->user->firstName }} {{ $comment->user->lastName }}</strong></h4>
<p>{{ $comment->comment }}</p>
</div>
</div>
</div>
</div>
#endforeach
You need to add post_id to the comments table and use the relationship:
public function comments()
{
return $this->hasMany(Comment::class);
}
Then you'll be able to load related comments:
Post::with('comments', ....
And iterate over posts and their comments:
#foreach ($posts as $post)
#foreach ($post->comments as $comment)
{{ $comment->content }}
#endforeach
#endforeach
I think if you create relationship between Post model and Comment model (post table and comments table), your #if is useless. I recommend you to check your corresponding models.
Your code should be like this,
Post.php
public function comments(){
return $this->morphMany('App\Comments','commentable');
}
Comment.php
public function commentable(){
return $this->morphTo();
}
in my app Comment model is shared by some other models also.
Eg :- User’s Questions also have comments.
Find more details in laravel:Eloquent page

No query results for model [App\Card]

I have the following problem:
No query results for model [App\Card].
My Route.php:
Route::post('/cards/{card}/notes' , 'NotesController#store');
My NotesController:
public function store(Request $request)
{
return $request->all();
}
And my View:
#section('content')
<div class="row">
<div class="col-md-6 col-md-offset-3">
<h1> {{ $card->title }}</h1>
<h4> {{ $card->created_at }}</h4>
<ul class="list-group">
#foreach($card->notes as $note)
<li class="list-group-item">{{ $note->body }}</li>
#endforeach
</ul>
<hr>
<h3>Add a New Note</h3>
<form action="post" action="/cards/{{ $card->id }}/notes">
<div class="form-group">
<textarea name="body" class="form-control"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success">Add note</button>
</div>
</form>
</div>
</div>
#stop
I have two database tables - cards and notes.
This is my route.php
Route::get('/' , 'PagesController#home');
Route::get('/about' , 'PagesController#about');
Route::get('cards' , 'CardsController#index');
Route::get('cards/{card}' , 'CardsController#show');
Route::post('/cards/{card}/notes' , 'NotesController#store');
Yes i have records in tables here is pics
cards
Notes

Categories