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());
Related
public function countPeople($id = 0, $country = false)
{
if ($id == 0) {
$s = Group::leftJoin('user_hobbies', 'user_hobbies.hobby_id', '=', 'groups.hobby_id')
->where('groups.hobby_id', $this->hobby_id)
->select(DB::raw('count(user_hobbies.user_id) as count'))
->get()
->first();
} else if ($country) {
$s = Group::leftJoin('user_hobbies', 'user_hobbies.hobby_id', '=', 'groups.hobby_id')
->leftJoin('user_locations', 'user_locations.user_id', '=', 'user_hobbies.user_id')
->leftJoin('cities', 'cities.id', '=', 'user_locations.city_id')
->where('groups.hobby_id', $this->hobby_id)
->where('cities.country_id', $country)
->select(DB::raw('count(user_hobbies.user_id) as count'))
->get()
->first();
} else {
$s = Group::leftJoin('user_hobbies', 'user_hobbies.hobby_id', '=', 'groups.hobby_id')
->leftJoin('user_locations', 'user_locations.user_id', '=', 'user_hobbies.user_id')
->where('groups.hobby_id', $this->hobby_id)->where('user_locations.city_id', $id)
->select(DB::raw('count(user_hobbies.user_id) as count'))
->get()
->first();
}
if ($s) {
return $s->count;
}
return 0;
}
Beginner here.. I'm using another persons code to try to learn/understand a few problems. There exists this function in the controller that counts members in a group, but it doesn't give access to that persons other information, like name, photo.. etc.. Is it possible from this function to use the same function and return it as a view? Would that give me the access to the user information?
I'm not yet so well informed on how to query the DB so fluently.
Any help useful! thank you.
Since this query returns an aggregate value (count) you won't be able to get any user information from it. However, you could remove the ->select(DB::raw('count(user_hobbies.user_id) as count')) part which would end up returning a Collection with all the information from the joined tables. To get the count from that, just use the Collection's ->count() method.
$groups = Group::leftJoin('user_hobbies', 'user_hobbies.hobby_id', '=', 'groups.hobby_id')
->where('groups.hobby_id', $this->hobby_id)
->get();
#foreach ($groups as $group)
<p>{{ $group->hobby_id; }}</p>
<p>{{ $group->user_id; }}</p>
#endforeach
<p>Count: {{ $groups->count() }}</p>
Im using Chart.js to show the number of bookings for each month. This is my query. It is working fine.
My problem is if there is no booking in a month then it doesnt show anything. No zero value. On the chart i get the value like
January 23
February 34
April 23
May 25
July 42
March and June are shown on the chart..How can i get the value Zero for months where there is no booking..
$graph = DB::table('bookings')
->select(DB::raw('MONTHNAME(created_at) as month'), DB::raw("DATE_FORMAT(created_At,'%M %Y') as monthNum"), DB::raw('count(*) as totalbook'))
->groupBy('monthNum')
->orderBy('created_at', 'asc')
->get();
To get months,`
#foreach ($graph as $dat)
"{!! $dat->monthNum !!}",
#endforeach`
And to get booking numbers
#foreach ($graph as $dat)
{!! $dat->totalbook !!},
#endforeach
MySQL will not fill in the months that aren't available, it will simply group by what you have available and then give you those results.
What you could do is use DatePeriod and Laravel's Collection class:
$results = DB::table('bookings')
->selectRaw("DATE_FORMAT(created_At,'%Y-%m-01') as monthNum, count(*) as totalbook")
->orderBy('monthNum')
->groupBy('monthNum')
->get();
$results = collect($results)->keyBy('monthNum')->map(function ($item) {
$item->monthNum = \Carbon\Carbon::parse($item->monthNum);
return $item;
});
$periods = new DatePeriod($results->min('monthNum'), \Carbon\CarbonInterval::month(), $results->max('monthNum')->addMonth());
$graph = array_map(function ($period) use ($results) {
$month = $period->format('Y-m-d');
return (object)[
'monthNum' => $period->format('M Y'),
'totalbook' => $results->has($month) ? $results->get($month)->totalbook : 0,
];
}, iterator_to_array($periods));
Please note I have updated monthNum in the query as it will be reformatted later.
Also, you should need to use the blade raw tags ({!! !!}) for this as {{ $dat->totalbook }} should work absolutely fine.
Hope this helps!
You have to set zero when there are no records for counting.
Change your query something like this:
$graph = DB::table('bookings')
->select(DB::raw('MONTHNAME(created_at) as month'),
DB::raw("DATE_FORMAT(created_At,'%M') as monthNum"),
DB::raw('ifnull(count(*),0) as totalbook'))
->groupBy('monthNum')
->orderBy('created_at', 'asc')
->get();
Hope you understand.
In blade you can simply use
#foreach ($graph as $dat)
{{ $dat->totalbook ? $dat->totalbook : 0 }},
#endforeach
This checks if $dat->totalbook exists and if it does then displays the value, else will show 0.
Use eloquent
Model::withCount('members')
->having('members_count', '>', 0)
->get();
Use query builder doc
$users = DB::table('users')
->groupBy('account_id')
->having('account_id', '>', 100)
->get();
I want to access values from my query in view.
$bookings = DB::table('bookings')
->join('staffs', 'staffs.id' , '=', 'bookings.staff_id')
->join('customers', 'customers.id' , '=', 'bookings.customer_id')
->select('bookings.id', 'bookings.start_time', 'bookings.end_time', 'bookings.service', 'staffs.name as Staff-Name', 'customers.name as Customer-Name')
->orderBy('customers.name', 'desc')
->get();
return view('booking.index')->with('bookings', $bookings);
This is simple enough to understand. What I am trying to do is that i want to get start_time, end_time which are in bookings table, name which is staffs table also name in customers table.
Right now I am doing like:
#foreach($bookings as $booking)
{{ $booking->start_time }}
{{ $booking->end_time }}
{{ $booking->name }} // name column which is in customers table
#endforeach
But these things don't seem to work.
It's all because you are using column names instead of aliases which you set.
Take a look at it, by example customers.name is named Customer-Name.
->select('bookings.id', 'bookings.start_time', 'bookings.end_time', 'bookings.service', 'staffs.name as Staff-Name', 'customers.name as Customer-Name')
If you want to access data you need to do it like that:
#foreach($bookings as $booking)
{{ $booking->start_time }}
{{ $booking->end_time }}
{{ $booking->Customer-Name }} // name of alias
#endforeach
Anyway I don't think that dash in alias is good solution, you should use underscore instead. (customers.name as Customer_Name) and $booking->Customer_Name
Try this
$bookings = DB::table('bookings')
->join('staffs', 'staffs.id' , '=', 'bookings.staff_id')
->join('customers', 'customers.id' , '=', 'bookings.customer_id')
->select('bookings.id', 'bookings.start_time', 'bookings.end_time', 'bookings.service', 'staffs.name as Staff-Name', 'customers.name as Customer-Name')
->orderBy('customers.name', 'desc')
->get();
return view('booking.index')->with(compact('bookings'));
The $bookings contains an array of data. You can print these in your view ike this..
#foreach($bookings as $booking)
{{$booking->start}}
{{$booking->end_time}}
#endforeach
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
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.