Display only if query is found via search in Laravel using php - php

I have referral code search box that query referral codes. this code must be available before user can register. So basically on Auth.register I have two boxes, firs t box holds the referral code search box and the other one is the registration box. My goal is to hide first the registration box and appear only if the code has found.
RegisterController
public function index(Request $request)
{
$keyword = $request->get('search');
$referral = Referral::where('code', 'LIKE', '%'.$keyword.'%')->get();
if (count ( $referral ) > 0)
return view ( 'Auth.register')->withDetails ( $referral )->withQuery ( $keyword );
else
return view ( 'Auth.register')->withMessage ( 'The code you provided is not existing.' );
}
register.blade.php
<!-- THIS IS THE FIRST BOX THAT HOLDS THE CODE SEARCH BOX -->
<div class="card mx-4">
<div class="card-body p-4">
<h1>Referral Code</h1>
<p class="text-muted">Please provide the referral code given to you by your collector</p>
#if(isset($message))
<div class="alert alert-success">
{{ $message }}
</div>
#endif
{!! Form::open(['method' => 'GET', 'url' => '/register', 'class' => 'form-inline my-2 my-lg-0', 'role' => 'search']) !!}
<div style="width: 100%;">
<input type="text" class="form-control" name="search" style="width: 100%;" placeholder="Enter your referral code here!">
</div>
<div style="width: 150px; margin: auto; margin-top: 20px; ">
<button class="btn btn-success btn-default" type="submit">
<i class="fa fa-search"></i> Check Availability
</button>
</div>
{!! Form::close() !!}
</div>
</div>
<!-- THIS IS THE 2ND BOX THAT HOLDS THE REGISTRATION FORM -->
#if(isset($details))
<div class="card mx-4">
<div class="card-body p-4">
#foreach($details as $code)
#if($code->status==0)
<h2>Code is available</h2>
#else
<h2>Code is already taken</h2>
#endif
#endforeach
... the rest of registration form ...
</div>
</div>
#endif
My problem now is, the #details is displaying the current rows of "Referrals"
Is there a way that query from this line,
$referral = Referral::where('code', 'LIKE', '%'.$keyword.'%')->get();
should only display if the result is match from $keyword?
because currently the page is look like this
Thanks!

I think you want something like to match the keyword against your database. So instead of partial matching use exact matching.
public function index(Request $request)
{
$keyword = $request->get('search');
$referral = Referral::where([
['code', $keyword],
['status', 0]
])->first();
if ($referral)
return view ( 'Auth.register')->withDetails ( $referral )->withQuery ( $keyword );
else
return view ( 'Auth.register')->withMessage ( 'The code you provided does not exist or already used.' );
}
And in view you need not to use the following lines.
#foreach($details as $code)
#if($code->status==0)
<h2>Code is available</h2>
#else
<h2>Code is already taken</h2>
#endif
#endforeach
Just add your registration form after #if(isset($details)).
Its weird how you are doing this. You can use AJAX to do it in a single page

Related

Delete and Update Method of CRUD is not passing all the parameters

