Laravel 4 Multiple Search Fields - php

I am creating a search function in my Laravel 4 Application.
It is working great, in the fact that it is functioning well, the only thing that when I search for example in my postcode field and click search.
I want the value that I search to stay in the text input. Exactly like setting the value to be a php variable in standard PHP/HTML.
I have included my controller function and a text input field for you to see below. Any help would be greatly appreciated, thanks.
public function postSearch()
{
$search_order_from_date = Input::get('search_order_from_date');
$search_order_to_date = Input::get('search_order_to_date');
$search_order_type = Input::get('search_order_type');
$search_order_status = Input::get('search_order_status');
$search_order_agent = Input::get('search_order_agent');
$search_order_assessor = Input::get('search_order_assessor');
$search_order_postcode = Input::get('search_order_postcode');
$orders = DB::table('orders')
// ->where('order_date', '>=', $search_order_from_date, 'and', 'order_date', '<=', $search_order_to_date, 'or')
->orWhere('type', '=', $search_order_type)
->orWhere('epc_status', '=', $search_order_status)
->orWhere('agent', '=', $search_order_agent)
->orWhere('assessor', '=', $search_order_assessor)
->orWhere('postcode', '=', $search_order_postcode)
->orderBy('order_date', 'DESC')
->paginate();
Session::put('search', 'search query');
$users = User::all();
$userType = Session::get('type');
$perms = DB::table('permissions')->where('user_type', $userType)->first();
$this->layout->content = View::make('orders.index', compact('orders'), compact('perms'));
}
{{ Form::text('search_order_postcode', null, array('class'=>'form-control', 'placeholder'=>'Order Postcode')) }}

You can pass search_order_postcode to your view.
$this->layout->content = View::make('orders.index', compact('orders', 'search_order_postcode'), compact('perms'));
Add this in your index view or where ever the initial search form view is created, so you dont get an error if it does not exists.
Edit: Also pass it to your search view from you controller.
$search_order_postcode = (isset($search_order_postcode) && $search_order_postcode !== '') ? $search_order_postcode : null;
Then in your view:
// Search_order_postcode is either the value it was given or null
{{ Form::text('search_order_postcode', $search_order_postcode, array('class'=>'form-control', 'placeholder'=>'Order Postcode')) }}
Rinse repeat for other inputs, or store them in an array so you dont bloat your view::make, but this is personal preference.

Related

Laravel withQueryString does not exist after calling paginate method on query builder

