search with pagination is not working in laravel - php

I make it in 1 route with
in route
Route::get('/all-students', 'AdminController#studentList')->name('admin.student');
Route::post('/all-students', 'AdminController#searchByClassRoll')->name('search-by-class-roll');
in controller funtion student list
public function studentList(Request $request)
{
Session::put('url.intended2', URL::current());
Session::put('url.intended', URL::previous());
if (isset($request->class)) {
if (isset($request->roll)) {
if ($request->class == 'all') {
$students = DB::table('students')
->where('roll', '=', $request->roll)
->orderBy('id', 'DESC')
->paginate(20);
} else {
$students = DB::table('students')
->where('roll', '=', $request->roll)
->where('class', '=', $request->class)
->orderBy('id', 'DESC')
->paginate(20);
}
} else {
if ($request->class == 'all') {
return redirect()->route('admin.student');
} else {
$students = DB::table('students')
->where('class', '=', $request->class)
->orderBy('id', 'DESC')
->paginate(20);
}
}
} else {
$students = DB::table('students')
->orderBy('id', 'DESC')
->paginate(20);
}
return view('admin.student-list')->with('students', $students);
}
post method
public function searchByClassRoll(Request $request)
{
$class = $request->class;
$roll = $request->roll;
if (isset($request->class)) {
if (isset($request->roll)) {
return redirect()->route('admin.student', ['class' => $class, 'roll' => $roll]);
} else {
return redirect()->route('admin.student', ['class' => $class]);
}
}
}
in blade
#if(method_exists($students,'links'))
{!! $students->links() !!}
#endif
normally when I click page 2 it returns
all-students?page=2
when I search something all-students?class=2 and then i click on pagination page it returns again all-students?page=2 and remove the search data from URL.
form from view
<form action="{{ route('search-by-class-roll') }}" method="post">
{{ csrf_field() }}
<input type="hidden" name="type" value="student_list">
<div class="row gutters-8">
<div class="col-4-xxxl col-xl-4 col-lg-3 col-12 form-group">
<div class="ui-alart-box">
<div class="default-alart">
<div class="result" role="alert">
#if(app('request')->input('class') || app('request')->input('roll'))
See All<span> | </span>
#endif
Showing results {{$students->count()}} of {{$students->total()}} entries
</div>
</div>
</div>
</div>
<div class="col-3-xxxl col-xl-3 col-lg-3 col-12 form-group">
<input type="number" name="roll" placeholder="Search by Roll..." class="form-control">
</div>
<div class="col-4-xxxl col-xl-3 col-lg-3 col-12 form-group">
<select class="select2 form-control" name="class" required>
<option value="all">All Classes</option>
<option value="baby">baby</option>
<option value="nursery">nursery</option>
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
<option value="5">five</option>
<option value="6">six</option>
<option value="7">seven</option>
<option value="8">eight</option>
<option value="9">nine</option>
<option value="10">ten</option>
</select>
</div>
<div class="col-1-xxxl col-xl-2 col-lg-3 col-12 form-group">
<button type="submit" class="fw-btn-fill btn-gradient-yellow">SEARCH</button>
</div>
</div>
</form>
i want to made this because I want this in 1 URL just because if someone manually entered the URL with search data he can see the output. but in here I can't get the result with pagination from blade. when I turned into page 2 it remove the search variable from URL. and paginate the whole data. how can I get result with pagination after search?

There is the simpler way
Just add with your paginated array.
{{ $users->withQueryString()->links() }}

Coming directly to your controller. You don't need any other route or method you can handle this filtering on same route and in same method.
public function studentList(Request $request)
{
if(!empty($request)){
$query = $request->all();
$students = DB::table('students')->orderBy('id', 'DESC');
if(isset($request->class) AND $request->class != '' AND $request->class != 'all')
$students = $students->where('class', '=', $request->class);
if(isset($request->roll) AND $request->roll != '')
$students = $students->where('roll', '=', $request->roll);
$students = $students->paginate(20);
return view('admin.student-list', compact('students','query'));
}
$students = DB::table('students')
->orderBy('id', 'DESC')
->paginate(20);
return view('admin.student-list', compact('students'));
}
Change few things in your view
<form action="{{ route('admin.student') }}" method="get"> change route and method to get
{{ csrf_field() }} //remove this
Below your table inside view write this code. The appends() is most important otherwise pagination in your filtered data won't work.
#if(isset($query))
{{ $students->appends($query)->links() }}
#else
{{ $students->links() }}
#endif