I've implemented a modal type Update and Delete functions in my website but it always return Too few arguments to function App\Http\Controllers\AdminController::destroy(), 1 passed in D:\SUDRTest\vendor\laravel\framework\src\Illuminate\Routing\Controller.php on line 54 and exactly 2 expected
it is also the same for the Update function as well
Here is my route for the CRUD
Route::resource('papers', AdminController::class)->only(['edit', 'update', 'destroy']);
Here is the View
<li class="pdfpaperInfo">
<div class="colpdf col-1" data-label="Title:">{{ $paper->PaperTitle }}</div>
<div class="colpdf" data-label="Paper Type:">{{ $paper->PaperType }}</div>
<div class="colpdf" data-label="College:">{{ $paper->College }}</div>
<div class="colpdf" data-label="Author(s):">{{ $paper->Authors }}</div>
<div class="colpdf" data-label="Date Published:">{{ $paper->DatePublished }}</div>
<div class="pdfbtnCont">
<button class="pdfBtn redBtn" onclick="location.href='{{route('MyProfile')}}'">Back</button>
<button class="pdfBtn redBtn" id="modalOneBtn" onclick="location.href='{{route('papers.edit', $paper->PaperID)}}'">Update</button>
<button class="pdfBtn redBtn" id="modalTwoBtn">Delete</button>
</div>
</li>
<div id="modalOne" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="m1Close close">×</span>
<div class="modalinfoCont">
<h2>Update Paper</h2>
#include('admin.updatepaper')
</div>
</div>
</div>
<div id="modalTwo" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="m2Close close">×</span>
<div class="modalTwoCont modalinfoCont">
<h2>Delete Paper</h2>
<br>
Are you sure you want to delete this paper?
<br>
<br>
<div class="modalbtnCont">
<form method="POST" action="{{route('papers.destroy', $paper->PaperID) }}">
#csrf
#method('DELETE')
<button class="redBtn" type="submit">Yes</button>
</form>
<button class="redBtn" type="submit">No</button>
</div>
</div>
</div>
</div>
</div>
and the controller
public function destroy(Papers $paper, $PaperID)
{
$paper=Papers::find($PaperID);
$paper->delete();
return redirect()->back();
}
public function edit(Papers $paper, $PaperID)
{
$paper=Papers::find($PaperID);
return view('admin.updatepaper',compact('paper'));
}
public function update(Request $request,Papers $paper, $PaperID )
{
$request->validate([
'PaperTitle' => 'required',
'PaperType' => 'required',
'file' => [
'required',
File::types('pdf')
->max(12 * 1024),
],
]);
$paper=new Papers();
$file=$request->file;
$filename=time().'.'.$file->getClientOriginalExtension();
$request->file->move('assets', $filename);
$paper->file=$filename;
$paper->DatePublished=$request->DatePublished;
$paper->PaperTitle=$request->PaperTitle;
$paper->PaperType=$request->PaperType;
$paper->Authors=$request->Authors;
$paper->update();
return redirect()->back();
}
I've tried not to do it in modal form and still it kept on displaying the same error and I don't know what is the missing parameter since it doesn't tell me
You need to take another look at route-model binding.
Laravel will by default do the Papers::find($paperID) and pass the Papers model as the Papers $papers argument to your methods.
So the destroy method should be:
public function destroy(Papers $paper)
{
$paper->delete();
return redirect()->back();
}
Of course you can disable route-model binding and do your own thing but it doesn't seem necessary here.
Its not clear what you intend to do in the update method. If you want to create a new paper on update and keep the old one then change $paper->update() to $paper->save() and you should be good. But if you want to do an actual update you should do something like this:
update(Papers $paper, Request $request) {
// validate
$paper->DatePublished=$request->DatePublished;
// update other fields
$paper->save();
return redirect()->back();
}

How to show summary data in Laravel Blade inside of ForEach Loop?

I am trying to display a ForEach loop on my view that shows each code type. That part works. I am having trouble figuring out how to display a count of how many pieces of code (stored in another table) exist for each code type. I don't understand how to use the id of the code_type to query the code_type_selected table and to return that count.
In my CodeType model
protected $fillable = [
'name',
'color',
'icon'
];
public function codeTypesSelected() {
return $this->hasMany(CodeTypesSelected::class, 'code_type_id', 'id');
}
In my CodeTypeSelected model
protected $fillable = [
'code_type_id',
'code_id',
];
public function codeTypes() {
return $this->belongsTo(CodeType::class, 'id', 'code_type_id');
}
In my controller
public function index(Request $request)
{
$codeTypes = CodeType::latest()->get();
$codeTypesSelected = CodeTypesSelected::latest()->get()->groupBy('code_type_id');
//dd($codeTypesSelected);
return view('code_layout.index', compact('codeTypes', 'codeTypesSelected'));
}
And in my view
<!-- /. ROW -->
<div class="row">
#foreach($codeTypes as $codeTypeItem)
<div class="col-md-3 col-sm-12 col-xs-12">
<div class="panel panel-primary text-center no-boder bg-color-{{ $codeTypeItem->color }}">
<div class="panel-left pull-left {{ $codeTypeItem->color }}">
<i class="fa fa-{{ $codeTypeItem->icon }} fa-5x"></i>
</div>
<div class="panel-right">
<h3>
{{ count($codeTypesSelected) }}
</h3>
<strong> {{ $codeTypeItem->name }} </strong>
</div>
</div>
</div>
#endforeach
</div>
<!-- /. ROW -->
Have you tried this
CodeType::latest()->withCount('codeTypesSelected')->get()

Laravel search not print the results

