I am trying to reduce the number of SQL queries executed. I have a post where I want to get the author of that post and list it on the page. To reduce the number of SQL queries, I have the following code:
$posts = Post:all();
$posts->load('user');
$posts->first()->user;
I get the error/notice "Trying to get property 'user' of a non-object". How do I get rid of this error?
Eager loading reduces this operation to just 2 queries
public function example()
{
$posts = Posts::with('user')->get();
foreach ($posts as $post) {
echo $post->user->name;
}
}
The error can be there because of the Post (or the first post) you are trying to access is not related to any of the users. You can try this to avoid the error.
$posts = Post:all();
$posts->load('user');
// Try any one of below.
1) $posts->first()->user ?? '';
2) $posts->first()->user or ''; // in Laravel 5.5 or below
Related
Trying to do assignRole() to many users, but it show me Call to undefined method Illuminate\Database\Query\Builder::assignRole(). Is this spatie laravel bug?
$get_username = \App\Applicant::select('username')->whereIn('id', $ids);
$updateUser = \App\User::whereIn('username', $get_username);
$updateUser->assignRole('Applicant');
$updateUser->save();
Any solution for bulk assignRole() in this case?
$get_username = \App\Applicant::select('username')->whereIn('id', $ids);
This is an incomplete query via the QueryBuilder. As well as the second line.
When utilizing the QueryBuilder you need to finish of your queries with the get() method to get a collection to iterate over.
The correct execution would like like this:
$get_username = \App\Applicant::select('username')->whereIn('id', $ids)->get();
Without knowing the exact result of this, it looks like you'd like to retrieve a collection of usernames, that you'd like to get the User model from.
You could do something like the following (untested) for bulk updating.:
$users = User::whereIn('username', function($query) use ($ids) {
$query->select('username')
->from('applicants')->whereIn('id', $ids);
})->get();
foreach($users as $user) {
$user->assignRole('Applicant');
$user->save();
}
I have an query, where it returns 1 or more results. After this query, I execute a delete on these tuples.
I think it's my coding failure, but what I'm trying to do is get this select and send it by ID parameter to Delete.
public function TestDelet(AcademicoRequest $request)
{
$academico = new Academico();
$res = $request->all();
$academico->member_id = $res->member_id;
if($res->member_id){
$dados_academicos[] = DB::table('academicos')->where('member_id', $res->member_id)->orderby('id')->get();
$this-> destroy($dados_academicos->Id);
}
}
List I try on postman:
{
"member_id": "1",
}
But, return this is error: Trying to get property of non-object
Hope these suggestions help:
$request->all();
the all() method is returning array format, so you need to change from
$res->member_id
into
$res['member_id']
I'm assuming you are trying to delete one/many rows from database at academicos table
if($res['member_id']){
Academico::where('member_id', $res['member_id'])->delete();
}
Please check values of object array:
dd($dados_academicos)
If you are using laravel with mysql by default it is id not Id and with mongodb it is _id. so use
$this-> destroy($dados_academicos->id);
OR
$this-> destroy($dados_academicos->_id);
OR
$this-> destroy($dados_academicos['Id']);
I have table with many to many relationship.
User many to many Permission
I already define many to many relationship on both model, and create the pivot table also.
What I want is get all user which contain permission name
What I have done so far is
User::all()->permissions->contains('name', 'access.backend.admin')->get();
But it give me
Undefined property: Illuminate\Database\Eloquent\Collection::$permissions on line 1
What wrong with my code?
User::All() returns a collection not model object. You have iterate over the collection to get the model object and use ->permissions().
For exapmle:
$users = User::all();
foreach ($users as $user) {
$user->permissions->contains('name', 'access.backend.admin'); // returns boolean
}
Or you can get a single model from DB as:
$user = User::first();
$user->permissions->contains('name', 'access.backend.admin'); // returns boolean
Update 1
To get users which contain desired permission use filter() method as:
$filtered_users = $users->filter(function ($user) {
if ($user->permissions->contains('name', 'access.backend.admin')) {
return $user;
}
});
Update 2
You can also write a query which returns the desired result as:
$filtered_users = User::whereHas('permissions', function($q) {
$q->where('name', 'access.backend.admin');
})->get()
I have a similar case of questions and tags, they have many to many relationship.
So when i have to fetch all question with a particular tag then i do this
$tag = Tag::where('name','laravel')->get()->first();
I first retrieved the Tag model with name laravel.
and then retrieved all questions having tag laravel.
$questions = $tag->questions;
Similarly you can do this
$permission = Permission::where('name','access.backend.admin')->get()->first();
$users = $permission->users;
I know, we can do this in the controller:
User::with('post')->get();
It will get every user's post from the database, based on users.id.
But the problem is, I want to do this:
User::with(['post' => function($query) {
# Throw users.id here...
}])->get();
How to do that?
You should get the users first, and then load related posts with a separate query and merge them manually.
$users = User::get();
$posts = Post::whereIn('user_id', $users->pluck('id'))->get(); // Get your additional data in this query
$users->each(function ($user) use ($posts)
{
$user->posts = $posts->where('user_id', $user->id);
});
Note: I did not test the code above. It's just an example to show you how to accomplish what you are trying to do.
I'm new to Laravel and I'm stuck. This is what I am struggling with:
$questions = Question::find($id)->quiz(); // this code retrieves data from
// the table using the primary key
// in the table. The is a parameter
// that is passed via get.
This is what I have right now:
$questions = Question::where('quiz_id', '=', $id)->quiz();
This is the error I get:
Call to undefined method Illuminate\Database\Query\Builder::quiz()
What I want to do:
I want to run a query to get data from my database table using the foreign key in the table not the primary key, I also want to be able to use relations with this as seen from what I tried to do above.
Edit: Added the Question Model
<?php
class Question extends Eloquent{
protected $table = 'quiz_questions';
public function quiz()
{
return $this->belongsTo('Quiz');
}
}
Calling the quiz() function from Question::find($id)->quiz() will return a Query Builder instance allowing you to query the parent of the Question, its not going to return any data at that point until you call ->get() or another method that actually executes the query.
If you're wanting to return all the questions belonging to a certain quiz then you can do it like this.
$questions = Question::where('quiz_id', $id)->get();
This will return an Eloquent\Collection of the results for all questions with a quiz_id that is equal to $id.
If you've setup the relations between the Quiz and Questions then you can also do this using the Laravel relations.
$quiz = Quiz::findOrFail($id);
foreach($quiz->questions as $question)
{
// Do stuff with $question
}
Laravel will automagically pull Questions from the database that belongTo the Quiz you've already got from the database, this is known as eager loading http://laravel.com/docs/4.2/eloquent#eager-loading
Wader is correct, just calling where() will not execute your query. You either call get() and get an iterable result or use first() if you only want one result.
$quiz = Question::where('quiz_id', '=', $id)->first()->quiz();