Try use append on paginator blade
{{$students->appends(\Illuminate\Support\Facades\Input::except('page'))->links()}}

Related

How to Store Multiple Select Values in Laravel 8?

So my problem is that if i try to save only one value like "Location in the layout" of a post it works, but the moment i am saving an array I'm getting something like ["value 1" , "value 2"] in the DB, therefore it cant be read and in the CRUD-Controller there is no data saved when i am editing.everything works perfectly except the value i am getting from the data. I would appreciate any help, methods or alternatives
edit.blade.php
<div class="form-group">
<label>Select Post Location</label>
<select
class="form-control select2 select2-hidden-accessible"
multiple=""
data-placeholder="Select Locations"
style="width: 100%"
tabindex="-1"
aria-hidden="true"
name="post_locations[]"
id="post_locations"
>
<option value="TopBox-GR" #if ($post->post_locations == "TopBox-GR") selected #endif>TopBox-GR</option>
<option value="TopBox-C3" #if ($post->post_locations == "TopBox-C3") selected #endif>TopBox-C3</option>
<option value="TopBox-C4" #if ($post->post_locations == "TopBox-C4") selected #endif>TopBox-C4</option>
</select>
</div>
home controller
public function index()
{
$posts = post::where([['status',1], ['post_locations','TopBox-GR']])->get();
return view('user.blog',compact('posts'));
}
and view:
<div class="topbox-c4">
#foreach ($posts as $post)
<a href="{{ route('post',$post->slug) }}">
<div class="image-topbox-c4-container">
<img src="{{ Storage::disk('local')->url($post->image)}}" />
</div>
<div class="text-topbox-c4-container">
<h3>{{$post->title}}</h3>
<p>
{{$post->subtitle}}
</p>
</div>
</a>
#endforeach
</div>
post.controller:
public function update(Request $request, $id)
{
$this->validate($request,[
'title'=>'required',
'subtitle'=>'required',
'slug'=>'required',
'body'=>'required',
'image'=>'required',
'post_locations'=>'required',
]);
if($request->hasFile('image'))
{
$imageName = $request->image->store('public');
}
$post = post::find($id);
$post->image = $imageName;
$post->title = $request->title;
$post->subtitle = $request->subtitle;
$post->slug = $request->slug;
$post->post_locations = $request->post_locations;
$post->body = $request->body;
$post->status = $request->status;
$post->tags()->sync($request->tags);
$post->categories()->sync($request->categories);
$post->save();
return redirect(route('post.index'));
}
Firstly you should get selected locations in $selectLocations variable and all locations in $allLocations variable for edit.blade.php
In edit.blade.php, you can display like this:-
#foreach($selectLocations as $value)
<select class="form-control" name="post_locations[]" multiple=''>
<option value="">Select Location</option>
#foreach($allLocations as $val)
<option #if($value['id'] == $val->id) {{ 'selected' }} #endif value="{{ $val->id }}">{{ $val->name}}</option>
#endforeach
</select>
#endforeach

How to save array data from multiple select in Laravel using Eloquent

i'd like to save data from multiple select to the database. So a user can choose more than one products in a multiple select. I've tried the code like below but i got this error "ErrorException Array to string conversion".
Here is my blade.php
<div class="form-group row" style="display:none;" id="inputbarang">
<label class="col-form-label col-lg-3 col-sm-12">Barang</label>
<div class="col-lg-4 col-md-9 col-sm-12">
<select class="form-control m-select2" width="500px" id="kt_select2_1" name="id_product[]" multiple="multiple">
<option value=""></option>
#foreach($produk as $p)
<option value="{{ $p->id }}">{{ $p->product }}</option>
#endforeach
</select>
</div>
</div>
and here is my controller
$id_promo = Promo::select('id')
->where('delete', 0)->orderBy('created_at', 'DESC')
// ->take(1)
->pluck('id')->first();
$id_product = [];
$id_product[] = $request->id_product;
// $id_products = $id_product['id_product'];
foreach ($id_product as $i) {
DetailPromo::create([
'id_promo' => $id_promo,
'id_product' => $i,
'det_potongan' => $request->potongan,
'det_jumlah_potongan' => $request->jumlah_potongan
]);
}
Any helps will be appreciated, thank you so much
Try below code:
$id_promo = Promo::select('id')
->where('delete', 0)
->orderBy('created_at', 'DESC')
// ->take(1)
->pluck('id')
->first()
;
$id_products = $request->id_product;
foreach ($id_products as $id_product) {
DetailPromo::create([
'id_promo' => $id_promo,
'id_product' => $id_product,
'det_potongan' => $request->potongan,
'det_jumlah_potongan' => $request->jumlah_potongan
]);
}

