Retrieving User's Name from Query - laravel

I have an Employee evaluation form which stores the supervisor (FTO) and employee (FTE) in the database by their ID number (EID).
I can retrieve the data and display the EID of both the supervisor and the employee, but how can I setup it up to pull their names from the user table and display those?
My User Table
ID | EID | first name | last name | email | password
Evaluation Table
ID | ftoEid | fteEid | date | rating1 | etc...
Currently using in the model:
$dor = Dor::find($id);
return view('dor.show', compact('dor'));

You need to set up relationships.
class Evaluation extends Model {
public function user() {
return $this->belongsTo("App\User", 'fteEid');
}
}
Dor::find(1)->user->first_name;
Your field names are confusing so I am not sure if they are correct; hopefully you get the idea.

Related

Laravel relationship returning name instead of id

I have 3 tables. The user permission table indicates which user has which permission.
User table
id | name
1 | jack
2 | bob
Permission table
id | name
1 | manage users
2 | manage jobs
User Permission table
id | user_id | permission_id
1 | 1 | 1
2 | 1 | 2
3 | 2 | 1
User model
public function userPermission()
{
return $this->hasMany(UserPermission::class);
}
UserPermission model
public function user()
{
return $this->belongsTo(User::class);
}
If I do auth()->user()->userPermission, I get all the data from the permission table for that user. Is there a way so that instead of getting the id of the permission table, I get all the permission name instead ? Maybe in an array. So user jack will have ['manage users','manage jobs']
I saw that User and Permission have "many to many" relationships.
https://laravel.com/docs/8.x/eloquent-relationships#many-to-many
Make sure that the name of User Permission table is "permission_user", and In User model, you should define the relation method like the following :
public function permission() {
return $this->belongsToMany(Permission::class);
}
So when you call auth()->user()->permission, you can get a collection of Permission Class belong to user.
If you want to get the name of all permissions belong to an user. Just use the pluck() collection method.
Link: https://laravel.com/docs/8.x/collections#method-pluck
You should first use foreign and local keys in your relations.
Also take a look at Many to Many relations and pivot tables on Laravel Doc.

Laravel | Polymorphic relationship from morphed model

I am creating a polymorphic relationship which defaults to null, as it doesn't have an association originally.
I then create the association and I want to be able to update the polymorphic table to have a link between the original and the morphed class.
post_images:
| id | post_id | width | height | created_at | updated_at
files:
| id | fileable_type | fileable_id | file_disk_id | created_at | updated_at
So basically, inside of the polymorphic table the type and the id they default to null as it has to be processed first and converted to a standard format etc.
I then create the associated row inside of the morphed table, however I am unsure how to update the polymorphic to have the type and the id from the morphed table.
I have tried to do something like $post->images()->create(...); and then try and do something like $file->where('id', $fileId)->firstOrFail()->associate($post); but this just seems to return null.
So the current process is:
Upload the file -> creates a row in the files table which contains the polymorphic relationships but columns are defaulted to null.
Standardize the file -> the file then gets converted and compressed into a standard format that is used for the site.
Create post_images row -> The site then creates a row for post_images table which then needs to link the update the files row to contain the new polymorphic relation.
Eloquent relationships:
File.php
public function fileable()
{
return $this->morphTo();
}
PostImage.php
public function file()
{
return $this->morphMany(File::class, 'fileable');
}
Post.php
public function images()
{
return $this->hasMany(PostImage::class);
}
I think you should just be able to call the save method on the relationship. For example:
$post->file()->save($file)

Laravel 5 - deleting child model data

I have a Model called Campaign which takes the following structure
+----+--------------+-----------------+----------+---------------+--------------+--------------------+----------+-------+--------+---------------------+---------------------+
| id | campaignName | userId | clientId | clientContact | contactEmail | campaignObjectives | acNumber | notes | active | created_at | updated_at |
+----+--------------+-----------------+----------+---------------+--------------+--------------------+----------+-------+--------+---------------------+---------------------+
| 1 | test | 7 | 10 | Mr Fakes | 12345 | sdfsdfsd | 12345 | | 0 | 2016-02-29 11:51:59 | 2016-02-29 13:51:28 |
+----+--------------+-----------------+----------+---------------+--------------+--------------------+----------+-------+--------+---------------------+---------------------+
I then have a CampaignTypes Model with the following structure
+----+--------------+-----------------+------------+---------------------+---------------------+
| id | campaignType | creativeArrival | campaignId | created_at | updated_at |
+----+--------------+-----------------+------------+---------------------+---------------------+
| 14 | Dynamic | 2016-02-26 | 1 | 2016-02-23 16:00:01 | 2016-02-23 16:00:01 |
+----+--------------+-----------------+------------+---------------------+---------------------+
The relationships in these Models is pretty straight forward. A Campaign can have many CampaignTypes and a CamapignType belongs to a Campaign.
In the Campaign schema I have an active column. This is what I use to delete a Campaign. So the destroy method looks like the following
public function destroy(Campaign $campaign)
{
$campaign->update([
'active' => false
]);
Session::flash('flash_message', 'Campaign deleted');
Session::flash('flash_type', 'alert-success');
return Redirect::route('campaigns.index')->with('message', 'Campaign deleted.');
}
Now although it does not cause too many problems, I do not currently set any CampaignTypes row as being deleted if its parent Campaign has been deleted.
What would be the best way to delete the child data without actually deleting it?
Thanks
What you are doing to your Campaign model is called a soft delete and Laravel actually has a nice way to handle that (check out the link). However, it is totally valid to use your own conventions for soft deleting, as you currently are doing when you change the active column to 0. Either way you choose, there is no native Eloquent method to do this automatically, so you'll need a bit of code to modify the parent model.
If you continue to use custom soft deleting (as you are now), it would be easiest to make a custom delete method on the Campaign model. This method will update the record (soft delete it) and also delete any children. You have not specified whether you also want the children models soft deleted or hard deleted, but either one is simple (if you want to soft-delete them, just loop through all and update the relevant column).
Campaign model:
public function deleteAll() {
$campaign = self::find($this->id);
$campaign->update([
'active' => false
]);
//delete children, either hard or soft (use foreach loop on soft)
$campaign->types()->delete();
}
Then you just call that custom method in your controller.
public function destroy(Campaign $campaign)
{
$campaign->deleteAll();
}
If you decide to implement the Laravel convention for soft deleting (basically adding a deleted_at attribute to the model and use a trait) then the model's deleting and deleted events will get triggered, and you can listen for those and respond to them in the model's boot method.
Campaign Model:
protected static function boot() {
parent::boot();
static::deleting(function(campaign) {
//delete children, either hard or soft (use foreach loop on soft)
$campaign->types()->delete();
});
}
And then that gets triggered every time you call delete() on your model, like this:
public function destroy(Campaign $campaign)
{
$campaign->delete();
}

