Laravel pagination link doesn't work during empty input - php

I am trying to show all data from my table in my laravel blade view.
Controller
public function search()
{
$search = request('show');
$users = User::query();
foreach ($search as $field=>$value)
{
if($value!=NULL)
{
$users = $users->where($field, 'LIKE', '%'.$value.'%');
}
}
if(request()->has('sort'))
{
$order = explode(',',request('sort'));
$users = $users->orderBy($order[0],$order[1]);
}
$users = $users->SimplePaginate(15);
return view('nabil.homepage',compact('users'));
}
Blade
#foreach($users as $user)
<tr>
#if(session()->has('show'))
#foreach(session()->get('columns') as $column)
#if(in_array($column,session()->get('show')))
<td>{{ $user->$column }}</td>
#endif
#endforeach
#endif
</tr>
#endforeach
</table>
{{ $users->appends(Illuminate\Support\Facades\Input::except('page'))->links() }}
If I search something then it works perfectly. But if I search with blank value. Then it doesn't work. The first page comes without any problem but then it breaks.
Case 1 (problematic case):
I input an empty value in search. So the search url is /search?show%5Bbango%5D= .
However, when I click next then the url becomes /search?page=2 (And returns error)
If I manually input /search?show%5Bbango%5D=&page=2 in url address then it works perfectly.
Case 2:
I input some data like '123' in search. Then my url becomes /search?show%5Bbango%5D=123 .
In that case everything works perfectly.
Case 3:
It may be irrelevant. But if I run query in more than one field then it works ok but somehow all empty inputs get removed from url when I use pagination.
I may try to search with two input fields (example: name and bango). If I keep the name field empty and put '123'in bango then the url becomes like /search?show%5Bbango%5D=123&show%5Bname%5D=.
However, if I try to go to next page. then the url becomes /search?show%5Bbango%5D=123&page=2.
Although, the showed results are good but url suddenly drops the name field.
How can I make sure that the pagination still works for empty input. I checked in some similar questions and tried appending query request. But it still doesn't work for me.

Since you are using foreach, it is expecting an array. Try to set
$search = request('show') ?? [];
on the controller.

Related

Laravel if statement in form generator to select checkbox

