How to work with pagination in Laravel Algolia search - laravel

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

Related

Using 2 Controller Functions in a View in Laravel

I want to have two loops in my view, so I wrote these two functions
public function index()
{
$books = Book::orderBy('created_at', 'desc')->take(10)->get();
return view('bookpage')->with('books', $books);
}
public function loggedin()
{
$books = Book::orderBy('RAND()')->take(1)->get();
return view('bookpage')->with('books', $books);
}
In the view I have
<!--First Loop -->
#foreach($books as $book)
<div class="col-md-6">
<div class="out-box">
<h2>{{ $book->name }}</h2>
<h3>{{ $book->author->name }}</h3>
<br>
Start Reading<br><br>
<img src="assets/img/cart-buy.png" width="13px"/> Buy
</div>
</div>
</div>
</div>
<div class="col-md-6">
<input id="aboutbook" type="radio" name="tabs" checked>
<label for="aboutbook" class="aboutbook">About This Book</label>
<input id="bookreview" type="radio" name="tabs">
<label for="bookreview" class="bookreview">Reviews</label>
<hr style="background-color:black;">
<section style="padding-top:5px;" id="bookabout" >
<div class="row">
<div class="col-md-12">
<p>{{ $book -> about }}</p>
<h1>About the Author</h1>
</div>
</div>
<div class="row">
<div class="col-sm-4 col-md-3 col-6">
<img src="assets/img/Ellipse.png" class="rounded-circle" width="120px">
</div>
<div class="col-sm-4 col-md-4 col-6">
<h1>{{ $book->author->name }}</h1>
<h4>{{ $book->author->about }}</h4>
</div>
<div class="col-sm-4 col-md-5">
<div id="learnbtn">
Learn More
</div>
</div>
</div>
</section>
<section style="padding-top:5px;" id="bookabout1" >
jjjjjjj
</section>
</div>
</div>
</div>
#endforeach
</section>
<!--Second Loop -->
#foreach($books as $book)
#if($book->recommended === 1)
<div class="col-1-5">
<div class="home-catalog-image">
<a href="{{ $book->image_url }}" target="_blank">
<!-- <img src="{{ $book->image }}" alt="trending image" /> -->
<img src="{{ $book->image_url }}" class="img-responsive" alt="{{ $book->image_url }}">
</a>
<!-- <img src="{{ asset('/books/'.$book->image) }}" alt="trending image" /> -->
</div>
<p class="author">{{ $book->author->name }}</p>
<h1 class="book-title">{{str_limit($book -> name, 20) }}</h1>
</div>
#endif
#endforeach
In my web.php
Route::get('/', 'WelcomeController#index')->name('welcome');
I want to call another function in the view, although I know the method is wrong, I don't know how to go about it.
You don't have to create two different method for logged in user just use
public function index()
{
if(auth()->user()) {
$books = Book::orderBy('RAND()')->take(1)->get();
} else $books = Book::orderBy('created_at', 'desc')->take(10)->get();
return view('bookpage')->with('books', $books);
}
in view file use
#auth
//code for logged in user
#else
//code for guest user
#endauth
I was able to solve my problem like this
public function loggedin()
{
$data = array();
$data['recommends'] = Book::where('recommended', 1)->take(10)->get();
$data['latests'] = Book::orderBy('created_at', 'desc',)->where('recommended', 0)->take(10)->get();
$data['logged'] = Book::all()->random(1);
return view('index-logged', compact("data"));
}
In my view, I did
#foreach($data['logged'] as $log)
<h1>{{ $log->author->name }}</h1>
<h4>{{ $log->author->about }}</h4>
#endforeach
#foreach($data['recommends'] as $recommend)
<p class="author">{{ $recommend->author->name }}</p>
<h1 class="book-title">{{str_limit($recommend -> name, 20) }}</h1>
#endforeach
#foreach($data['latests'] as $latest)
<p class="author">{{ $latest->author->name }}</p>
<h1 class="book-title">{{str_limit($latest -> name, 20) }}</h1>
#endforeach

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'));
}

How to fix query in edit view?