Laravel 4: one to many by on multiple columns?

I'm making a table that essentially maps rows in a table to rows in another table where the structures are as follows:
|--- Words --| |- Synonyms -|
|------------| |------------|
| id | | id |
| en | | word_id |
| ko | | synonym_id |
| created_at | | created_at |
| updated_at | | updated_at |
|------------| |------------|
Now then, I know I can essentially have the words model have many Synonyms through a function like:
public function synonyms()
{
return $this->hasMany('Synonym');
}
No problem, but this method always gets it by the the word_id, and I would like to get it from word_id OR synonym_id that way I don't have to make multiple entries in the DB.
Is there anyway I can do this?
Check laravel docs Eloquent relationships. It would only get word_id because that's the only foreign key I believe.
Also why do you have synonym_id in your Synonyms table?
I believe you are looking for polymorphic relationship.
http://laravel.com/docs/eloquent#polymorphic-relations
I think your best bet is to create a many-to-many relationship with words on itself using the synonyms table as your pivot table.
Add this to your Word model.
public function synonyms()
{
return $this->belongsToMany('Word', 'synonyms', 'user_id', 'synonym_id');
}
Using it:
$word = Word::where('en', '=', 'someword')->first();
foreach($word->synonyms as $synonym) {
// This method would probably return the same word as a synonym of itself so we can skip that iteration.
if($synonym->en == $word->en) {
continue;
}
// Echo the synonym.
echo $synonym->en;
}
I'm a bit confused on you wanting to be able to find synonyms by the word_id or synonym_id but I think if you are using the many-to-many, it won't matter because if you know the synonym, it's still technically just a word, and you'd do the exact same thing.

Laravel 4: A better way to represent this db structure/relationship within laravel

I have the following db table set up
+--------------+ +--------------+ +-----------------------+
| users | | clients | | user_clients |
+--------------+ +--------------+ +----------------------+
| id | | id | | usersid |
| name | | name | | clientid |
| authid | | email | +----------------------+
| (plus) | | (plus) |
+-------------+ +-------------+
I have set up the a relationship table [b]user_clients[/b] with foreign keys to the relevant db, so userid is link to users->id and clientid is linked to clients->id.
Dependant on the Users Authid is how many clients are linked:
Authid 1: User can only have one client associated to them.
Authid 2: User can only have one to many clients associated to them
Authid 3: User has access to ALL clients.
So as i am new to this relationship side of laravel currently i would do a lot of querying to get some details eg:
I would done something like:
$userClient =UsersClients::select('clientid')->where('userid','=',$userid)->get();
Then I would probably loop through the result to then get each client details and output to the page.
foreach($userClient as $i ->$cleint){
echo '<div>' .$cleint->name . '</div>';
........
}
Would this be an old way and could it be handled better??
----------------EDIT---------------
i have managed to sort it as the following:
User Model:
public function clients() {
return $this->hasMany('UsersClients','userid');
}
User Controller
$selectedUserClients = User::find(24)->clients;
I get the same out come as my previous result as in client id's 1 & 2, but now how to get the client details from the actual client db basically is there an easier way that the following:
foreach ($selectedUserClients as $key => $client) {
$clientInfo = Client::select('id','clientname')->where('id','=',$client->clientid)->get();
echo $clientInfo[0]->clientname;
}
The users_clients table needs it's own ID column in order for many-to-many relationships to work.
On your User Model, try
public function clients()
{
return $this->belongsToMany('Client','user_clients','userid','clientid');
}
Now you can find the clients assigned to each individual user with
User::find(24)->clients.
You could also do the inverse on your Client model...
public function users()
{
return $this->belongsToMany('User','user_clients','clientid','userid');
}
This would allow you to find all the users belonging to each client
Client::find(42)->users;
I would also like to mention that it's best practice to use snake case for your id's such as user_id or client_id.
Your table names should be plural. users and clients.
Your pivot table should be snake_case, in alphabetical order, and singular. client_user.
This would make working with Eloquent much easier because it's less you have to worry about when setting up the relationships and it might be easier for someone else to help you work on your project.
Instead of return $this->belongsToMany('Client','user_clients','userid','clientid'); all you'd have to do is return $this->belongsToMany('Client'); which should keep your app much cleaner and easier to read.

Resources