Skip to content
Advertisement

Laravel package base relationship models

in our web application we want to have a simple package base cms, for having that we have users, packages, features and user_package table on database

  1. each users can be have one package which we created user_package for that
  2. each user_package belongs to many users
  3. each user_package has on packages
  4. each packages can be have many features which we created features table
  5. each features belongs to many packages

when i try to get user package it, i think it should be:

JavaScript

my models:

JavaScript

migrations:

JavaScript

now when i try to get data i get null in package relation ship

JavaScript

output:

JavaScript

Advertisement

Answer

I think the crux of your question comes down to fetching nested relationships, which is as simple as auth()->user()->with('user_package.package.feature') but there is a problem with your relationships.

Your relationship between Package and Feature is broken; since the features table has a package_id column, a feature by definition cannot “belong to many” packages.

JavaScript

Now, using the relationship, you can get the package features:

JavaScript

You’ve got some naming problems that I corrected in my examples above – relationship methods that return a single model should be singular, others should be plural. Class names should never be plural words (i.e. Feature not Features.)

Generally speaking, there’s no need to create a pivot class if all it’s doing is connecting two models. I’m not going to get into that since it would make for a much longer answer, but it’s something to keep in mind.

And it’s a matter of personal taste, but your class names should be one word only (i.e. Subscription instead of UserPackage) as it makes figuring out things like relationship names more intuitive.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement