In my app i have define relationship (profile, user, level) but when I fetch data it is showing an error (Trying to get property 'email' of non-object) how can i solve this thank in advance.
this is User Model
public function profile()
{
return $this->hasOne(Profile::class, 'user_id');
}
Profile Model
public function user()
{
return $this->belongsTo(User::class, 'id');
}
public function level()
{
return $this->belongsTo(Level::class, 'id');
}
Level Model
public function profile()
{
return $this->hasOne(Profile::class, 'level_id');
}
This is Controller ProfileController
$users = Profile::with(['user', 'level'])->where('is_bd_partner', 'Yes')->get();
foreach ($users as $key => $value)
{
echo $value->first_name.'<br>';
echo $value->last_name.'<br>';
echo $value->user->email.'<br>';
echo $value->level->level.'<br>';
}
Note that belongsTo takes foreign_key as the first parameter.
So you should change the Profile Model as
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
public function level()
{
return $this->belongsTo(Level::class, 'level_id');
}
Read more here
Related
I have this Bookmark model
public function bookmarkable()
{
return $this->morphTo();
}
public function user()
{
return $this->belongsTo(User::class);
}
and in my User model
public function bookmarks()
{
return $this->hasMany(Bookmark::class);
}
public function posts()
{
return $this->hasMany(Post::class);
}
and the Post model
public function bookmarks()
{
return $this->morphMany(Bookmark::class, 'bookmarkable');
}
public function user()
{
return $this->belongsTo(User::class);
}
I want to create a new $bookmark and associate a $post with that bookmark
the bookmarks table has the columns bookmarkable_type, bookmarkable_id and user_id
Cause morphTo extends belongsTo
U can use like this
$post = Post::first()// the post u want add to bookmark
$newBookmark = new Bookmark([]);
$newBookmark->name="lorem ipsum";
$newBookmark->bookmarkable()->associate($post);
$newBookmark->user()->associate($post->user);
$newBookmark->save();
See the class docs:
https://laravel.com/api/9.x/Illuminate/Database/Eloquent/Relations/MorphTo.html
i am attempting to rewrite all my joins into Elequent model relationships.
Here is what i have so far:
class SectionAndUser
{
public function sections()
{
return $this->belongsTo('App\Models\Section');
}
public function users()
{
return $this->belongsTo('App\Models\User');
}
...
class User
{
public function sectionAndUser()
{
return $this->hasMany('App\Models\SectionAndUser');
}
...
class Section
{
public function sectionAndUsers()
{
return $this->hasMany('App\Models\SectionAndUser');
}
...
With the select:
$sections = User::find($userId)->sectionAndUser()->get();
I get the result:
{
"id": 1,
"section_id": 1,
"user_id": 133
}
How do i now attach the 3 model section that carries all the data about section_id 1?
This is the join that i am hoping to achieve:
$id=Auth::id();
$results = DB::table('sections')
->join('section_and_users', function ($join) use ($id) {
$join->on('sections.id', '=', 'section_and_users.section_id')
->where('section_and_users.user_id','=', $id);
})
->get();
The expected result:
{
"id": 1,
"section_id": 1,
"section_name": 'sectionName'
"user_id": 133
}
I think the solution is to create only models Section and User, and add the relationship as BelongsToMany.
class User
{
public function sections()
{
return $this->BelongsToMany('App\Models\Section');
}
...
And
<?
class Section
{
public function users()
{
return $this->BelongsToMany('App\Models\User');
}
...
And of course, you need to create the pivot table. You can consult BelongsToMany documentation.
If you use this way, you can simple get the result with this query:
$section = Section::find(1); // This will return all your Section data
$section_related_users = $section->users; // This will return a collection of Users
You could do it this way
$id=Auth::id();
$results = SectionAndUser::where('user_id', $id)->with('users', 'sections')->get();
then you could map it to get your desired output
$sections = collect($results)->map(function ($section){
return [
'id' => $section->id,
'section_id' => $section->id,
'section_name' => $section->sections->name,
'user_id' => $section->user_id
];
});
You can create a many-to-many realtionship without the SectionAndUser-model.
With the belongsToMany-method, you can pass the name of the pivot table as a second argument. You can view Illuminate\Database\Eloquent\Concerns\HasRelationships#belongsToMany if you want to know what other arguments you can pass.
Section:
class Section extends Model
{
...
public function users()
{
return $this->belongsToMany(User::class, 'section_and_users');
}
...
}
User:
class User extends Model
{
...
public function sections()
{
return $this->belongsToMany(Section::class, 'section_and_users');
}
...
}
Then use it as this:
$user->sections->where(...
// Post Model
public function user()
{
return $this->belongsTo('App\User');
}
public function categories()
{
return $this->belongsToMany('App\Category')->withTimestamps();
}
public function tags()
{
return $this->belongsToMany('App\Tag')->withTimestamps();
}
// Role Model
public function users()
{
return $this->hasMany('App\User');
}
// User Model
public function role()
{
return $this->belongsTo('App\Role');
}
public function posts()
{
return $this->hasMany('App\Post');
}
//Tag Model
public function posts()
{
return $this->belongsToMany('App\Post')->withTimestamps();
}
// Catgory Model
public function posts()
{
return $this->belongsToMany('App\Post')->withTimestamps();
}
// controller
public function index()
{
$posts = Post::latest()->get();
return view('admin.post.index',compact('posts'));
}
// posts tabel to user result get
foreach($posts as $post){
$post->user->name
}
I am not able to paginate in laravel in this situation
return $this->hasMany('App\News','category_id')->orderBy('id','desc')->paginate(20);
but says error. in controller I have also tried
$byCategories=Category::findOrFail($id)->paginate(20);`
it also says error.
help me.
My Model is
class Category extends Model
{
public function news()
{
return $this->hasMany('App\News','category_id')->orderBy('id','desc');
}
public function newsMany()
{
return $this->belongsToMany('App\News')->paginate(20);
}
public function user()
{
return $this->belongsTo('App\User');
}
public function getRouteKeyName()
{
return 'slug';
}
}
another model one is
class News extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
public function category()
{
return $this->belongsTo('App\Category');
}
}
my controller code is
public function byCategory($id)
{
$byCategories=Category::findOrFail($id);
return view('back-end/news/byCategory', compact('byCategories'));
}
Thank you so much.
Pagination is not done in the Model
it is to be done in the controller, For example remove (->paginate(20);) from here
public function newsMany()
{
return $this->belongsToMany('App\News')->paginate(20);
}
keep it only as
public function newsMany()
{
return $this->belongsToMany('App\News');
}
and call the pagination in controller when returning the view
$news=Category::findOrFail($id)->newsMany()->paginate(20);
return view('view name', compact('news'));
my user model:
public function roles()
{
return $this->belongsToMany('App\Role', 'user_role_pivot', 'user_id', 'role_id');
}
my role model:
public function users()
{
return $this->belongsToMany('App\User', 'user_role_pivot', 'role_id', 'user_id');
}
public function rolepermissions()
{
return $this->belongsToMany('App\User', 'role_permissions_connect', 'role_id', 'role_perm_id');
}
In laravel i want to get request user role permissions, this is my relation in tables. How can i get property of role_permissions?
i tried this one:
$user->roles->rolepermissions->pluck('permission_name')
In Role model your rolepermissions are linked to App\User model:
public function rolepermissions()
{
return $this->belongsToMany('App\User', 'role_permissions_connect', 'role_id', 'role_perm_id');
}
You should change belongsToMany('App\User' ... to belongsToMany('App\RolePermission' probalby.
$user=User::find(1);
foreach($user->roles as $role)
{
foreach($role->rolepermissions as $rolepermission)
{
echo $rolepermission->permission_name;
}
}
In my database I am an organisations table this table has the following relationships,
Many-to-many with users
Many-to-many with clients
One-to-many with projects
In turn these relationships have other relationships for example projects
One-to-one with client
In my controller I am doing the following,
$organisation = Organisation::all();
$organisation->load('users');
$organisation->load('clients');
$organisation->load('teams');
$organisation->load('projects');
return Response::json($organisation, 200);
So get all the organisations and there relational data.
However what I wanting to do is also get the relationships of relationships, so for example get the client that is related to each project that an organisation has? I thought that doing what I am doing would have worked but obviously not.
Here are my models,
Organisation,
class Organisation extends Eloquent {
//Organsiation __has_many__ users (members)
public function users()
{
return $this->belongsToMany('User')->withPivot('is_admin');
}
//Organisation __has_many__ clients
public function clients()
{
return $this->belongsToMany('Client');
}
//Organisation __has_many__ projects
public function projects()
{
return $this->belongsToMany('Project');
}
}
Projects
class Project extends Eloquent {
protected $fillable = [
'name',
'description',
'total_cost',
'start_date',
'finish_date',
'sales_person',
'project_manager',
'client_id',
'organisation_id',
'user_id'
];
public function organisations()
{
return $this->belongsToMany('Organisation');
}
public function salesperson() {
return $this->belongsTo('User', 'sales_person');
}
public function clients() {
return $this->belongsTo('Client', 'client_id');
}
}
Clients
class Client extends Eloquent {
public function organisations()
{
return $this->belongsToMany('Organisation');
}
public function users()
{
return $this->belongsToMany('User');
}
public function projects()
{
return $this->hasMany('Project');
}
}
Have you tried:
$organisations = Organisation::with('projects', 'projects.clients')->all();
foreach($organisations as $organisation) {
foreach($organisation->projects as $project) {
foreach($project->clients as $client) {
echo $client->name;
}
}
}