Laravel: Check on which form submitted the request

On my website, users can display posts created by other users. However, I have 2 select boxes, one for ordering by name or date and the other is ordering by category. The way I have done it is incorrect and I am aware of that. The simple reason for this is that I don't know how to make an if check on which form submitted the request.
Here is my controller method for displaying the events:
public function getEvents(Request $request){
if($request['sort'] == "created_at"){
$posts = Post::orderBy('created_at', 'desc')->get();
}
elseif($request['sort'] == "title"){
$posts = Post::orderBy('title', 'desc')->get();
}
elseif($request['category'] == "sport"){
$post = Post::where('type', '=', 'sport' )->get();
}
elseif($request['category'] == "culture"){
$post = Post::where('type', '=', 'culture' )->get();
}
elseif($request['category'] == "other"){
$post = Post::where('type', '=', 'other' )->get();
}
else{
$posts = Post::orderBy('created_at', 'desc')->get();
}
return view ('eventspage', ['posts' => $posts]);
}
This is currently incorrect, I want it to follow this structure:
if(request submitted by 'sort')
then do this...
elseif(request submitted by 'category')
then do this...
Here is my view containing the 2 select boxes:
<div class="row">
<div class="col-md-6">
<form action="{{ route('events') }}">
<select name="category" onchange="this.form.submit()" class="form-control">
<option value="sport">sport</option>
<option value="culture">Culture</option>
<option value="other">Other</option>
</select>
</form>
</div>
<div class="col-md-6">
<form action="{{ route('events') }}">
<select name="sort" onchange="this.form.submit()" class="form-control">
<option value="created_at">Date</option>
<option value="title">Title</option>
</select>
</form>
</div>
</div>
You can have a hidden input in your form with name as formName and the respective values.
Then it's easy to check which form submitted.
//Category form
<input type="hidden" name="formName" value="category">
//Sort form
<input type="hidden" name="formName" value="sort">
Then, in the controller:
if($request['formName'] == 'category') //request submitted by 'category'
//then do this...
elseif($request['formName'] == 'sort') //request submitted by 'sort'
//then do this...
Just be careful not to put too much different code in both conditionals. If you find yourself having two entirely different functions, create an action for each form.

Separating a sort by filter/select

I have a form where i search for products on a few subjects, i also have a html select working with a php switch to enable the ability to sort the order of the results. this currently works in the search form and i want to make the sort by html select to work without clicking the the search button and to run the correct select option every time its changed and to instantly change the order of the products to match the select option.
Here is the HTML:
{!! Form::open(['route' => 's.index', 'method' => 'GET']) !!}
<div class="form-group">
{!! Form::label('productsname', 'Search By Name:') !!}
{!! Form::text('productsname', null, array('class' => 'form-control')) !!}
</div>
</div>
<div class="col-md-6">
<div class="form-group">
{!! Form::label('categories_id', 'Search By Category:') !!}
<select class="form-control" name="categories_id" >
<option value=""></option>
#foreach($types as $type)
<option value="{{$type->id}}">{{$type->name}}</option>
#endforeach
</select>
</div>
</div>
<div class = col-md-6>
<div class="form-group">
</div>
</div>
<div class="form-group">
<select class="form-control" name="SortbyList" >
<option value="1">Highest Avg</option>
<option value="2">Lowest Avg</option>
<option value="3">Another Sort option</option>
<option value="2">another sort option</option>
</select>
{!! Form::submit('Find Products', array('class' => ' btn-lg btn-block')) !!}
{!! Form::close() !!}
</div>
Here is the PHP:
public function index(Request $request)
{
//
$productsQuery = Product::where('approved', '=', 1)->leftJoin('reviews', 'reviews.products_id', '=', 'products.id')->select('products.*', DB::raw('AVG(ratings) as ratings_average' ))->groupBy('products.id');
switch ($request->SortbyList) {
case 1:
$productsQuery = $productsQuery->orderBy('ratings_average', 'DESC');
break;
case 2:
$productsQuery = $productsQuery->orderBy('ratings_average', 'ASC');
break;
case 3:
$productsQuery = $productsQuery->orderBy('ratings_average', 'ASC');
break;
case 4:
$productsQuery = $productsQuery->orderBy('ratings_average', 'ASC');
break;
default:
$productsQuery = $productsQuery->orderBy('ratings_average', 'DESC');
}
$name=$request->input('productname');
$location=$request->input('categories_id');
if(!empty($name)){
$sightsQuery->where('productname', 'LIKE', '%'.$name.'%')->get();
}
if(!empty($location)){
$sightsQuery->where('categories_id', $request->input('categories_id') )->get();
}
$products= $productsQuery->paginate(8);
return view('p.search')->withproducts($products);
}
If I understood correctly, you want to change the order without clicking on the submit button (and so, without changing/reloading the page)?
PHP can not dynamically update your page, but Javascript can.