I have search box for my Laravel project it seems working because after request I'll get http://project.dev/search?q=fifth but nothing prints in blade template.
here 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('slug','LIKE','%'.$q.'%')->get();
if(count($posts) > 0)
return view('theme.search', compact('posts', 'countTodayOrders', 'yesterday_posts', 'weekly_posts', 'monthy_posts'))->withQuery ( $q );
else return view ('theme.index')->withMessage('No Details found. Try to search again !');
}
}
Here is my search form
<!-- search box -->
<form action="/search" method="get" role="search">
<div class="input-group">
<input type="text" class="form-control" name="q" placeholder="Search users"> <span class="input-group-btn">
<button type="submit" class="btn btn-default">
<span class="glyphicon glyphicon-search"></span>
</button>
</span>
</div>
</form>
<!-- search box -->
Here is my routes
Route::any('/search', ['uses' => 'SearchController#index', 'as' => 'search.index']);
Here is my blade
#extends('layout.app')
#section('content')
<div class="col-md-9 technology-left">
<div class="tc-ch wow fadeInDown" data-wow-duration=".8s" data-wow-delay=".2s">
#if(isset($details))
<p> The Search results for your query <b> {{ $query }} </b> are :</p>
<h2>Sample User details</h2>
<table class="table table-striped">
<thead>
<tr>
<th>Post</th>
</tr>
</thead>
<tbody>
#foreach($posts as $post)
<tr>
<td>{{$post->name}}</td>
</tr>
#endforeach
</tbody>
</table>
#endif
</div>
</div>
#endsection
where is my mistake?
Update
Now 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:
first page
But when i go to second page everything changes!
second page
Why?
Ok guys i got it thanks, the issue was withQuery method as i used compact i shouldn't use with i just added it to `compact and now it's working. but what about counting the results? how can i pass the number of founded result in blade?

Slug not work properly

I am try create slug with laravel on admin its work but on front-end view its work too except one problem, i have four article and work nice on admin but when on view front end its always open same article even-tough slug is different URL.
Controller code
public function singleArticle($slug){
Article::where('slug', '=', $slug)->increment('viewed');
$navi['country'] = Country::get();
$navi['genre'] = Genre::get();
$articles = Article::orderBy('created_at','desc')->limit(3)->get();
$latest_movies = Movie::where('type', '=', 'movie')->orderBy('created_at','desc')->limit(4)->get();
$latest_tv = Movie::where('type', '=', 'tv')->orderBy('created_at','desc')->limit(4)->get();
$most_viewed_movies = Movie::where('type', '=', 'movie')->orderBy('viewed','desc')->limit(3)->get();
$most_viewed_tv = Movie::where('type', '=', 'tv')->orderBy('viewed','desc')->limit(4)->get();
$most_viewed_article = Article::orderBy('created_at','desc')->orderBy('viewed','desc')->limit(4)->get();
$article = Article::where('slug', '=', $slug)->first();
and for view front end
#if(count($articles) > 0)
<div class="articles_list">
#foreach($articles as $article)
<div class="col-md-6">
<div class="article_item row">
<div class="article_info">
#if($article->thumb)
<a href="{{route('articles.single',$article->slug)}}"><img class="img-responsive" src="{{ url(Image::url($article->thumb,350,200,array('crop'))) }}" alt="{{$article->title}}">
#else
{{-- <img class="img-responsive" src="{{ url(Image::url($article->thumb,250,250,array('crop'))) }}" alt="{{$article->title}}"> --}}
#endif
<div class="artice_title"><h3>{{$article->title}}</h3></div>
<div class="article_time">
<span class="author">By Admin</span>
<span class="cateogry">Category</span>
<span class="time">{{date('F d, Y', strtotime($article->created_at))}} </a></span></div>
<!--<div class="article_descr">
<?php echo mb_substr($article->content, 0, 200) . ' ...'; ?>
</div>
<a class="btn btn-default read_more" href="{{route('articles.single',$article->id)}}">Read more</a> -->
</div>
</div>
</div>
#endforeach
</div>
<div class="clearfix"></div>
<div class="text-center col-xs-12">
{{$articles->links()}}
</div>
#else
<div class="col-xs-12">
Nothing found in there
</div>
#endif
For routing below code :
// Category
Route::get('category/{slug}', ['as' => 'category.index', 'uses' => 'CommonController#categoryIndex']);
// Articles
Route::get('articles', ['as' => 'articles.index', 'uses' => 'CommonController#articleIndex']);
// Specific article
Route::get('articles/{slug}', ['as' => 'articles.single', 'uses' => 'CommonController#singleArticle']);
thanks before.
It is just issue of naming convention.Please choose different names for variables.
#foreach($articles as **$article**). It is in your view which have $article variable.
**$article** = Article::where('slug', '=', $slug)->first(); It is in your controller. so it is just because of conflict.

Pagination replacing new search results with old ones when try to change page

I've added a ajax search box in app's home page. It works fine. But when i use the pagination after the new results shows up, pagination leads me to the old results. I'm not sure what I'm not doing right. So looking for expert's help to get a solution for it.
I've these in routes --
Route::get('/', 'BookmarkController#index');
Route::post('/', 'BookmarkController#search');
I've these in their controller -
public function index(Request $request)
{
$tags_list = Tag::orderBy('tag', 'asc')->get();
$bookmarks = Bookmark::orderBy('created_at','desc')->where('public', '1')->paginate(10);
$bookmarks_all = Bookmark::orderBy('created_at','desc')->where('public', '1')->get();
return view('welcome')->with('bookmark', $bookmarks)->with('tags_list', $tags_list)->with('bookmarks_all', $bookmarks_all);
}
public function search(Request $request){
$search_value = $_POST['search'];
$bookmarks = Bookmark::orderBy('created_at','desc')->where('public', '1')->where('title', 'rlike', $search_value)->orwhere('description', 'rlike', $search_value)->orwhere('contents', 'rlike', $search_value)->orwhere('tags', 'rlike', $search_value)->paginate(10);
return view('public_bookmarks')->with('bookmark', $bookmarks);
}
In welcome.blade.php
<div class="container content-container">
<div class="row ">
<div class="col-sm-12">
<div class="page-header">
<div class="row">
<span class="title col-sm-8">Recent Bookmarks</span>
<form id="demo-2" class="search-form col-sm-4" method="post">
{{ csrf_field() }}
<div class="input-group">
<!-- <input id="search" class="form-control" onkeyup="search_data(this.value, 'result');" placeholder="Search" name="search" value="" type="text"> -->
<input id="search" class="form-control" placeholder="Search" name="search" value="" type="text">
<span class="input-group-btn">
<button class="btn btn-primary" id="search-btn" type="button"><i class="fa fa-search"></i></button>
</span>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#search-btn').click(function(){
$.ajax({
url: '/',
type: "post",
data: {'search':$('input[name=search]').val(), '_token': $('input[name=_token]').val()},
success: function(data){
$('#search-results').html(data);
},
error: function (data) {
console.log('Error on Article extracting');
console.log(data);
}
});
});
});
</script>
</form>
</div>
</div>
</div>
<div class="col-sm-9" id="search-results">
#include ('public_bookmarks')
</div>
</div>
In public_bookmars.blade.php
#if (count($bookmark) > 0)
<div class="row card-row">
#foreach ($bookmark as $bookmark_single)
<div class="col-sm-4 col-xs-12 card-parent" data-col="col-sm-4">
<div class="card">
<div class="card-part1">
<div class="img-card">
<img src="{{$bookmark_single->thumbnail}}" />
</div>
<div class="card-content">
<h4 class="card-title">
{{ $bookmark_single->title }}
</h4>
<div class="card-desc">
{{ str_limit($bookmark_single->description, $limit = 50, $end = ' [...]') }}
</div>
</div>
<div class="card-read-more">
<p><?php $tags = $bookmark_single->tags;
$tag_list = explode(',', $tags); ?>
#foreach ($tag_list as $tag)
{{$tag}}
#endforeach
</p>
<p class="card-user">- {{ $bookmark_single->bookmarker }}</p>
<a class="v-link" target="_blank" href="{{ $bookmark_single->url }}">Visit the link</a>
</div>
<button type="button" class="btn btn-success btn-circle btn-lg btn-read-more"><i class="fa fa-chevron-right"></i></button>
</div>
<div class="card-part2 col-xs-0">
{{ print $bookmark_single->contents }}
</div>
</div>
</div>
#endforeach
</div>
{{ $bookmark->links() }}
#endif
You can use flash() method to achieve this. Old Input
In your search() method add $request->flash(). This will flash the current inputs in the session.
And, next time you want retrieve it by $request->old('search');
Here's the complete search() method:
public function search(Request $request){
$search_value = $_POST['search']; //assign the current value of search field
if(!$search_value) //check if current value is not null, means this is new search or previous one
{
$search_value = $request->old('search'); //If search_value is null use the old value
$request->search = $request->old('search'); //add the old value to current request so that it can be flashed
}
$bookmarks = Bookmark::orderBy('created_at','desc')->where('public', '1')->where('title', 'rlike', $search_value)->orwhere('description', 'rlike', $search_value)->orwhere('contents', 'rlike', $search_value)->orwhere('tags', 'rlike', $search_value)->paginate(10);
$request->flash(); //adding this request's search value to the session
return view('public_bookmarks')->with('bookmark', $bookmarks);
}
Update:
public function search(Request $request){
//$search_value = $_POST['search']; change this to use $request
$search_value = $request->search;
$bookmarks = Bookmark::orderBy('created_at','desc')->where('public', '1')->where('title', 'rlike', $search_value)->orwhere('description', 'rlike', $search_value)->orwhere('contents', 'rlike', $search_value)->orwhere('tags', 'rlike', $search_value)->paginate(10);
return view('public_bookmarks')->with('bookmark', $bookmarks)->withInput($request->only('search')); // flashed input to the view
}
Now, in your view you can get the value with old() method:
{{ $bookmark->appends(['search' => old('search')])->links()}}
Update 2:
change your ajax call to use get method and point it to new address:
type: "get",
url: '/search'
Add a route to handle search request as a get method:
Route::get('/search', 'BookmarkController#search');
In your search() method use $request to get the search value:
$search_value = $request->search;

Categories