i'm setting up a new project to perform multi language form but i'm stuck in edit form i don't know how to handle that
I created my controller and create view the only thing i need is edit view
so you can check my create view in bellow that work fine :
<div class="card-body text-center">
{!! Form::open(['route' => 'content.store', 'method' => 'Post']) !!}
<div class="card">
<div class="card-body">
<div class="form-group">
<label class="mx-4" for="my-input">{{ __('content/form.country_t') }}:</label>
<input id="my-input " type="text" name="country" placeholder="{{ __('content/form.country') }}">
<label class="mx-4" for="my-input">{{ __('content/form.city_t') }}:</label>
<input id="my-input" type="text" name="city" placeholder="{{ __('content/form.city') }}">
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="card col-xs-12 p-0">
<nav>
<div class="nav nav-pills nav-fill card-header" id="nav-tab" role="tablist">
#foreach (config('translatable.locales') as $la=>$desc)
<a class="nav-item nav-link" id="nav-home-tab" data-toggle="tab" href="#{{ $la }}" role="tab" aria-controls="nav-home" aria-selected="true">{{ $desc }}</a> #endforeach
</div>
<div class="tab-content py-3 px-3 px-sm-0 card-body" id="nav-tabContent">
#foreach (config('translatable.locales') as $la=>$desc)
<div class="tab-pane fade px-4" id="{{ $la }}" role="tabpanel" aria-labelledby="nav-home-tab">
<div class="form-group">
<label for="my-input" class="">{{ __('content/form.title') }}</label>
<input id="my-input" class="form-control" type="text" name="translations[{{ $la }}][title]">
</div>
<div class="form-group">
<label for="my-input" class="">{{ __('content/form.body') }}</label>
<input id="my-input" class="form-control" type="text" name="translations[{{ $la }}][body]">
</div>
</div>
#endforeach
</div>
</nav>
</div>
<button type="submit" class="row col-12 mt-2 mx-auto btn btn-primary">{{ __('content/form.submit') }}</button>
</div>
</div>
</div>
</div>
{!! Form::close() !!}
</div>
and this is my controller :
public function store(Request $request)
{
$contents = new Content;
// $contents->fill($request->all());
$this->fillRequest($request,$contents);
$contents->User()->associate(\Auth::user());
$contents->saveOrFail();
return redirect()->route('content.index')->with('success','با موفقیت ساخته شد');
}
private function fillRequest(Request $request, Content $model)
{
//fill model on fillable variables
$model->fill($request->only($model->getFillable()));
$model->saveOrFail();
foreach ($request->translations as $la => $desc) {
//if title field is null ignore the translations
// in case of there is a translation... delete it
if (!$desc["title"]) {
if ($model->hasTranslation($la)) {
$model->deleteTranslations($la);
}
continue;
}
//create new translation if not exists
$model->translateOrNew($la)->fill($desc);
$model->saveOrFail();
}
return $model;
}
I need to know how can i create edit view exactly same as my create view above

Undefined variable: title (View: C:\xampp\htdocs\myproject\resources\views\categories\index.blade.php)

I try to make a page index.blade, but i getting error
Undefined variable: title (View: C:\xampp\htdocs\myproject\resources\views\categories\index.blade.php)
I am using laravel 5.4 PHP 7.0.33
Is there anything wrong with the code?
My Controller
<?php
namespace App\Http\Controllers;
use App\Category;
use Illuminate\Http\Request;
class CategoryController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$categories = Category::orderBy('created_at', 'DESC')->paginate(10);
return view('categories.index', compact('categories'));//
}
My index.blade
this is my view/categories/index.blade.php
#extends('layout.master')
​
#section('title')
<title>Manajemen Kategori</title>
#endsection
​
#section('content')
<div class="content-wrapper">
<div class="content-header">
<div class="container-fluid">
<div class="row mb-2">
<div class="col-sm-6">
<h1 class="m-0 text-dark">Manajemen Kategori</h1>
</div>
<div class="col-sm-6">
<ol class="breadcrumb float-sm-right">
<li class="breadcrumb-item">Home</li>
<li class="breadcrumb-item active">Kategori</li>
</ol>
</div>
</div>
</div>
</div>
​
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-md-4">
#card
#slot('title')
<div class="card">
<div class="card-header with-border">
<h3 class="card-title">{{ $title }}</h3>
</div>
<div class="card-body">
{{ $slot }}
</div>
{{ $footer }}
</div>
#endslot
#if (session('error'))
#alert
<div class="alert alert-{{ $type }} alert-dismissible">
{{ $slot }}
</div>
#endalert
#endif
​
<form role="form" action="{{ route('kategori.store') }}" method="POST">
#csrf
<div class="form-group">
<label for="name">Kategori</label>
<input type="text"
name="name"
class="form-control {{ $errors->has('name') ? 'is-invalid':'' }}" id="name" required>
</div>
<div class="form-group">
<label for="description">Deskripsi</label>
<textarea name="description" id="description" cols="5" rows="5" class="form-control {{ $errors->has('description') ? 'is-invalid':'' }}"></textarea>
</div>
#slot('footer')
<div class="card-footer">
<button class="btn btn-primary">Simpan</button>
</div>
</form>
#endslot
#endcard
</div>
<div class="col-md-8">
#card
#slot('title')
List Kategori
#endslot
#if (session('success'))
#alert(['type' => 'success'])
{!! session('success') !!}
#endalert
#endif
<div class="table-responsive">
<table class="table table-hover">
<thead>
<tr>
<td>#</td>
<td>Kategori</td>
<td>Deskripsi</td>
<td>Aksi</td>
</tr>
</thead>
<tbody>
#php $no = 1; #endphp
#forelse ($categories as $row)
<tr>
<td>{{ $no++ }}</td>
<td>{{ $row->name }}</td>
<td>{{ $row->description }}</td>
<td>
<form action="{{ route('kategori.destroy', $row->id) }}" method="POST">
#csrf
<input type="hidden" name="_method" value="DELETE">
<i class="fa fa-edit"></i>
<button class="btn btn-danger btn-sm"><i class="fa fa-trash"></i></button>
</form>
</td>
</tr>
#empty
<tr>
<td colspan="4" class="text-center">Tidak ada data</td>
</tr>
#endforelse
</tbody>
</table>
</div>
#slot('footer')
​
#endslot
#endcard
</div>
</div>
</div>
</section>
</div>
#endsection
My route web.php
Route::resource('/kategori', 'CategoryController',
['except' => ['create', 'show']]);
It should be like this
public function index()
{
$categories = Category::orderBy('created_at', 'DESC')->paginate(10);
$title = ''; //your title
return view('categories.index', compact('categories','title'));
}
because title not getting value from controller.
You dont pass variable title to view
Add some like this:
$title = 'Your title';
return view('categories.index', compact('categories','title'));
If title is a field of Category
If title is a field/member of Category model, then you would do {{ $category->title }}. I think this is the real error.
Otherwise
You need to define and send the variable as other have said.
$tile='Your Title';
return view('categories.index', compact('categories','title'));

