Laravel eloquent issue getting db datas - php

I'm having a problem getting some datas from my database via eloquent:
at first I do this to get 'id' and 'capMax' from clase_schedule table:
$plazas = DB::table('clase_schedule')->select(['schedule_id', DB::raw('SUM(capMax) as capMax')])->groupBy('schedule_id')->get();
and then i want to get the the name of table schedule where the id i got before coincides with the one on this table, like this:
$nom_horarios = DB::table('schedule')->select('name')->where('id', 'in', $plazas->schedule_id)->get();
I get this error:
"Trying to get property of non-object"

Since, $plazas is an array so you should loop the $plazas to get the value in next query as below :
foreach ($plazas as $plaza)
{
$nom_horarios[] = DB::table('schedule')->select('name')->where('id', 'in',$plaza->schedule_id)->get();
}
print_r($nom_horarios);

$plazas returns an array of items, instead of get(), use first(). This will return single item.
$plazas = DB::table('clase_schedule')->select(['schedule_id', DB::raw('SUM(capMax) as capMax')])->groupBy('schedule_id')->first();
Or loop plazas in foreach

What is returning in the $plazas variable?
I think the problem is you are getting a collection and not a item... If you want to get just one plaza you should ->first() instead of ->get();

Related

How to get count of each result

How can I get the total number of records for each of the grouped column(some_id) results generated in this eloquent query? (Answers generated using DB query builder or vanilla PHP also welcome).
$results = \App\MyModel::groupBy('some_id')
->whereNotNull('some_id')
// some query here to get sum of each grouped column records
->get();
The desired result would be such that when I'm looping through the results, I can also have a field called for example totalRecords for each grouped results. i.e.
foreach($results as $result) {
echo $result->totalRecords;
}
$results = DB::table('your_table')
->select('some_column_name', DB::raw('count(some_id) as totalRecords'))
->whereRaw('some_id IS NOT NULL')
->groupBy('some_id')
->get();
You can do like this :-
$results = \App\MyModel::select('*', DB::raw('count(some_id) as totalRecords'))
->groupBy('some_id')
->whereNotNull('some_id')
->get();
foreach ($results as $result) {
echo $result->totalRecords;
}
Collection Provide itself count() method.
But sometime once you fetch whole collection using get(). You can use count method on collection something like this:
$results = \App\MyModel::groupBy('some_id')
->whereNotNull('some_id')
// some query here to get sum of each grouped column records
->get();
dd($results->count());
Also, If your data is not collection then Php array's provide you count method you can use that too:
dd(count($results));
I used dd method just for debuging purpose.That will show you result before actual output.
count() method of array will help you to count collection as well as sub collection or array of sub array.
Good luck !!!

retrieve single row in LARAVELusing eloquent

i am using laravel 5.1 and want to retrieve a single row in the database then manipulate it after.
my current code is
$profiles = Profile::where('user_id', $this->user->user_id)
->where('profile_code', $this->user->profile_code)
->get();
foreach($profiles as $profile ){
$data['address'] = $profile->address;
}
why cant i do it like this?
$profiles = Profile::where('user_id', $this->user->user_id)
->where('profile_code', $this->user->profile_code)
->get();
$data['address'] = $profiles->address;
am i using a wrong function or something?
thanks in advance.
Try this:
$data['address'] = $profiles[0]->address;
When you are using get(), it returns an array of Std class object.
In addition to retrieving all of the records for a given table, you may also retrieve single records using first. Instead of returning a collection of models, these methods return a single model instance:
// Retrieve the first model matching the query constraints...
$flight = App\Flight::where('active', 1)->first();
laravel 5.8
Retrieving A Single Row / Column From Profile
If you just need to retrieve a single row from the database table, you may use the first() method. This method will return a single stdClass object:
$Profile = DB::table('Profiles')->where('user_id', $this->user->user_id)
->where('profile_code', $this->user->profile_code)->first();
If you don't even need an entire row, you may extract a single value from a record using the value() method. This method will return the value of the column directly:
$address = DB::table('Profiles')->where('user_id', $this->user->user_id)
->where('profile_code', $this->user->profile_code)->value('address');

