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');
Related
I want to combine two data search results into one array, I use array_merge but there is an array_merge() error:
Argument # 1 is not an array
How to turn $vendor's eloquent results into an array and combine it with $plucked?
$vendor = Vendor::find($id);
$vendor_detail = VendorDetail::where('vendor_id',$id)->get();
$plucked = $vendor_detail->pluck('vendor_profile_value','vendor_profile_name');
$coba = array_merge($vendor,$plucked);
$plucked already an array
I think the problem here is that $vendor is not yet an array
You could do it like this:
$vendor = Vendor::find($id);
$vendor_details = VendorDetail
::select('vendor_profile_value', 'vendor_profile_name')
->where('vendor_id', $id)
->get()
->toArray();
$coba = array_merge($vendor,$vendor_details);
The get() method execute the query returning a Collection instance, in which you can call the toArray() method.
Side note
As far as I can see, you could make use of relationships and eager loading.
If you have a one-to-many relationship defined like this in your Vendor model:
public function details()
{
return $this->hasMany(VendorDetails::class);
}
Then, you could eager load the relationship like this:
$vendor = Vendor::with('details')->find($id);
// ^^^^^^^^^^^^^^
You could even just load the wanted fields:
$vendor = Vendor::with('details:vendor_profile_value,vendor_profile_name')
->find($id);
Then, your object will have a new attribute called "details" containing the related objects (or a collection of the limited selected fields).
You can convert the $vendor to an Array like below.
$vendor = Vendor::find($id)->toArray();
Suppose I have a query that, among other things, returns user id's, this query was built using DB::table()... rather than using the models, so, as a result, I got a collection with arrays for each retrieved row, something like this:
user_id | calculated_data
--------+----------------
1 | 123
2 | 111
3 | 222
... | ...
Supose I store this collection on a $data variable, of course if I do a foreach ($data as $d) { $d->user_id ... } will work.
But I want this query to return something more like what the ORM does, so instead user_ids, return User models so I can do, for example, a $data->user->name
Can this be even done? if so, how?
You can use the hydrate() function, it accepts an array of stdClass objects (or even associative arrays AFAIR) as input and returns a collection of Eloquent Models, so you can do things like this:
$result = DB::table('users')->take(10)->get();
$users = App\User::hydrate($result->all());
You can even get a collection of Eloquent Models directly from a RAW query with the fromQuery() function, i.e.:
$users = App\User::fromQuery('SELECT * FROM users WHERE id > ?', [2])
Update: If in your collection you don't have all the fields to hydrate a model, you can preload all the users you need with one query and modify your collection, i.e.:
$users = App\User::find($data->pluck('user_id'));
$data->transform(function($item) use($users) {
$item->user = $users->where('id', $item->user_id)->first()
return $item;
});
You need to use Eloquent to call value the "ORM way" I did not find anything related to the query builder in relation to ORM.
You could do something like this:
$flights = App\Flight::all();
foreach ($flights as $flight) {
echo $flight->name;
}
And in the ORM way you would get the user like this:
foreach ($flights as $flight) {
echo $flight->user->name;
}
Of course you would need to setup the correct relations.
// initial query will return collection of objects
$query = DB::table('user_something')
->join('users', 'users.id', 'user_something.user_id');
// You could cast it to the model query, by using fromSub.
// Make sure to alias a subquery same as the model's name,
// otherwise it would not be able to parse models data
User::fromSub($query, 'users');
// The most robust way is to get table name from the model
User::fromSub($query, User::make()->getTable());
I'm trying to retrieve single column from my table grades.
For that I have used following code in my controller:
public function verify($id,$sid)
{
$grade=Grade::all('annual')->whereLoose('id',$id);
return $grade;
}
Where, annual is column name. But it is returning empty set of array [].
all() takes a list of columns to load from the database. In your case, you're fetching only one column called annual, therefore filtering on id later on does not return results. Replace your code with the following and it should work:
$grade = Grade::all('id', 'annual')->whereLoose('id', $id);
Keep in mind that it will return a collection of objects, not a single object.
NOTE: you're always loading all Grade objects from the database which is not efficient and not necessary. You can simply fetch object with given id with the following code:
$grade = Grade::find($id); // fetch all columns
$grade = Grade::find($id, ['id', 'annual']); // fetch only selected columns
The code you are using is loading all rows from the grades table and filtering them in code. It is better to let your query do the filter work.
For the columns part, you can add the columns you need to the first() function of the query, like so:
public function verify($id,$sid)
{
$grade = Grade::where('id', $id)->first(['annual']);
return $grade->annual;
}
How to merge this two queries ?
$data = DB::table('category_to_news')
->where('category_to_news.name', ucwords($category))
->remember(1440)
->count();
and
$data = DB::table('category_to_news')
->where('category_to_news.name', ucwords($category))
->remember(1440)
->get();
So, as far as I understand from your comment, you simply want to get all records from the table category_to_news and you want to know how many records are in there, right?
MySQL's count is an aggregate functions, which means: It takes a set of values, performs a calculation and returns a single value. If you put it into your names-query, you get the same value in each record. I'm not sure if that has anything to do with 'optimization'.
As already said, you simply run your query as usual:
$data = DB::table('category_to_news')
->where('name', ucwords($category))
->remember(1440)
->get(['title']);
$data is now of type Illuminate\Support\Collection which provides handy functions for collections, and one them is count() (not to be confused with the above mentioned aggregate function - you're back in PHP again, not MySQL).
So $data->count() gives you the number of items in the collection (which pretty much is an array on steroids) without even hitting the database.
Hi DB class dont return collection object it give error "call member function on array" but eloquent return collection object. for above code we can use collect helper function to make it collection instance then use count and other collection methods https://laravel.com/docs/5.1/collections#available-methods .
$data = DB::table('category_to_news')
->where('name', ucwords($category))
->remember(1440)
->get();
$data = collect($data);
$data->count();
You my get it using:
$data = DB::table('category_to_news')
->where('name', ucwords($category))
->remember(1440)
->get();
To get the count, try this:
$data->count();
Why you are using DB::table(...), instead you may use Eloquent model like this, create the model in your models directory:
class CategoryToNews extends Eloquent {
protected $table = 'category_to_news';
protected $primaryKey = 'id'; // if different than id then change it here
}
Now, you may easily use:
$data = CategoryToNews::whereName(ucwords($category))->get();
To get the count, use:
$data->count();
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);
}