Strange view error on Laravel

I have some cotroller like this:
Route::get('/article/create', 'ArticlesController#create');
and here's my ArticlesController#create:
public function create(){
return view('articles.create',
[
'title'=>'Add Artikel',
'username'=>'Whatever Myname',
'status' => 'Offline'
]
);
}
when i trying to access blog.dev/article/create i got this strange errors:
"Trying to get property of non-object (View: E:\xampp\htdocs\blog\resources\views\articles\single.blade.php)"
how come i can get this kind of error when my view is pointing at articles.create but the error is at single.blade.php which it suppose for ArticlesController#view?
this is what in create.blade.php:
#extends('admin.layout')
#section('content')
<div class="box box-info">
<div class="box-header with-border">
<h3 class="box-title">Horizontal Form</h3>
</div>
#include('admin.formerrors')
<form method="post" class="form-horizontal" action="/articles">
{{ csrf_field() }}
<div class="box-body">
<div class="form-group">
<label for="title" class="col-sm-2 control-label">Title</label>
<div class="col-sm-10">
<input class="form-control" id="title" name="title" placeholder="Judul Artikel">
</div>
</div>
<div class="form-group">
<label for="content" class="col-sm-2 control-label">Content</label>
<div class="col-sm-10">
<textarea class="form-control" rows="3" id="content" name="content"></textarea>
</div>
</div>
<div class="box-footer">
<button type="submit" class="btn btn-primary">Save</button>
</div>
</form>
</div>
#endsection
and here's in my single.blade.php :
#extends('admin.layout')
#section('content')
<h1>{{ $article->title }}</h1>
<p>{{ $article->content }}</p>
<hr>
#foreach($article->comments as $comment)
<blockquote>
<p>{{ $comment->comment }}</p>
<small>{{ $comment->created_at->diffForHumans() }}</small>
</blockquote>
#endforeach
#include('admin.formerrors')
<form method="post" class="form-horizontal" action="/article/{{ $article->id }}/comment">
{{ csrf_field() }}
<div class="box-body">
<div class="form-group">
<label for="comment" class="col-sm-2 control-label">Comment</label>
<div class="col-sm-10">
<textarea class="form-control" rows="3" id="comment" name="comment"></textarea>
</div>
</div>
<div class="box-footer">
<button type="submit" class="btn btn-primary">Save</button>
</div>
</form>
#endsection
and here's my router:
Route::get('/articles', 'ArticlesController#index')->name('home');
Route::post('/articles', 'ArticlesController#save');
Route::get('/article/{id}', 'ArticlesController#view');
Route::get('/article/create', 'ArticlesController#create');
Route::post('/article/{article}/comment', 'CommentsController#save');
Route::get('/register', 'RegistrationController#create');
Route::post('/register', 'RegistrationController#store');
I try to change the create function by pointing into another view, but still it showing same error and pointing at single.blade view.
I delete all code at single.blade and write 'test' text, i don't get any errors. but i'm pointing my controller for viewing into create.blade not sigle.blade
After seeing you routes the problem is in this two routes :
Route::get('/article/{id}', 'ArticlesController#view');
Route::get('/article/create', 'ArticlesController#create');
In this case Laravel will consider the create in your path blog.dev/article/create as an id parameter of the view route here => /article/{id}.
So as a solution you should simply inverse the two routes :
Route::get('/article/create', 'ArticlesController#create');
Route::get('/article/{id}', 'ArticlesController#view');
You need to find what's in the file by reading more than just that line. Maybe you're including that file in the articles.create? Maybe you're accessing a variable that doesn't exist whenever you load the page. Edit your answer with more of the error and what's inside both blades and we can pinpoint what's wrong.

Resources