Getting value from database column Laravel

May be is simple but I have one table where I want to take value from one column. They are two records and always will be two records and I need value from second id.. Here is visual
id key value
1 key_1 Value_1
2 key_2 value_2
I want to take value_2. Here is what I have in my controller
$free = DB::table('settings')->select('value')->where('key', '=', 'free')->get();
return View::make('site.cart.order', [
'cart' => $cart,
'free' => $free
]);
And in my view I'm trying this
#if( $total < $free['value'] )
// loop
#endif
Currently I'm getting - Undefined index: value
If I'm right Laravel returns a standard class there and you should access it like this.
$free->value
Instead of
$free['value']
But you have to change now it selects the first record
$free = DB::table('settings')->select('value')->where('key', '=', 'free')->first();
Then you can access it like
$free->value
Or if you don't want to change get() to first() you can access it like this because get() returns an array.
$free[0]->value
Use first() instead of get() and use $free->value, get() return an array of object

Store the result of an sql query to a variable (without For each) (Laravel)

I'm new to Laravel and i need your help please.
This runs on my controller and the result should be "3" as long as I have 3 rows with that title in the same table.
$countcategories = DB::table('categories')
->select(DB::raw('count(title) as result'))
->where('title','=','dsds')
->get();
I'm passing the query result to the view like this->with('counts', $countcategories)
And now my questions are:
In the view I can only display the result by using foreach. Why? My query returns only one row.
I want to store the query result in a variable inside my controller in order to use that result. How can I do that?
Thank you very much!
you should use ->first() method:
$countcategories = DB::table('categories')
->select(DB::raw('count(title) as result'))
->where('title','=','dsds')
->first();
What you are getting are rows from a result, it tunrs out there is only one in your situation.
You have already done that.
Anyways, here's my approach:
// The result
$categories = Category::where('title','=','dsds');
foreach( $categories->all() as $category ) {
echo $category->title . "\n";
}
// The count
echo $categories->count();

Eloquent and Pivot Tables in Laravel 4

I have a Poll table, a Students table, and a pivot table between them that includes a token and their three votes.
public function students()
{
return $this->belongsToMany('Student', 'polls_students')->withPivot('token','first','second','third');
}
While working out saving the poll results, I came across some odd behavior that I don't quite understand. I'm hoping somebody can explain what it is I'm missing:
$poll = Poll::find(Input::get('poll_id'));
foreach($poll->students()->where('students.id', '=', Input::get('student_id'))->get() as $student){
var_dump($student->pivot->token);
}
$student = $poll->students()->where('students.id', '=', Input::get('student_id'))->get();
var_dump($student->pivot->token);
In the above code, the foreach loop will successfully display the token, where the second one throws the exception Undefined property: Illuminate\Database\Eloquent\Collection::$pivot
What am I missing? Are these two calls not logically creating the same object? How is 'pivot' working on the first and not the latter?
You first example:
$poll = Poll::find(Input::get('poll_id'));
foreach($poll->students()->where('students.id', '=', Input::get('student_id'))->get() as $student){
var_dump($student->pivot->token);
}
Here $poll->students() retrieves a collection and because of foreach loop you get a single object in your $student variable and you can use $student->pivot->token
You second example:
$student = $poll->students()->where('students.id', '=', Input::get('student_id'))->get();
var_dump($student->pivot->token);
Here you are doing same thing, using $poll->students() you are getting a collection but this time you are not using a loop and trying to do same thing using $student->pivot->token but it's not working because you didn't define any index from which you want to get the pivot->token, if you try something like this
$student->first()->pivot->token
Or maybe
$student->get(1)->pivot->token
Or maybe you can use first() instead of get() like this
$student = $poll->students()->where('students.id', '=', Input::get('student_id'))->first();
Then you can use
$student->pivot->token
Remember that, get() returns a collection even if there is only one record/model.
$poll = Poll::find(Input::get('poll_id'));
foreach($poll->students as $student){
var_dump($student->pivot->where('student_id',$student->id)->where('poll_id',$poll->id)->first()->token);
}

Categories