I'm pretty new to laravel and trying to create my first app.
I have three different classes: User, Activity and Lecture.
Users are capable of creating an activity and lecture.
Every activity has its technical manager, product manager and activity manager, and users are capable of enrolling the activities.
Every lecture has its lecturer and users are capable of enrolling the lecture.
I want to create the eloquent relationships necessary but I'm not sure if the users should belong to the activity or vice versa.
I have accomplished one of my goals (creating a relationship between users and activity managers) however, I'm confused with the rest of it and feel like it is not the best way to achieve my results.
In that moment, my code looks like that:
App\Activity :
class Activity extends Model
{
protected $guarded = [];
public function TechnicalManager(){
return $this->belongsTo('App\User','technical_manager');
}
public function ActivityManager(){
return $this->belongsTo('App\User','activity_manager');
}
public function ProductManager(){
return $this->belongsTo('App\User','product_manager');
}
public function Enrollers(){
return $this->belongsToMany('App\User','user_activity');
}
}
App\User :
class User extends Authenticatable
{
use Notifiable;
public function activities(){
return $this->belongsToMany('App\Activity','id');
}
}
If you plan on using Eloquent's relationships, then the idea would be:
Do I need to access users (Enrollers) from Activity and call it by accessing the relationship?
If yes, write the relationship
I see nothing wrong with writing relationships on both sides of a model, as long as you use them. If you're not going to use them, then why have them?
Image the situation:
Find a user, it's activities and who is the technical manager and the activity manager for the activities
User::with(['activities','activities.TechnicalManager','activities.ActivityManager'])->find($id)
Related
In my app, you can create lists of roles that are attached to contacts. So you can assign the contact "Bob" the roles of "Gardener" and "Pet Sitter". Then you can create the list "People" and add "Gardener (Bob)" and "Pet Sitter (Bob)" to it.
I have the following tables:
contacts
id
name
roles
id
name
contact_role (pivot)
id
contact_id
role_id
lists
id
name
contact_role_list (pivot)
id
contact_role_id
list_id
Everything was working smoothly until the second pivot table linked to the first pivot table. My pivot tables are (currently) not having any models so I'm not sure if there is a built-in feature to tackle this in Laravel or if I need to think differently.
I currently have this in my List model:
public function list_roles(): BelongsToMany
{
return $this->belongsToMany(XYZ::class, 'contact_role_list', 'list_id', 'contact_role_id');
}
Is this even close? What do I put where it says XYZ::class?
Ok, so the below is doing what I want, but is there an even better way to do it? The key to solving my problem was to create a Model for ContactRole and changing extends Model to extends Pivot.
I placed this in my List Model:
public function list_roles(): BelongsToMany
{
return $this->belongsToMany(ContactRole::class, 'contact_role_list', 'list_id', 'contact_role_id');
}
And this in my ContactRole Model:
public function contact(): BelongsTo
{
return $this->belongsTo(Contact::class);
}
Now I could reach the contact data by using something like this: List::first()->contact_roles->first()->contact
Any way to use with, pivot or similar to tidy this up even more? Thanks!
I like to approach these issues in terms of Models rather than pivots. I think many new Developers in Laravel get over obsessed with what's going on in the Database which is fine, but theres a lot of Magic going on so you can write very simple code that does a lot of Heavy lifting, so that being said if I fully understand your problem
You have a Contacts Model
This model can have many roles
so in your contacts Model you need a role relationship
public function roles()
{
return $this->belongsToMany(Roles::class);
}
next of course you have a role Model (pun intended)
your each role can have many list
public function lists()
{
return $this->hasMany(List::class)
}
then the idea is now that you have roles on contacts and lists on roles you should be able to have many lists through contact
public function lists()
{
return $this->hasManyThrough(List::class, Role::class);
}
I've done similar things before and for your description it seems like that's the approach you might need to take.
I'm facing an issue with model extension. Here's an example of my problem:
I have a User model and an Admin model that extends my User model. I use a github repo called Bouncer for permissions. When I save my roles for an Admin model, it saves as /App/Admin and for Users, it saves as /App/User for the model reference.
So when I call my roles for a Admin or for a User, no problem. But my issue is when I want to query all my users with their roles. I obviously get all my users AND my admin, but the Admins can't get their roles because the are "/App/Admin" in the database.
How can I get all the roles of my "extended" models when I call the parent?
You will create a relationship in your model using belongs to and use a method called "with ()".
First step:
In your model, create belongs to ex:
public function post()
{
return $this->belongsTo('App\Post', 'foreign_key', 'other_key');
}
Second step:
You will use it in your controller,example:
$users = User::with('podcasts')->get();
Eloquent: Relationships
https://laravel.com/docs/7.x/eloquent-relationships#updating-belongs-to-relationships
Another example
Get Specific Columns Using “With()” Function in Laravel Eloquent
Laravel 7.0
I am trying to set up a system where users can belong to
different models, like Courses or Realms. I call this a
'membership'.
A user who is a member in a Realm or Course always has a
Role within that Realm, like 'amdin', 'editor', or 'guest'
I have models for User, Role, Memberable and the Course/Realm stuff.
Like this:
Role ⇦1:N⇦ Memberable ⇨N:1⇨ User
⇩
poly 1:1
⇩
Realm/Course/YouNameIt
At the moment I am using a wild mix of relations to get
more or less what I want. But my approach seems rather
gross to me, or even wrong.
For example, to get a list of models that I am a member of, I write:
User::find(2)->memberships()->get()
But this gives me a Collection of Memberables, not Realms or
Courses, which kind of sucks. Can this be remedied?
To get my first Realm/Course, I have to write:
User::find(2)->memberships()->first()->memberable // YUCK!
Here are my models:
class User {
public function memberships()
{
return $this->hasMany(Memberable::class)->with('memberable');
}
public function roles()
{
return $this->belongsToMany(Role::class, 'memberables')
->withPivot(['memberable_id', 'memberable_type']);
}
}
class Memberable extends Model
{
public function role()
{
return $this->hasOne(Role::class, 'id', 'role_id');
}
public function memberable()
{
return $this->morphTo('memberable');
}
}
trait HasMembers
{
public function members()
{
return $this->morphToMany(User::class, 'memberable', 'memberables')
->withPivot('role_id')
->join('roles', 'roles.id', 'memberables.role_id')
->addSelect(['role' => Role::select('name')
->whereColumn('role_id', 'roles.id')]);
}
}
class Realm extends Model
{
use HasMembers;
}
class Course extends Model
{
use HasMembers;
}
I know that questions like "is this good" or "is this bad" are difficult to answer, so I'll ask:
Is this so wrong that I should worry?
How could I improve this design?
I'll probably never have more Models that Realms and Courses that can have members. Is it smarter to ditch the whole memberable-polymorphism in favour of two separate tables? It IS nice to keep the flexibility the polymorphic approach offers.
You could just set up more relationships
User belongsToMany Roles
Roles belongsToMany Users
User morphedByMany Realm using Memberable
User morphedByMany Courses using Memberable
User morphedByMany YouNameIt using Memberable
Realm morphToMany User using Memberable
Courses morphToMany User using Memberable
YouNameIt morphToMany User using Memberable
I'd make Memberable a morph pivot.
class Memberable extends MorphPivot { ... }
With this, accessing the relationships isn't hard.
$user->roles // Get an Eloquent Collection made up from $user's roles.
$role->users // Get an Eloquent Collection made up from users that have $role.
$user->realms // Get an Eloquent Collection made up from $user's realms.
$user->courses // Get an Eloquent Collection made up from $user's courses.
$user->youNameIt // Get an Eloquent Collection made up from $user's youNameIt.
$realm->users // Get an Eloquent Collection made up from users associated with $realm.
$course->users // Get an Eloquent Collection made up from users associated with $course.
$youNameIt->users // Get an Eloquent Collection made up from users associated with $youNameIt.
And maybe make User <---> Roles relationship use a separate pivot. If not, then make it a morph relationship as well (User morphedByMany Role using Memberable, Role morphToMany User using Memberable)
The thing is, if you use a central table to morph everything up, it will grow a lot. You're essentially making it do the job of 3-4 pivots (in this example). If your data grows a lot, it might become a problem.
Also, different relationships might need different data from the pivot table but since you're only using a single table, that would complicate things unless you opt to use a json field.
Currently I have two tables; Users and Employees
All users are employees but not all employees are users,
I have a models Users and Employee, the personal details of a user are pulled his respective employee record.
Now I wanted to display all users and I can do it using User::all();
but also I wanted to have their personal details too.
currently I'm doing a DB:: call to join table in a function on my Users Model.
is there a better approach to this?
You can do it the Laravel way - eager load the relationship
$users = User::with('employee')->get();
This assumes that you have your relationships defined, at least on User side.
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Employee;
class User extends Authenticatable
{
// ...
public function employee()
{
return $this->hasOne(Employee::class, 'employee_no');
}
}
FYI the Laravel way doesn't necessarily mean the fastest or the best way. It's usually syntactically more expensive/terse and convenient though.
Eager loading a relationship requires an additional query. In your case two queries will be executed under the hood and then employee property will be materialized for each User model in a collection.
So your way with a join and one roundtrip to the database might be more performant at the end of the day.
You should establish a relation. In this case your users can relate to your employees as such
public function employee()
{
return $this->hasOne(Employee::class);
}
With Eloquent, you can just define methods in your User model to access the relation and be done with it.
public function role
{
return $this->employee->role;
}
However, when fetching users, you want to ensure you "eager load" your employee relation so that you're not individually fetching employees when using these methods. When you fetch your users:
User::with('employee')->all()
If you will always require the employee record you can eager load by default:
class User extends Authenticatable
{
protected $with = ['employee'];
}
Sounds like you need to use an Eloquent One to One Relationship
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function employee()
{
return $this->hasOne('App\Employee');
}
}
I have three tables in my database: Users, Books, and Reading. The structure of Reading is:
id, user_id, book_id
Now, I need to access to all the books that the user is reading.
First, I would like to know which kind of relationship is, one to many, many to many, Has Many Through, etc. And what do I have to specify in each model? I mean, in the users model hasMany('Reading') or whatever.
I want to access with something like this: Auth::user()->reading()->books()->get() or something similar.
The kind of relationship where one User can be reading several books and one Book can be read by many users is Many-to-Many relationship.
So, to define such a relation in Laravel you should use belongsToMany method:
class User extends Eloquent
{
function books()
{
return $this->belongsToMany("Book", "Reading", "user_id", "book_id");
}
}
class Book extends Eloquent
{
function users()
{
return $this->belongsToMany("User", "Reading", "book_id", "user_id");
}
}
$books = Auth::user()->books;
Notice, you don't need to call method ->books() but use a property ->books, otherwise you'd have to call it like Auth::user()->books()->get().