Method Illuminate\Database\Eloquent\Collection::withQueryString does
not exist.
when i write this code it gives this error
blade;
<div class="float-right">{{ $modeller->withQueryString()->links()}}</div>
controller;
public function index(){
$modeller = Modeller::query();
$koleksiyonlar = Koleksiyon::all();
$modelistler = Modelist::all();
$uretim_sorumlulari = Uretim_sorumlusu::all();
if(request('model_kodu')){
$modeller = $modeller->where('ModelKodu', 'LIKE', "%".request('model_kodu')."%");
}
if(request('koleksiyon_id')){
$modeller = $modeller->where('koleksiyon_id', 'LIKE', "%".request('koleksiyon_id')."%");
}
if(request('uretim_sorumlusu_id')){
$modeller = $modeller->where('UretimSor', 'LIKE', "%".request('uretim_sorumlusu_id')."%");
}if(request('modelist_id')){
$modeller = $modeller->where('modelist_id', 'LIKE', "%".request('modelist_id')."%");
}
$modeller = $modeller->paginate(18);
return view('kumas.index',compact('modeller','koleksiyonlar','modelistler','uretim_sorumlulari'));
}
The paginate method, runs an implicit get on your query result.
try to use withQueryString instead of paginate.
example:
$modeller->withQueryString()->paginate(18);
but from your use case I suggest to use this in your view, instead of query string, this will add everything came from query string to your links:
{{ $users->appends($_GET)->links() }}
More Details on the pagination & Query String params
the page, offset, ... and everything paginate needs, would append automatically to paginate function without any effort.
you only need to explicitly ->appends($_GET) when you have some filtering parameters in your $_GET and want to preserve them in the following requests, when user clicks the next page or previous page
to expand on #Abilogos answer, I think it is better to use Request::except('page') method, which return an array of query parameter except the page parameter
in your blade view:
{{ $users->appends(\Request::except('page')->links() }}

Updating record in Laravel from a select using laravel's lists not working

In one of my laravel pages I am updating a record. The form is bound to the model, and all fields are updating properly except those where I am presenting a select using lists that populates the select from the database:
{{ Form::select('resume_id', $resume_lists) }}
I just have no idea why these will not update. They are pulling the appropriate values from mySQL. Any ideas?
Thank you.
I have my code in routes, not in a controller
Route::get('application/edit/{id}', array('as' => 'application.edit', function($id)
{
$user = Auth::user();
$company_lists = Company::where('user_id', '=', $user->id)->get()->lists('company', 'id');
$resume_lists = Resume::where('user_id', '=', $user->id)->get()->lists('name', 'id'); //changed resume to name
$companies = Company::where('user_id', '=', Auth::user()->id)->get(); //just added
//$currentintdate=$application['followupBy']; /////
Session::put('appid', $id); /////
return View::make('application-edit', array('company_lists' => $company_lists), array('resume_lists' => $resume_lists))
->with('application', Application::find($id));
}));
try this:
$resume_lists = YourResumeModel::lists('title', 'id');
{{ Form::select('resume_id', $resume_lists) }}
frist column is your text for dropdown
and next column is your row id
just var dump the resume list data in controller, make sure its available at the controller, so after you initialize the variable/array
return var_dump($resume_lists); // check if its valid array with id as key and label as value, if available, go view and do the same
Use: $resume_lists = Resume::all()->where('user_id', '=', $user->id)->lists('name', 'id');
Or: $resume_lists = Resume::where('user_id', '=', $user->id)->lists('name', 'id')->toArray();
well, my records were not updating because I had a column as not nullable and I was not passing any value while testing. I got no error at all about this so I had no idea.

Laravel returning multiple views

I'm trying to return multiple views using the laravel framework. When I return the variable, it only makes it through the loop once, therefore only one comment is displayed on the page.
foreach($index_comments as $comments){
$commentComment = $comments->comment;
$index_children = NULL;
$getUser = DB::table('users')->where('id', '=', $comments->from_user_id)->get();
foreach ($getUser as $user) {
$firstName = $user->first_name;
$lastName = $user->last_name;
}
return View::make('feeds.comments')->with(array(
'firstName' => $firstName,
'lastName' => $lastName,
'commentComment' => $commentComment,
'index_children' => $index_children
));
}
I just need a way of returning multiple views.
Thanks for any help!
Toby.
It seems that you don't quite understand the concepts of Laravel and/or PHP yet. So let's start it from scratch: We want to fetch all comments, output the comment and the name of the user who wrote the comment.
At a very basic level, we can just grab it straight from the DB with the query builder:
public function showComments()
{
$commentData = DB::table('comments')
->join('users', 'users.id', '=', 'comments.from_user_id')
->get(['text', 'firstName', 'lastName']);
return View::make('feeds.comments')->with('commentData', $commentData)
}
And in your view:
#foreach($commentData as $comment)
{{ $comment->text }}
<br />
written by {{ $comment->firstName }} {{ $comment->lastName }}
<hr />
#endforeach
That's it. You don't return the view on each iteration, the iteration happens in the view. The return statement terminates the function execution immediately. If you return within in a loop, it will always exit upon the first iteration, that's why you're getting only one result.
In the next step, you should play around with Models and Eloquent for even more powerful and readable data handling.

AND operator on Laravel 4

I am trying to fetch 3 values = 2 select forms and 1 from date form and compare it to the one's on my database if it's equal but whenever I tried to compare the 3 of them using the AND operator in laravel, it doesn't give me any details. How can I compare them correctly?
OnewayflightController.php
public function onewayflightresults()
{
$search1 = Input::get('destinationto');
$search2 = Input::get('destinationfrom');
$search3 = Input::get('departure');
$results = DB::table('oneways')->where('destinationto','=',$search1)
->where('destinationfrom','=',$search2)
->where('destinationfrom','=',$search3)
->get();
var_dump($results);
}
Database:
id-1
destinationto-Australia
destinationfrom-Japan
departure-01-2-14
onewayflight.blade.php
<div>
{{ Form::label('label','From: ') }}
{{ Form::select('destinationfrom', $destinationfrom)}}
</div>
<div>
{{ Form::label('destinationto','To: ') }}
{{ Form::select('destinationto', $destinationto)}}
</div>
<div>
{{ Form::label('departure','Departure:', array('class'=>'"input-group-addon btn"'))}}
{{ Form::text('departure', '', array('id' => 'calendar')) }} <span class="glyphicon glyphicon-calendar"></span>
{{ Form::close() }}
UPDATE
I've changed
->where('destinationfrom','=',$search3)
to
->where('departure','=',$search3)
But still gives me no results.
Your third where should be searching departure, not destinationfrom a second time.
Problem with
->where('destinationfrom','=',$search3)
Update your to
->where('departure','=',$search3)
I think that will work.
Need to update you third where condition. you are comparing destinationfrom value two times.
I think you are looking to a collection, and think that is not a result.
Try:
foreach($results as $result)
{
var_dump($result);
}
This will dump all the rows found with your input. Only want 1 result? change ->get(); to ->firstOrFail(). Then you can dump $results without a foreach.
Or maybe a subquery is the solution?
$results = DB::table('oneways')
->where('destinationto', '=', $search1)
->where('destinationfrom', '=', $search2)
->where(function($query) {
return $query->where('departure', '=', $search3)
})
->get();
Is there only 1 result you are trying to get? Maybe this is better:
$results = DB::table('oneways')
->where('destinationto', '=', $search1)
->where('destinationfrom', '=', $search2)
->where(function($query) {
return $query->where('departure', '=', $search3)
})
->firstOrFail();
This will give you 1 result, not a collection.
If this doens't work, you can try dumping your input to check if its filled correctly:
public function onewayflightresults()
{
dd(Input::all());
// Rest of the code
}
If the values in Input::all(); are exactly the same as the values in your database, the query should give you the result. If not, try this to futher debug:
dd(DB::table('oneways')->where('id', '=', 1)->first());

Laravel 4 - Too much logic in my view template?

i created a search functionality within my Laravel project - the user can search for teamnames or usernames - the result is created and returned like this:
$teams_obj = Team::where('teamname', 'LIKE', '%'.Input::get('searchterm').'%')->get();
$persons_obj = User::where('name', 'LIKE', '%'.Input::get('searchterm').'%')->orWhere('vorname', 'LIKE', '%'.Input::get('searchterm').'%')->get();
return View::make("team.search-content", array('resp' => 'resultlist', 'teams_obj' => $teams_obj, 'persons_obj' => $persons_obj))->with('user', User::find(Auth::user()->id));
Now its getting a little more complicated. I have a database table "relation" which stores if a user is a member of a team via an entry containing user_id and team_id. Laravel knows this relation.
If the search result is displayed within the view, i have to make a distinction if the current user is already a member in the respective team which is displayed in the current row. If the user is already a member within the team he should not be able to apply, otherwise he should have the option to apply.
I solved it with this:
#foreach($teams_obj as $team_obj)
<li data-teamid="{{ $team_obj->id }}">
<span>{{ $team_obj->teamname }}</span>
<?php
$data = ['user_id' => $user->id, 'team_id' => $team_obj->id];
$res = $team_obj->whereHas('Relation', function($q) use ($data) {
$q->where('team_id', '=', $data['team_id']);
$q->where('user_id', '=', $data['user_id']);
})->get();
if (count($res) == 0) {
echo'apply fct available';
}
?>
</li>
#endforeach
I fetch the relation and check if the relation of team_id and user_id is existent. But i have a strange feeling doing this within my view template. What do you think? How can i improve this?
Additionally i think it is strange that i have to make $q->where('team_id'), as I already do $team_obj-> ... but otherwise it is not working correctly.
Any help is appreciated. Thanks!
Do you have any need to show teams that your user cannot apply ? if not you can simply modify your code to get teams that your user is not a member. If you need you can do some checkup in the controller in order to get that information.
I suggest making a foreach for the every team and checking if they have relationship with the user. You can set an attribute in a team to check in the view.
Controller:
foreach($teams_obj as $team_obj){
$res = $team_obj->whereHas('Relation', function($q) use ($data) {
$q->where('team_id', '=', $data['team_id']);
$q->where('user_id', '=', $data['user_id']);
})->get();
if(count($res) == 0)
$team_obj->isApplyableByUser = true;
else
$team_obj->isApplyableByUser = false;
// You can do the same code above in one line, but it's not that compreensive
$team_obj->isApplyableByUser = count($res) == 0;
}
View:
if($team_obj->isApplyableByUser) echo'apply fct available';
Yes, too much logic for a view (in terms of best practices)
Do you have relationships set up for these? Assuming Team hasMany('User')... Why not just eager load your User models?
$teams = Team::with(['users' => function($query){
$query->where('name', 'LIKE', '%'.Input::get('searchterm').'%')
->orWhere('vorname', 'LIKE', '%'.Input::get('searchterm').'%')
}])where('teamname', 'LIKE', '%'.Input::get('searchterm').'%')
->get();
return View::make('your.view', ['teams' => $teams]);
// And in your view.
#foreach($teams as $team)
<li data-teamid="{{ $team->id }}">
<span>{{ $team->teamname }}</span>
#if(!$team->users->count())
apply fct available
#endif
</li>
#endforeach

Categories