I have a Laravel User's Repository that I am utilizing but to prevent the always nagging N+1 problem I'm trying to get all my users to be returned with their role and status in the user's array.
As you can see right now with how its running I have 200+ times its running because of how any records in my db I have. So I"m trying to cut that down.
How would I go about doing this?
<?php namespace Backstage\Repositories\Users;
use User;
use Backstage\Repositories\DbRepository;
class DbUserRepository extends DbRepository implements UserRepositoryInterface {
protected $model;
function __construct(User $model)
{
$this->model = $model;
}
}
views/users/partials/table.blade.php
<td>{{ $user->id }}</td>
<td>{{ $user->full_name }}</td>
<td>{{ $user->email_address }}</td>
<td>{{ $user->role->name }}</td>
<td>{{ $user->status->name }}</td>
You can use eager loading to get rid of the N+1 problem, see the docs
You didn't include your models so not 100% sure about naming, but i think you need this:
function __construct(User $model)
{
$this->model = $model;
$this->model->load('roles');
}
However this always eager loads the roles for the DbUserRepository.
You can also call ->load('roles') in the right method only.
Related
I have 2 relationships that point to the same User model: operador() and profesional().
class Cita extends Model
{
public function paciente(){
return $this->belongsTo('\App\Models\Paciente');
}
public function profesional(){
return $this->belongsTo('\App\Models\User');
}
public function operador(){
return $this->belongsTo('\App\Models\User');
}
}
In the view I call them like this:
#foreach ($comisiones as $comision)
<tr>
<td>{{ $comision->paciente->name }}</td>
<td>{{ $comision->profesional->name }}</td>
<td>{{ $comision->operador->name }}</td>
<td>{{ number_format($comision->total, 0, '.', '.') }}</td>
<td>{{ $comision->estado }}</td>
</tr>
#endforeach
The program crashes on me when it tries to call $commision->operador->name. If I leave it as a comment it works without problems. But it gives me an error when I have the 2 relations at the same time.
Can I have 2 relationships pointing to the same model? And if not, what alternative do I have? Thanks
For the fact that you are using belongTo relationship, that means User is the parent model and Professional and Operador are the child model.
Hence, it is expected that the table for Professional has a column called user_id, thesame thing for the Operador table, it should have user_id column.
With this the relationship will work just fine.
Yes, you can have 2 relationships pointing to the same model.
When you write :
public function operador(){
return $this->belongsTo('\App\Models\User');
}
Laravel expects that The Migration (The table citas) has a column named operador_id. So Yes you can have multiple relationships to the same model.
I'm the beginner of laravel 5.4. I just want to ask. I want to display in Assignments table the Collectors but it doesn't show.
Screenshot of the Assignments Index
Code in my Assignment index.blade.php
<td>{{ $assignment->collector['firstname'] }} {{ $assignment->collector['lastname'] }}</td>
Assignment.php model
public function collectors()
{
return $this->belongsToMany(Collector::class);
}
Collector.php model
public function assignments()
{
return $this->belongsToMany(Assignment::class);
}
AssignmentsController
public function index()
{
$assignments = Assignment::all();
return view('assignments.index', compact('assignments'));
}
I search to how to display the collectors with both many to many relationship. I read the doc about using pivot but I had still errors about that. Can you help me resolving this? Thanks
$collector is an object, not an array. Use -> syntax to access properties on individual collector models:
$collector->firstname
Since the relationship is many to many you need two loops:
#foreach($assignments as $assignment)
#foreach($assignment->collectors as $collector)
<td>{{ $collector->firstname }} {{ $collector->lastname }}</td>
#endforeach
#endforeach
If you find you often need two fields together, like first and last names, you can create an accessor on the Collector model to easily join them:
public function getFullNameAttribute()
{
return $this->getAttribute('firstname') . ' ' . $this->getAttribute('lastname');
}
Allowing you to then do:
#foreach($assignments as $assignment)
#foreach($assignment->collectors as $collector)
<td>{{ $collector->fullname }}</td>
#endforeach
#endforeach
There are numerous questions concerning my problem but it's never been the case I encounter, so here my code:
<td>{{ $note->title}}</td>
<td>{{ App\User::where('id', $note->user)->first()->name }}</td>
<td>{{ date("d.m.Y H:i:s", strtotime($note->created_at)) }}</td>
<td>{{ date("d.m.Y H:i:s", strtotime($note->updated_at)) }}</td>
Everything works fine so far, except for
<td>{{ App\User::where('id', $note->user)->first()->name }}</td>
I figured out that the problem is $note->user and it throws
(2/2) ErrorException
Trying to get property of non-object
which doesn't make ANY sense to me since $note->title above and $note->created_at work like a charm. Any ideas?
You should always check if a user exists:
$user = App\User::where('id', $note->user)->first();
Then in the view:
{{ is_null($user) ? 'No user with specified ID' : $user->name }}
Also, it's a terrible idea to use Eloquent in a view.
You need to check the existence of user before asking for its name.
Also you can leverage Eloquent relationships which will remove the user retrieval from your view.
Add a user relationship to the Note model
public function user()
{
return $this->belongsTo(\App\User::class, 'user');
}
Then in your view you can call $note->user which will return a App\User instance if found or else null.
So to print user's name
<td>{{ $note->user ? $note->user->name : '' }}</td>
I have a doubt that I couldn't find an answer anywhere.
I'm new to eloquent and to make the basic stuff it is excelent!
Now I need to query data from different tables and I was wondering if I can do it with eloquent.
I have two models:
class Worker extends Model {
protected $table = 'workers';
public $timestamps = true;
public function area()
{
return $this->belongsTo('Area');
}
}
And this one
class Area extends Model {
protected $table = 'areas';
public $timestamps = true;
public function worker()
{
return $this->hasMany('Worker');
}
}
So basically a worker belongs to an area and an area has many workers.
Now I want to show in a table the name of the worker and the name of the area that he belongs to.
I can do it using the query builder but I wanted to know if I can do it with eloquent.
I saw a post in laracast with this code:
$workers = Worker::with('area')->get();
Now when I use that I get the following error:
Class 'Area' not found
I don't know why I get that error when the function 'area' exists in the Worker class and in the WorkerController I'm using
use App\Area;
What I want to be able to do is the following:
#foreach ($workers as $worker)
<td>{{ $worker->name }}</td>
<td>{{ $worker->lastname }}</td>
<td>{{ $worker->areas->name }}</td>
#endforeach
Like I said, I already I'm able to accompish this using laravel's query builder but I just want to know if I can make more use of the Eloquent :)
Thank you for your time.
Just in case anyone asks here is my raw query:
$workers = DB::table('workers')
->join('areas', 'areas.id', '=', 'workers.area_id')
->select('workers.*', 'areas.name as area')
->get();
That's the one I'm using and it works perfectly fine, thank you! :)
You are missing namespaces in your relations.
public function area()
{
return $this->belongsTo('App\Area');
}
and
public function worker()
{
return $this->hasMany('App\Worker');
}
You need to use function like you named in model "area" not "areas":
#foreach ($workers as $worker)
<td>{{ $worker->name }}</td>
<td>{{ $worker->lastname }}</td>
<td>{{ $worker->area->name }}</td>
#endforeach
Here is my situation;
I have an agreements table which will list the different types of agreements there are. It's a lookup table basically.
I have a client_agreements table which list which clients have signed up to which type of agreement. I have an agreement_id within this table (foreign key id).
As I am using Laravel, here is my Controller method to view all agreements for a specific client;
public function index($client_id)
{
$client_agreements = Agreement::find($client_id);
return View::make('client_agreements.index')
->with('client_agreements', $client_agreements);
}
Here is my Agreement Model;
class Agreement extends Eloquent {
protected $table = 'agreements';
public function client_agreements(){
return $this->hasMany('ClientAgreement', 'agreement_id');
}
}
So I want to output in the view from the agreements table;
agreement_type
level
and from the client_agreements table;
start_date
expire_date
My View code (which I'm sure is wrong but don't know why) is essentially;
#foreach($client_agreements as $client_agreement)
<tr>
<td>{{ $client_agreement->agreement_type }}</td>
<td>{{ $client_agreement->level }}</td>
<td>{{ $client_agreement->start_date }}</td>
<td>{{ $client_agreement->expire_date }}</td>
</tr>
#endforeach
What am I doing wrong?
You can do it like this:
$client = Client::with('agreements')->find($client_id);
$client_agreements = $client->agreements;
return View::make('client_agreements.index')
->with('client_agreements', $client_agreements);
And in your view:
#foreach($client_agreements as $client_agreement)
<tr>
<td>{{ $client_agreement->agreement_type }}</td>
<td>{{ $client_agreement->level }}</td>
<td>{{ $client_agreement->pivot->start_date }}</td>
<td>{{ $client_agreement->pivot->expire_date }}</td>
</tr>
#endforeach
This would require the following setup:
Client model
class Client extends Eloquent {
public function agreements(){
return $this->belongsToMany('Agreement', 'client_agreements')->withPivot('id', 'start_date', 'expire_date');
}
}
Agreement model
class Agreement extends Eloquent {
public function clients(){
return $this->belongsToMany('Client', 'client_agreements')->withPivot('id', 'start_date', 'expire_date');
}
}
For more information read the Eloquent docs (especially the section about relationships)