Laravel 5.1 - Store input data in my session

I have a view show.php of my single product, when user click on ADD PRODUCT my controller CartController.php update my session cart and update my cartSession table,
Now i'm tryng to put new data (Color input,Size input, Quantity input) on my session and also in my CartSession table. But i dont know why it doesn't work.
-I think that the principal problem is that $request->get('input') doesn't pass to my CartController.php , i tried to return
$request->all() and there is not nothing.
CartController.php
namespace dixard\Http\Controllers;
use Illuminate\Http\Request;
use dixard\Http\Requests;
use dixard\Http\Controllers\Controller;
use dixard\Product;
use dixard\CartSession;
use dixard\CartItem;
use dixard\Shipping;
use Session;
// i think that all classes are ok
public function add(Product $product, CartSession $CartSession,Request $request)
{
$id = $request->get('id');
$cart = \Session::get('cart');
$product->quantity = $request->get('qty');
$product->size = $request->get('size');
$product->color = $request->get('color');
$cart[$product->id] = $product;
\Session::put('cart', $cart);
return $request->all(); // here i tried to get all inputs but it shows me nothing result
$subtotal = 0;
foreach($cart as $producto){
$subtotal += $producto->quantity * $producto->price;
}
$session_code = Session::getId();
$CartSession = new CartSession();
$session_exist = CartSession::where('session_code', $session_code)->orderBy('id', 'desc')->first();
if (isset($session_exist)) {
$s = new CartSession;
$data = array(
'subtotal' => $subtotal,
);
$s->where('session_code', '=', $session_code)->update($data);
}else {
$CartSession = new CartSession();
$CartSession->session_code = $session_code;
$CartSession->subtotal = $subtotal;
$CartSession->save();
}
//return $cart;
//salveremo tutte le informazioni nel array cart nella posizione slug
foreach($cart as $producto){
$this->saveCartItem($producto, $CartSession->id, $session_code, $cart);
}
return redirect()->route('cart-show');
}
Routes.php
Route::bind('product', function($id) {
return dixard\Product::where('id', $id)->first();
});
Route::get('cart/add/{product}', [
'as' => 'cart-add',
'uses' => 'CartController#add'
]);
show.php view
Get Data about the product is ok, title, description, color avaible, price ecc. all information pass to my view.
{!! Form::open(['route'=> ['cart-add', $product->id],'class'=>'form-horizontal form-label-left'])!!}
<input type="hidden" name="_method" value="PUT">
<input type="hidden" name="id" value="{{$product->id}}">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label for="p_color">Colore</label>
<select name="color" id="p_size" class="form-control">
#foreach($colors as $color)
<option value="{{ $color->color }}">{{ $color->color }}</option>
#endforeach
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="size">Size</label>
<select name="size" id="p_size" class="form-control">
<option value="XS">XS</option>
<option value="S">S</option>
<option value="M">M</option>
<option value="L">L</option>
<option value="XL">XL</option>
</select>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="qty">Quantity</label>
<select name="qty" id="p_qty" class="form-control">
<option value="">1</option>
<option value="">2</option>
<option value="">3</option>
</select>
</div>
</div>
</div>
<div class="product-list-actions">
<span class="product-price">
<span class="amount">{{$product->price}}</span>
<input type="submit" class="btn btn-lg btn-primary" >
ADD PRODUCT
</input>
</div><!-- /.product-list-actions -->
{!! Form::close() !!}
Thank you for your help!
You have to explicitly set the post-method to be "get" or you need to change your router to accept the request as post. Even though you're calling the route by name, Form::open defaults to "POST"
https://laravelcollective.com/docs/5.2/html#opening-a-form
Option 1. Change
Route::get('cart/add/{product}',...
to
Route::post('cart/add/{product}',...
Option 2. Change
{!! Form::open(['route'=> ['cart-add', $product->id],'class'=>'form-horizontal form-label-left'])!!}
to
{!! Form::open(['method'=>'GET', 'route'=> ['cart-add', $product->id],'class'=>'form-horizontal form-label-left'])!!}

Categories