I want to automatically select a checkbox when the field in the database is filled in.
I am trying to use #if statement in the Form generator but it is not checking the checkbox.
Here is the code I am using:
{!! Form::checkbox('offer_made', 'offer_made', #if(empty($phase_2->offer_made)) 1 #endif) !!}
Im sending this over to the view in my Controller:
public function show(Order $order)
{
$order = Order::where('id', $order->id)->first();
$current_phase = $order->current_phase;
if($current_phase == 1) {
$phase_2 = Order_Phase_2::where('order_id', $order->id)->first();
return view('orders.phase-2', compact('order', 'phase_2'));
}
}
When I echo $phase_2->offer_made in the view it shows 1 so the value is coming through but the if statement is not working inside the Form builder.
Anyone knows how to fix this?
Thanks already!
You might be checking for the value incorrectly:
#if(empty($phase_2->offer_made)) 1 #endif)
This outputs a 1 if the value is empty. You should be checking for !empty() if I understand the field correctly.
So you might have success with this:
#if(!empty($phase_2->offer_made)) 1 #else 0 #endif)
Is the value 1/0 itself? Use $phase_2->offer_made directly as the third parameter.
use ternary operator as you cannot use blade syntax in php code. Try something like this:
{!! Form::checkbox('offer_made', 'offer_made',(!empty($phase_2->offer_made)) ? 'checked' : '') !!}

Output value from table in view

I've got a problem in Laravel. I have passed my whole table to my view like this from my controller:
$usersTable = DB::table('users')->get();
return view('users')->with('users', $usersTable);
In a foreach loop I can perfectly get each of the values like this in my view:
#foreach($users as $user => $value)
<div class="projectBox">
<br><span class="projectBoxName">{{ $value->name }}</span>
#php
echo Form::image('/images/edit.png', "",['class' => "editUserBtn", 'userId' => $value->id]);
#endphp
<br><span class="projectBoxSmallText projectBoxEmail">{{ $value->email }}</span>
<br><span class="projectBoxSmallText projectBoxId">ID: {{ $value->id }}</span>
<br><span class="projectBoxSmallText projectBoxProjects">Currently no projects</span>
</div>
#endforeach
But I also need to access these values outside my foreach loop, how can I do that?
echo Form::text('email', "$users->$value->email", array('placeholder' => "Email"));
Ain't working...
This gives my the whole object in this form
[{"id":"1","name":"Administrator","email":"admin#mail.com","password":"$2y$10$Re3Ahf.SwU5vj4UvtU5Dy.jxaZMsUNC2WhuJMwsNy9gu6TST4PuRG","remember_token":null}]
How to get only the email? I also tried using indexes, but those weren't working.
Thanks!
Edit:
Full situation:
I have a list of users with their extra information (mail, tel,...). In those user-boxes there is a button which says 'edit user' when I click that a modal opens giving the current mail and tel. So I can't say in my controller WHO's mailaddress to return because I only know that at the moment the user clicks a client-side button.
Images: http://imgur.com/a/krDrY
(Edit button is that small circle with three dots).
To access a collection without using loop, you should use collection methods:
$users = User::get();
$users->where('name', 'John Smith')->first()->email
This will not create any additional queries since you've already eager loaded data.
If you want to load just one user, use first() instead of get():
$users = User::first();
If you'll use get() and then [0] or first() like some guys recommend here, you'll load all users data into the memory for each request which will overload your server.
Also, using indexes to access data (like $users[4]['email']) is a bad practice. Avoid it if possible.
You need to add as first element by adding [0]
echo Form::text('email', $users[0]->email, array('placeholder' => "Email"));
I suggest use ->first() instead of ->get() to get single object. And remove loop and use anywhere you want.
You are using a collection of users to get the first user's email, you do
$users->first()->email;
Looks like it's coming in as JSON. Try json_decode($data) and $data->email to get that attribute.

How to access URL segment(s) in blade in Laravel 5?

I have a url : http://localhost:8888/projects/oop/2
I want to access the first segment --> projects
I've tried
<?php echo $segment1 = Request::segment(1); ?>
I see nothing print out in my view when I refresh my page.
Any helps / suggestions will be much appreciated
Try this
{{ Request::segment(1) }}
BASED ON LARAVEL 5.7 & ABOVE
To get all segments of current URL:
$current_uri = request()->segments();
To get segment posts from http://example.com/users/posts/latest/
NOTE: Segments are an array that starts at index 0. The first element of array starts after the TLD part of the url. So in the above url, segment(0) will be users and segment(1) will be posts.
//get segment 0
$segment_users = request()->segment(0); //returns 'users'
//get segment 1
$segment_posts = request()->segment(1); //returns 'posts'
You may have noted that the segment method only works with the current URL ( url()->current() ). So I designed a method to work with previous URL too by cloning the segment() method:
public function index()
{
$prev_uri_segments = $this->prev_segments(url()->previous());
}
/**
* Get all of the segments for the previous uri.
*
* #return array
*/
public function prev_segments($uri)
{
$segments = explode('/', str_replace(''.url('').'', '', $uri));
return array_values(array_filter($segments, function ($value) {
return $value !== '';
}));
}
The double curly brackets are processed via Blade -- not just plain PHP. This syntax basically echos the calculated value.
{{ Request::segment(1) }}
Here is how one can do it via the global request helper function.
{{ request()->segment(1) }}
Note: request() returns the object of the Request class.
An easy way to get the first or last segment, in case you are unsure of the path length.
$segments = request()->segments();
$last = end($segments);
$first = reset($segments);
Here is code you can get url segment.
{{ Request::segment(1) }}
If you don't want the data to be escaped then use {!! !!} else use {{ }}.
{!! Request::segment(1) !!}
https://laravel.com/docs/4.2/requests

Redirect back to form with data in laravel

I have this function in the controller.
public function newsedit($id)
{
$editNews = $this->agro->find($id);
//return $editNews;
return Redirect::back()->with('editNews',$editNews);
//return View::make('agro.show')->with('editNews',$editNews);
}
The return $editNews displays data, so there is data in $editNews.Now i am trying to pass the same data to the view using redirect as shown in the above code.
But apparently the value is not passed. The following code shows the value is not availabel in the view
#if(isset($editNews))
<h1> value availabel</h1>
#else
<h1> No value </h1>
#endif
It displays No value . Please help me pass the data to view.I don't understant where have i gone wrong.
Laravel 4:
#if(Session::has('editNews'))
Laravel 5:
#if(session()->has('editNews'))
If you want to get the data, replace has() with get()
return View::make('agro.show', ['editNews' => $editNews]);
You can simply use
#if( Session::get( 'editNews' ) )
// show something
#endif
in Laravel 4 - it will return false to the #if block if the variable is not set

Empty search results Laravel 4

I am making a simple search engine in which, If the selected list from the dropdown would match with the one inside the 'destinationto' column from the database then it would fetch all the items inside that row. But when I hit the find button, it would not return any item from the database. It would be giving me an empty array.
object(Illuminate\Database\Eloquent\Collection)[141]
protected 'items' =>
array (size=0)
empty
What have I done wrong?
Here are the snippets
OnewayflightControllers.php:
public function onewayflightresults()
{
$destinationto = Input::get('destinationto');
$results = Oneways::where('destinationto','=',$destinationto)->get();
var_dump($results);
}
public function onewayflight()
{
$onewaysfrom = DB::table('oneways')->distinct()->lists('destinationfrom');
$onewaysto = DB::table('oneways')->distinct()->lists('destinationto');
return View::make('content.onewayflight')->with(['destinationfrom'=>$onewaysfrom,'destinationto'=>$onewaysto]);
}
onewayflight.blade.php:
{{ Form::label('destinationto','To: ') }}
{{ Form::select('destinationto', $destinationto)}}
It's only a guess but you should make sure you have only one form element with name destinationto
If you have in form for example
{{ Form::label('destinationto','From: ') }}
{{ Form::select('destinationto', $destinationfrom)}}
{{ Form::label('destinationto','To: ') }}
{{ Form::select('destinationto', $destinationto)}}
If you think it's ok, you should add var_dump($destinationto); to your function to make sure value is what you expect
EDIT
I thought select will use values as keys but it's not so you should probably do something like that:
$onewaysfrom = DB::table('oneways')->distinct()->lists('destinationfrom','destinationfrom');
$onewaysto = DB::table('oneways')->distinct()->lists('destinationto','destinationto');
and not:
$onewaysfrom = DB::table('oneways')->distinct()->lists('destinationfrom');
$onewaysto = DB::table('oneways')->distinct()->lists('destinationto');

Categories