Laravel get relation from softdelete - php

I've got 2 tables,
user
intern
A user belongsTo a intern, and a inter hasOne user. My problem is that when I've softdelete a user record and the related intern record. And I want to restore it i can't find the related intern anymore.
So when I find the user like this:
$user = user::onlyTrashed()->find($userId);
And then say $user->intern result is null because it cannot find intern
Trying to get property of non-object
How could I fix this?

Check whether the user exists. If does, do whatever you want to do.
Here's the code
$user = user::onlyTrashed()->find($userId);
if(!is_null($user)) {
echo $user->intern;
} else {
echo 'User does not exist!';
}

To get the soft deleted intern object from your user object, try the following:
$user->intern()->withTrashed()->get()->first()

Related

How to get laravel pivot table records in views?

I have three tables.
Users: id,name
Courses: id,user_id,name
Order: id,user_id,course_id (
Pivot table)
How can i make sure in course view that this user has purchased this particular course using Laravel eloquent.
Firstly, you need to define a many to many relationship between your models:
class User extends Model {
public function courses() {
return $this->belongsToMany(Course::class);
}
}
Once you have it, you can easily check if User has bought access to a Course with given ID with:
if ($user->courses()->find($courseId)) {
// user has access to course with given $courseId
}
If you simply want to an error to be raised when course was not bought, replace a call to find() with a call to findOrFail():
if ($user->courses()->findOrFail($courseId)) {
// user has access to course with given $courseId
}

Laravel one to many get data

So I'm very bad with these relationships in Laravel and I cant get my one to many relationship to work. Lets say I have a friend system like this:
Table Users:
id | username | password
Table Friends:
id | person1(int) | person2(int)
person1 and person 2 are the ID's of a user in the table Users
Now I have these 2 models:
class Friend extends Eloquent {
protected $table = 'friends';
public function friend_relations(){
return $this->belongsTo('User');
}
}
and:
class User extends Eloquent {
protected $table = 'users';
}
Now what I am doing is, after logging in, I want to show friends on the home page with the ID of the person logging in. So to get this I'd have it run like this:
$friends = Friend::where('person1', $id)->get();
Now this will give me the ID's of both of the persons, now I want to get the username that belongs to that user without running unnecessary extra queries so I would use a one to many relationship. However I cant seem to get the query to instantly get the name of the friends of the user logged in.
I tried something like:
$friends = Friend::where('person1', $id)->friend_relations;
and:
$friends = Friend::all()->friend_relations()->where('person1',$id)->get();
gives me: Call to undefined method friend_relations()
but this will give me the error: Undefined property friend_relations.
What am I doing wrong?
Your relationships are a little off because you may be thinking about this one a little wrong.
Even though it may not look like it, this is a belongs to many relationship and your friends table is actually a pivot table relating your users table to itself.
To further simplify this, you should rename the columns in your friends table so it's more clear what is what. person1 and person2 are incredibly vague and will only serve to confuse. With that said, I'm going to assume the two columns are user_id and friend_id. If you wish to not do this, just assume when I say user_id, I mean person1 and friend_id would map to your person2.
With all that said, this becomes a fairly simple problem. Add the following to your User model.
public function friends()
{
return $this->belongsToMany(User::class, 'friends', 'user_id', 'friend_id');
}
Now in order to retrieve a user with their friends, you can do the following.
$user = User::with('friends')->find($id);
$friends = $user->friends; // This will return a collectino of friends.
Additionally, your Friend model becomes unnecessary so you can feel free to delete that.
Edit:
Now $friends is going to be a Collection (you can think of this as a sort of array) of User objects. There are going to be 0, 1 or many User objects inside the Collection so it doesn't make any sense to try to use $friends->date because it doesn't know which User's date within that collection to grab from.
You will need to loop through it to access each User's properties.
foreach($friends as $friend) {
echo 'Name: ' . $friend->name;
echo 'Date: ' . $friend->date;
}

Eloquent: Has Many Through Relationships

I am trying to figure out a relationship but I can't seem to solve the issue.
So what my script does first is checking if there is a valid session where status = 0.
Then I want to check if there is a valid trial where status = 0 ->first() associated with that session. And if so, I want to grab all the relevant data related by trial_id.
I understand what logic is required. However, I am wondering if there is a method to do this with as little commands as possible using Eloquent relationships.
Specifically, once i have the $session object. How can I filter the trials, in order to get the appropriate stimuli_tracker data?
The important components to the relationships for the table is as follows:
Sessions
id (has one to many relationship to trials(sessions_id)
user_id (foreign key)
status
Trials
id (one to many relationship with stimuli_tracker)
sessions_id (foreign key)
status
Stimuli_Tracker
trials_id (foreign key)
stimulus
stimulus_type
Sessions Model
class Sessions extends Model
{
protected $table = 'sessions';
public function stimuliTracker()
{
return $this->hasManyThrough('App\StimuliTracker', 'App\Trials', 'sessions_id','trials_id');
}
}
Trials Model:
class Trials extends Model
{
public function stimuli()
{
return $this->hasMany(App\StimuliTracker);
}
}
EDIT
I have tried in artisan tinker to
$object = \App\Session::where(arg);
then I tried to
$object->stimulus
but didn't work. I tried a few other fields but I only received null. Maybe I'm not getting how to grab the content properly
$object->stimulus is an undefined attribute based on what you've shown in your code.
To access the stimulus information for your session, you have to use the name of the relationship, which in this case is:
$object->stimuliTracker
The thing is that this will return an Eloquent Collection because it is a hasManyThrough relationship (which is a hasMany of a hasMany).
I'm assuming that the 'stimulus' attribute belongs to the StimuliTracker class. If this is the case, then you will need to loop through your StimuliTracker Collection to extract it:
foreach ( $object->stimuliTracker as $record )
{
$stimulus = $record->stimulus;
// do something with $stimulus
}
EDIT (Added):
If you are just looking for an array of the values in the 'stimulus' attribute, you can get that with the lists() method:
$stimulus_values = $object->stimuliTracker->lists('stimulus');

Laravel accessing relationships - check if data exists from within the model

Let's say I have a User and Group model that has a one-to-many relation. User can belong 0 or 1 group. Group can have many users.
When I show a list of users, I also want to display his group's name--if he belongs to one. So I do this:
$user->group()->first()->name
If the user doesn't belong to a group, this will--of course--throw an error.
So I do something like this:
!empty($user->group) ? $user->group()->first()->name : 'No group here'
Now in my actual app there isn't just group. There a lot more relationships that I loop through from within the view. Like, role, account, etc.
So I don't really want to clutter up my view with that. Is there a way to check if a data exists from within the model?
Something like this, perhaps?
class User extends Model
{
// .. snip
public function group()
{
if (empty($this->group)) {
return 'Nothing here';
}
return $this->hasOne(App\Group::class);
}
}
Am I going about this the wrong way? Is this already available? I haven't seen anything on the docs or on google that can help me with this (maybe looking for the googling the wrong words?).
So if anyone could point me in the right direction, that'd be great.
You may create an accessor method in your User model for example:
public function getGroupNameAttribute()
{
$this->group ? $this->group->name : 'Oops! Nothing.';
}
So, in the view, you can use something like this:
{{ $user->group_name }}
The output will be either a group name or Oops! Nothing..

Kohana 3.3: WHERE statement with relationships

I have setup Kohana models with relationships define (1:* and : using through) but wanted to know the best way to use them in WHERE statements.
Example: I have a User model and a Post model. Post has a foreign key (userID) to User
I have setup a $_has_many relationship on the User model with an alias user_created
I know I can use the actual field userID, but I want to be able to do something like this
$user->where('user_created', 'IS', NULL);
This would also be handy for checking whether a many-to-many with something like this
'm2m_relation_count', '>', 0
Is this possible? Thanks!
You can do this with the ORM in Kohana in the following way.
$user->user_created->find_all();
This will result in all Posts the User created.
If you want to check if the User has created posts you just use the same function and do a count() on the result and check if it is greater than 0.
I don't think you can use the alias in a where clause itself. You have to call it from the ORM object.
Many-to-many relations work the same way.
1) There is no quick method to get all users without posts. Id prefer to add special column post_count and increment it after posting.
2) You can check user for m:m relationship with has()/has_any() methods:
if ($user->has('roles')) {
// user has at least one role
}
if ($user->has('roles', $roleId) {
// user has role with id=$roleId
}
if ($user->has('roles', array($roleId1, $roleId2))) {
// user has both $roleId and $roleId2 roles
}
if ($user->has_any('roles', array($roleId1, $roleId2))) {
// user has on of the $roleId1 or $roleId2
}

Categories