Member Since 4 Years Ago


Experience Points

1,745 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
Best Reply Awards
Best Reply
  • start-engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber-token Created with Sketch.


    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.


    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

Level 3
13,255 XP
2 years ago
Activity icon

Started a new conversation Passing Related Attribute To Create Method - Model Factories

$factory->define(CourseOffer::class, function (Generator $faker) {
    return [
        'course_unit_id' => factory(CourseUnit::class)->create()->id,
        'quota_id' => factory(Quota::class)->create()->id,
        'regulation_id' => Regulation::findOrCreateWithRegulationStartYear(2016)->id,
        'fee' => 4000,

$factory->define(CourseUnit::class, function (Generator $faker) {
        $duration = $faker->numberBetween(3, 4);
    return [
        'code' => $faker->sentence,
        'degree' => $faker->words(1, true),
        'course' => $faker->words(4, true),
        'length' => $duration . ' years',
        'duration' => $duration,

Given the following two factory methods, I’d like to be able to do this:

$courseOfferOne = factory(CourseOffer::class)->create(['course' => 'a']);

But the course column doesn't reside in CourseOffer, it actually lives in the CourseUnit model. What can I do to make it as easy as passing in a course attribute to my CourseOffer model without changing the schema?

3 years ago
Activity icon

Replied to Homestead Not Mapping Properly

@mehany so when I run your global status command I get the following output:

id       name   provider state  directory                           
There are no active Vagrant environments on this computer! Or,
you haven't destroyed and recreated Vagrant environments that were
started with an older version of Vagrant.

What have I done wrong during the vagrant homestead box upgrade? It seems like homestead is ignoring my .yaml folder mapping instructions after the update.

3 years ago
Activity icon

Replied to How Do You Filter Children Models?

I think I've done it:

Route::get('/', function () {
    return dump(Branch::
        with(['studentEnrolments' => function($q){
            $q->whereHas('student.person', function($query) {
                $query->where('gender', 1);
Activity icon

Started a new conversation How Do You Filter Children Models?

Here are the relationship definitions

  1. A Branch hasMany StudentEnrolment
  2. StudentEnrolment belongs to ONE Student
  3. Student belongs to ONE Person
  4. The 'gender' column is of type boolean and lives in the Person model. Where the value 0 is for male, and the value 1 is for female.

How does one filter the Branch's student enrolments array based on the gender of the person?

This doesn't seem to work:

Branch::with(['studentEnrolments.student.person' => function($q){
            $q->where('gender', 1);

What do I need to do to get this working? It still returns the full set of Branch's student enrolments array.

Activity icon

Started a new conversation GROUP BY On Eager Loaded Table.

GENDER | total_students
0   |    9
1   |    14

p.s. This is a table which shows a total students of 23. That gives 9 male students, and 14 female students.

To simplify the question, I'm trying to produce the above result set with as much eloquent as possible. Here's what the required SQL query looks like to produce the above result:

SELECT persons.gender, COUNT(*) as 'total_students' FROM student_enrolments as se

LEFT JOIN students on se.student_id =
LEFT JOIN persons on students.person_id=

GROUP BY persons.gender

Here’s what I’ve tried so far to recreate this in eloquent:

        'student.person' => function($q){
        ->selectRaw('count(*) as total_students')

Notice the inner Group by to reach the gender attribute on the person table that belongs to the student model. But that produces the following incorrect query:

string 'select count(*) as total_students from `student_enrolments`' (length=59)

And when var dumping the toArray result… I get the following:

array (size=2)
      'total_students' => int 23 //<-notice how GROUP BY had no affect in splitting the result

And instead, I expected the result:

array (size=2)
  0 => 
    array (size=2)
      'total_students' => int 9
  1 => 
    array (size=2)
      'total_students' => int 14

I also tried doing a group by as a chain but by trying to reference the column with dot syntax like so: StudentEnrolment::with('student.person')->groupBy(‘student.person.gender’)t that didn't work too.

What can I do to get this working?

3 years ago
Activity icon

Replied to Laravel Forge Let's Encrypt SSL 502 Bad Gateway.

Any updates on this as I'm getting the same error..

4 years ago
Activity icon

Replied to Can I Do This In One? If Not Whats The Most Efficient Way?

I don't understand your question. But this is elegant, providing you have a model for that table. :)

4 years ago
4 years ago
Activity icon

Replied to Users And Customers, Where Some Users Are Customers

@myflashstore Since a user will always be a customer, but a customer may or may not be an existing user, then just store the customer_id on the user's table, and have a customers table with a hasOne relationship to User. You don't want a bunch of null values in your customers table if you were to store the user_id there, since not every customer will be a user.

Having one foreign key to tie the relationship between the two tables is more than enough. I've stated my reason above where I would place the foreign key relationship.

Activity icon

Replied to Eager Loading All Relationships

@prymribb Hey, well I wondered the same thing since every single query I was making on my Orders model went hand in hand with a with->(OrderLines::class) at the beginning. So it made sense to want to have something which automatically eager loaded my OrderLines dataset. Another use case in my app, I have another model called Agent which also requires the eager loading of three other models related to it for everything to make sense in the iOS client.

I did some research last week and Taylor Otwell had documented in his Model class a variable which allowed one to set their eager loaded relationships in their own model to automatically enable the loading of relationships without having to specify the with method.

Here's the documentation on that: Model.php

     * The relations to eager load on every query.
     * @var array
    protected $with = [];

All Eloquent models inherit from this class you'll notice the line: class YourModelName extends Model this means you can use the with variable yourself by specifying an array. Here's an example:

    // order
    protected $with = array('orderlines');
    // agent
    protected $with = array('state', 'direction', 'areas');

It's important to remember to only eager load relationships that have to be loaded each and every time, otherwise you will be wasting time on queries especially if you're not going to use them.

In my case it's required. That's how you achieve automatic eager loading.

I hope this will help you and future members visiting this post. If it helped don't forget to mark the answer.


4 years ago
Activity icon

Replied to Appending Relation Sum

@JarekTkaczyk ah, I didn't know this :|

I've noticed in one of your posts on your website where you use getRelation quite a bit. I've seen it used for some solutions to. I feel like I'm missing out. Where can I learn about this in depth?

Activity icon

Replied to API Authentication For Mobile Applications

That's a big question. I currently haven't learned about authentication yet with server development but will do soon in the next few months. I've just been learning about API development, and RESTful webservices theory.

Hopefully someone will be able to help you out :) . It might also be helpful to narrow the questions down.

Good luck,


4 years ago
Activity icon

Replied to Eloquent Relationships Returning Empty

@TobyMellor you mean fellow ;p would you be able to explain why my answer wasn't the chosen one? I explained the details to your question and how to fix them, rather than a copy and paste solution. :D ;p

4 years ago
Activity icon

Replied to Autoplay Series Videos

I agree to a youtube like playlist which will play the videos one after the other. +1 to this.

Activity icon

Replied to Appending Relation Sum

@psaunders It looks like your motion_id is inside a motionRank relationship definition. Instead try this:

public function motionRank()
      return $this->hasOne('App\Vote')
        ->selectRaw('sum(position) as rank')

You should have the result look like this:

"motionRank": 7

Tag me and let me know if that helps.

Activity icon

Replied to Parameters In Relations Are Mixed

@pckz Do you really need all those relationship definitions? What do the models do? how are products, users, and messages related in reality? lol they seem like very different things.

However, I can understand a relationship between a product and a user through message so that a user can write a message about a certain product, but it would be great if you could explain the reality of these relationships. What are you trying to do in your view?

In fact, having taken a look at your images I'll presume the following:

  1. You're querying on your Message model
  2. You wish to access the User model associated to the Message model, and
  3. you wish to access the Product model associated to it too.

I notice the message has the id of those two respective models you want associated to your Message model, so then here's how to set up the relationships:

//Message model
public function user()

Your User model will have the inverse relationship defined to link back to the Message model if you want to be able to do User::find(1)->message() or messages();

//User model
public function messages()
    //If the user can have many messages do this

     * if the user cannot have many messages, and can only have one message then do this
     * $this->has(App\Message::class);

That's the basics of it and all you really need from the information you've provided so far. If you want to query on the Product it's the same definitions as I have defined for you in the User model.

Now to run your queries:

you can do:


And then you will have a single model instance returned that looks something like this:

message: {
   - id
   - user_id
   - user: {
        - id
        - first_name
        - email 
   - product_id
   - product: {
       - id
       - name
       - price 

I hope this works for you and you understand more.

Don't forget to mark an answer :) Thanks


Activity icon

Replied to Overthinking In Which Class To Put A Method In.

@belisar where can I read up on JSON api for fractal? and what it's advantages are? I'm using eloquent collections with nested relationships, as well as outputting to json

4 years ago
Activity icon

Replied to Eloquent Relationships Returning Empty

@TobyMellor Hey Toby, since the foreign key sits in the Album model referencing to an Artist model, and you have mentioned that each album can only have one artist, then in your Album model the relationship method needs to be defined as a belongsTo. relationship. You then mentioned that an artist can have many albums, this therefor means that the relationship needs to be defined as hasMany. This would yield your models looking like this:


public function artist()
    return $this->belongsTo(App\Artist::class);


public function albums()
    return $this->hasMany(App\Album::class);

Now when you will be able to run these commands:

>>> $album->artist()->get() and >>> $artist->albums()->get()

Ensure that you also have data in your tables.

I hope you get it fixed.

Don't forget to mark an answer :) Thanks


Activity icon

Replied to SelectRaw Not Working

@dharmendrajadon SQLSTATE42000 means that you have a syntax error somewhere. I can't see anything that stands out, but I would suggest commenting out the bottom queries, and running them one by one, uncommenting each line after each successful sql execution so that can see which query actually contains the syntax error.

Can you show me the full error?

Activity icon

Replied to Overthinking In Which Class To Put A Method In.

@bugsysha sorry. I have updated my post to add in the URL link that Iw as meant to insert before. Please take a look

Activity icon

Replied to Nested Method Eager Loading

@JarekTkaczyk Could have liked it ;) Anyway, jokes aside, I'm not sure what happened, no sleep has caused me to have a brain freeze! Momentarily stuck in a while loop! I answered his initial generic question but didn't deal with his problem! lol.

Well I'm glad you did anyway. :) Edit: Ah, I've just had another look at the OP's question, and one of his relations is a pseudo relation... lol as you mentioned. Lol, i missed that! I instantily assumed a proper relationship definition ;p

Activity icon

Replied to Overthinking In Which Class To Put A Method In.

@bugsysha Traits are good for when you have duplication across classes. Here we have a situation where it's only in one class... hmmm I can however imagine this code being duplicated for my FactoriesController, UsersController, AccountsController, and so on so forth...

Hmmm, what would I call this trait then? and what would the method look like for it to work across my controllers? And what of the fractal manager instance, would I still need to instantiate that in every controller or... will that be instantiated inside the trait? And what of the transformers that get instantiated into the fractal manager?

Activity icon

Started a new conversation Overthinking In Which Class To Put A Method In.

Hey, here's some code that I have in my controller which contain methods all connected to my routes. Please see the code pasted into this Laravel paste bin.

Each method calls a method from my repository, and then calls a method on a transformer manager class to process the dataset into the final result. (appending the wrapper data around my json, essentially)

I have an OrdersController, which has a Fractal manager, orderRepository and OrderService class all of them instantiated through the constructor.

OrderRepository, contains all my database querying logic

OrderService I was thinking of putting my duplication method here.. there's nothing in here atm. If I move the duplication into a method in this class then that'll mean I'll have to pass a fractal instance to this method too which is ugly, and I could instead instantiate my fractal manager here instead of inside my controller...

Normally the controller is responsible for handling HTTP related stuff, json, and transformations, right? So should I just decouple the duplication in my OrdersController instead?

Any thoughts? Lol. Sorry, normally this kind of stuff doesn't hinder me at all, not sure what's happening today.

Activity icon

Replied to Eloquent Get Latest Tickets -> HowTo?

@uibar why don't you set up a hasManyThrough relationship on your User model? This way you can access all tickets which are referenced to the user's locations.

> Users->locations->tickets

It allows you to create and reach long distant relations with a shortcut relationship.

Activity icon

Replied to Nested Method Eager Loading

@slaughter550 Great question. Allow me to answer it:

Why does this work

$this->load('question', 'question.assessment'); 

while this does not work.

$this->load('question', 'assessment');

This is because when you query on your model, you have to eager load relative to that model. There is no relationship defined between assessment and your model which is why you're not able to lazily eager load them. Now when you do question , that works because there is indeed a relationship defined called question on your model class. You can also eager load nested relationships using dot notation. Because question.assessment works you can be sure that there is an assessment relationship defined belong to the question model.

So you're technically eager loading the grandchildren belonging to the question model which belongs to the parent model which you referred to as model.

Just so you know, you don't have to eager load, questions seperately if you're already eager loading question.assessment, since you can't eager load the grandchild assessment without eager loading it's parent called: question.


Activity icon

Replied to Different Models Based On Table Column, All Extending A Base Model

@dprevite this is exactly what polymorphism does for you.

You have a table called media_collections, and a table for videos, and a table for photos; you can have any other media tables connected to it to.

Each media type table of course has their own rows, for example the videos table may have column names such as duration, genre, movie_budget and so on. These are attributes that you won't find in your Photos table since you might instead have pixels, pixel_width, pixel_height, resolution and so on. Yet both these can fall inside the media_collections table.

So in your collections table you would have at least two fields called, imagable_id, and imagable_type. This would look like the following:

    id - integer
    duration - timestamp
    genre_id - reference id

    id - integer
    resolution - integer
    pixel_width - integer
    pixel_height - integer

    id - integer
    imageable_id - integer
    imageable_type - string

This will then store the appropriate model's id number, and model's type, so that when you process the rows on your media_collections table, they will automatically convert it to the correct model type. You would retrieve a row on your polymoprhic table like so:

$mediaCollection = App\MediaCollection::find(1);
$imageable = $mediaCollection->imageable;

So here the imageable relation on the MediaCollection model will return either a Movie or Photo instance, depending on which type of model owns the MediaCollection instance.

I hope this helps. If it does then please do mark the answer.

Thank you


4 years ago
Activity icon

Replied to Nested Relation Query

Yes @david-w, it is possible.

Set up a hasManyThrough relationship on your User model so you can access all projects through the user's associated customers. It provides a convenient short-cut for accessing distant relations - projects - via an intermediate relation - customers.

Please refer to the documentation so that you can learn how to set this relationship up. It's dead easy. A one liner. Doing so, you'll be able to retrieve just a collection of Projects.

If you do it your way then as you have noticed you will get nested relationships because of eager loading, you could filter those out, but the nested relationship will still be there, and then you'd have to use a Collection method to extract the projects in post, which you don't want to do.

I hope that helps. Don't forget to mark the answer if it helped!


Activity icon

Replied to Ordering Table

Ok @Ghaleon I thought it might have been that. As I said, you might have written your code in the wrong part of the class or not inside a method at all!

If it helped, please do mark the answer :)


Activity icon

Replied to Most Used Tags In Many-to-Many Relation


Well, you could do it with eloquent but this requires post-processing which isn't clean in my opinion especially as you won't be filtering on the SQL domain which is ideal to do it in as you don't want to load data just so you can do some math with it after.

Activity icon

Replied to Ordering Table

Can you show me the full source code of your entire file please? Paste the code into something like

The chances are you are not writing this database query statement inside a method or in the right part of a class. Once you have that fixed then don't forget to add two colons after DB like so:

$professor = DB::table('professors')->orderBy('name','asc')->get();
4 years ago
Activity icon

Replied to Polymorphic Relations And Scope.

@pmall what are you talking about? That is not the reason why one should add a boolean value just to indicate which ticket is the latest. One simply has to query the latest status added to the table.

@terumi I'm sorry but you have been misinformed. Allow me to help and answer a few of your questions

I get an error exception "Trying to get property of non object" on this line, in Ticket model: This is because you are creating a scope and trying to query on top of $this:

//This is wrong because there is no object instantiated, hence the error
return $this->getStatusAttribute() == $type;

And instead a scope should look like this:

public function scopeCurrentStatus
    return $query->... and so on;

Scopes are used for chaining to filter the model. Scopes should always return a collection of the same Model the scope was created in. In your case you don't want a collection of Statuses/Tickets instead you just want an item that item being the latest Ticket inserted into the database

So instead create a method like so:

public static function currentStatus
    $ticketModel = \DB::table('ticketModels')
                    ->latest() //Will order the whole set from latest to oldest.
                    ->limit(1) // limit the entry to 1 row
                    ->first(); // Use first() to get an item instead of using get() which returns a collection
    $currentStatus = $ticketModel->current_status; //name of the attribute on your TicketModel
    return $currentStatus;

Now you can filter the TicketModel based on the current_status like so:

        $currentStatusTickets = Ticket::where('current_status', TicketModel::currentStatus())->get();

I hope I have understood your question properly. Either way, I believe I was close, what I have written will help you understand a lot more about how scopes and queries work. If this helps, please do mark the answer as correct.

Thank you


Activity icon

Replied to Most Used Tags In Many-to-Many Relation

@ftiersh So this currently isn't possible in Eloquent's query builder, since the methods aren't there for complex filtering on the SQL where you want to harness orderBy, groupBy, and most importantly chain the count command. Luckily this is possible with the Database Query builder. Now before we get onto that, you mentioned that you are not using polymorphism, and that instead you have a table for each category. candidate_tags table, file_tags table. So when you wish to answer your question of I'd like to display the top 5 most tags for that relation then you'll have to query the tables separately. Of course you know this.

In pseudocode, you want this:

1) Count all tags within the relational table
2) group the tag count by the `tag_id` used in the seggragated relation table that you have. This will cause your count to split up into the tag type, and then
3) order by the the count
4) limit query to grab only 5 rows

This is what it will look like in code:

public function topFiveCandidateTags
        ->select(DB::raw('count(*) as tag_count, tag_id'))
        ->orderBy('order_count', 'desc')

This is what the result looks like: Note: I've converted to json for presentation purposes.

    "tag_count": 2896,
    "tag_id": 3
    "tag_count": 2320,
    "tag_id": 1
    "tag_count": 2123,
    "tag_id": 23
    "tag_count": 1529,
    "tag_id": 61
    "tag_count": 1407,
    "tag_id": 4

I hope this helps you get a better understanding of how it all works, the limitations of Eloquent and the power of DB query builder. Eloquent is still great and I use it in my project currently for all my database logic, but in this situation you need the power of DB's query builder.

If this helps please do mark the answer.

Thanks Pavan

Activity icon

Replied to Return A Relationship Depending On Value Of A Model's Property

@BenG you're getting a funky error.

In my opinion you shouldn't be filtering the result set on your relationships. The point of the relationship definition is to do what it was meant for, to map properly the related tables and how it references to it. Remember, the query builder is only building a query to be executed at a later point. So you don't need to worry that the whole data set is being returned which is why I assume you're filtering in your relationship itself. Which brings me onto the next point.

Filtering your Order model dependant on a attribute of that model will work best when you query using a where clause. Another developer working on your project won't be expecting for there to be a filter applied, and by practise would apply the filter while building the query. Before we get into that let's talk about your scenario first and how to set your relationships up properly so that you eager load works well.

The two models we are dealing with are Order and PaymentType. This leads me to believe that a PaymentType can have many Orders, and an Order belongs to a PaymentType. It makes sense for the foreign key to lie in the Order model. I presume you have this setup for the two tables in question.

- id
- payment_type_id
//Payment Type
- id

So your relationship in your Order to PaymentType currently set to hasOne is wrong. It should rather be defined like so:

public function paymentTypes()
    return $this->belongsTo(App\PaymentType::class);

And in your PaymentType model you can have:

public function orders()
    return $this->hasMany(App\Order::class);

Now that you have all the ground work in place we can move onto what the query will look like when you are querying on your Order model. We need to use the whereHas method to add further constraints in our query like so:


And that's all. Here's a side point for you, I wouldn't have magic numbers like that, in the future one may ask, what is 2? It makes your code hard to read especially if that number signifies a certain status.

In my Order class, (Yes, I too am working with Orders ;) ) I have constants defined like so:

const CREATED = 1;
const PROCESSING = 2;
const FINALISED = 4;
const CLOSED = 5;
 * //Previously
 * Order::whereStatus(2)
 *    ->with('paymentType')
 *    ->get(); 
// Updated cleaner version

I hope this helps you on your way.

Please do mark the answer if it's helped :)


Activity icon

Replied to Scope, Method Not Found

@cristian9509 This won't work because you've defined the scope in your Model class yet you are trying to access the scope from the UserType scope.

You'd want to access the scope by writing the correct model like so:

Model::slug()->get(); //Notice the correction in the model that we are querying against.

Hope that helps Also, don't forget to mark the answer!



Activity icon

Replied to Multiple Quires In Model Scope Function

@sufi could you explain what you are trying to do overall so we can understand better the reason for you wanting to run two queries.

Activity icon

Replied to Store Attributes To A Model In A Separate (flexibel) Table

I'm glad to hear it @stefr. If it helped you, don't forget to mark the answer please!

Thank you.


Activity icon

Replied to Store Attributes To A Model In A Separate (flexibel) Table

Hi @stefr there are no columns called keys from what you've shown us so far. You're right in thinking that you won't need to make any changes to your existing tables since you can define the relationship by creating a new table which will have a column that references to the parent. Does every Model only have one UserSetting or can the Model have more than one? Use this: if the Model can only have one UserSetting:

public function setting()
    return $this->has(App\UserSettings::class);

Or use this if the Model can have more than one UserSetting :

public function settings()
    return $this->hasMany(App\UserSettings::class);

Also you mentioned this to another fellow:

This doesn't work. I think with $test->settings['website'];

This won't work and that's not because of the reasons you think. You have an instance of your Model and then you can access the relationship method like so


This returns either an item or a collection depending on how you defined the relationship. Most likely it will be a collection since you mentioned a hasMany relationship having been defined. So you would do something like this to access the website:

foreach($settings as $setting){
    $website = $setting->website;

And you can do whatever you want once you retrieve the website. I hope this explains a few things for you.

Activity icon

Replied to Solve The Player Controls Over Video Issue.

Switch to full screen, my friend, anyone actually, for that matter :) You seem to have the video covering your entire window anyway. lol

Activity icon

Replied to Eagerload Multiple Nested Relations In The Same Call

You can only eager load objects that have relationships defined between the models. They must be linked in a way for you to be able to eager load the children. I believe you understand this. I presume that your Movie model branches into two different relationships like below:

  1. A Movie->hasMany:Actor
  2. A Movie->hasMany:Genre

If your Movie does branch into two like above then you will need to eager load them seperately like so:


That's one way to do it.

Activity icon

Replied to Custom Pivot Vs New Model

  1. What is a customer order item position? Is it a reference number?
  2. Where did 02 come from for the order_item_id, I know it was an example.
  3. Could you explain in detail what the custom options will hold?

p.s. Why is the order_item_id indented? Mistake?

4 years ago
Activity icon

Replied to INNER Join

@Liosva I'm glad you are now using the belongsToMany method, this is what the issue was before. :) If you could mark my answer as correct I would appreciate it. Thank you.


Activity icon

Replied to INNER Join

In php i use this sql : SELECT * FROM objects INNER JOIN user_objects ON and user_objects.id_user= 1 ; It is possible to make something similar to this on laravel

@Liosva Take a look at my message, you don't need to do the above in Laravel if you set everything up properly as I described. :) The belongsToMany relationship definition will take care of this query for you ;)

Activity icon

Replied to INNER Join

@PLB-RR Hi, I've read your answer, the inverse for a belongsToMany relationship is not hasMany as you've defined in your example User model, it is again, a belongsToMany definition that should be used. Unless you were trying to find the inverse for the hasMany relationship, then the relationship defined in your example Object model is wrong, and should be belongsTo.

Either way a pivot table is not formed with either of those relationship pairs I stated above in relation to your example. Both models require a belongsToMany relationsihp definition if you want to interact with the pivot table properly on both ways.

I just thought it would be good for you to know for your future reference, I mean well. :)

Activity icon

Replied to INNER Join

@Liosva It looks like you're trying to setup a many-to-many relationships based on the fact that you have a user_objects table. Many-to-many relationships are defined by using the belongsToMany method in both models instead of using hasMany which is actually used for a one-to-many relationship.

So your User model should have a relationship defined to the Objects table like so:

public function objects()
     * you dont need to pass in extra parameters providing you're following
     * the column naming conventions, which you're not. More on that down below.
    return $this->belongsToMany(App\Objects::class);

You'd do the same within the Object model but making the appropriate references to the Users table. Do this if you're interested in doing $object->users.


  1. You're making it more difficult for yourself by inputting extra parameters to explicitly define the correct references when you created your hasMany relationships. You've got column names such as: id_user and id_object, instead Laravel does magical things for you where it will assum the relationship name to be the model_name + _id, so if you define your column names in your pivot user_objects table with user_id, and object_id, you won't then have to provide extra foreign and local keys into your relationship definition, as I have shown in my example where I just needed to pass the name of the model.

  2. Looking at your example it is clear that you're only interested the objects associated to the user, so if you follow the conventions properly then you will realise that for this occasion you won't need to access the pivot table directly as you are. Instead you'll be able to do this $user->objects within your foor loop.

  3. change the name of the pivot table from user_objects to object_users. Laravel will automatically save into the correct pivot table so long as you name your pivot table properly: following the convention of sorting your two models my alphabet order, and then pluralising the second model. thus creating object_users instead of user_objects.

4 years ago
Activity icon

Replied to Bill Of Materials Pattern And Models

Hey, great! No problem, I was just helping. I'm glad it worked for you.

I MUST :) put your name in the acknowledgments so that people know that it was your solution. Can I?

LOL, you don't have to but sure, if you like you can just link to this page. and JUST for fun, you can add an extra comment telling them to like your post/this comment so we can see how many people actually visit your link ;p

Good luck,


Activity icon

Replied to Bill Of Materials Pattern And Models

oh I see @mcanaves, good question. that’s okay :) since the client can have either a Product model or Bundle model then this means that relationship should also be polymorphic. This will enable you to assign more than one type of model to the client :)

So create a polymorphic relationship on the Client model ​as well​. To reiterate it's so that you can save either a Product model or a Bundle model into your client.

Activity icon

Replied to Bill Of Materials Pattern And Models

You can’t have an addon model or a plan model if you don’t have a table for them :) It doesn't make sense since the model is there to act on behalf of the table. From your current design it seems that an Addon or a Plan are considered as a type of Product .

So I assume then that bundles work like this:

bundle1 = can consist of addon1 and addon2;
bundle2 = plan1 + bundle1;

This then actually translates to this: Products table:

Product 1 = (addon1);
Product 2 = (addon2)
Product 3 = (plan1)

And so then you should do the bundles table like this:

bundles table

- id //bundle id
- imageable_a_id  //polymorph relationship to either products or itself bundles table
- imageable_a_type //Model type tells Laravel which table to take product from.

- imageable_b_id //polymorph relationship to either products or itself bundles table
- imageable_b_type //Model type

Example content: Bundle 1 = addon 1 + addon 2, here’s how that's stored:

- id = 1,  
imageable_a_type = ‘products’, imageable_a_id = 1, //references the products table id 1
imageable_b_type = ‘products’, imageable_b_id = 2 //references the products table id 2

Bundle 2 = Plan 1 + bundle 1, here’s how that's stored:

- id = 2,  
imageable_a_type = ‘products’, imageable_a_id = 3, //references the products table id 3
imageable_b_type = ‘bundles’, imageable_b_id = 1 //references the bundles table id 1
Activity icon

Replied to Bill Of Materials Pattern And Models


Laravel models are not able to manage composite primary key.

What makes you say that Laravel cannot handle composite keys? It is in fact possible to create composite keys. You write something like this in your migrations file

$table->primary(array('first', 'last'));

Take a look at the documentation:

As a side note, you are not limited to the defaults of Laravel when designing your database. You may use the DB::raw() method if you wish to run raw SQL queries.

4 years ago
Activity icon

Replied to A Big Thank You To Taylor

Thank you luceos for inviting me to write here.

So, Taylor, I caught up on the twitter drama hype today morning. Blasphemous!

I can understand how discouraging and demotivating it might be when dealing with people who don't appreciate, or people who suck out your energy by not being constructive and helpful. I go with the attitude of, "hey, no problem." and move on. Everyone goes through bad moments, don't live in them. It's the people who pick themselves up very quickly after a bad moment and continue on their day with positivity that do well; i.e. maintaining a positive mental attitude.
Taylor, all is well!

I don't think your spirits need to be lifted, but I hope you don't mind me taking a moment to say thank you for the awesome work that you have done. My business has been working so efficiently now since I've joined the Laravel community. You can't imagine the setup I had before and how much it slowed me down, the code wasn't scalable, I of course didn't know the best practises at the time. Now, processes on my end have improved for the better ever since I networked with the guys who also use Laravel, thanks to your framework.

Using Laravel has made me become a better programmer. Here's the following features I'm grateful for:

  1. The documentation. The documentation is one of a kind! It's so beautiful, every single sub header has an example. The technicals are explained, even the most advanced niche features have an example JUST incase there's a person who may find it helpful.

  2. The Eloquent ORM included with Laravel and migrations. Sighs. Beautiful. I was a spaghetti programer 3 years ago for server side API building, and it was hard to maintain. Since joining the Laravel community, I Instantly made the decision to port everything over. The migration is nearly complete, and I forecast scalable code! Man, my clients will be happy to know that I can meet all of their challenging requirements (which required database changes) very easily now with Eloquent and migrations

  3. Form requests and Validation classes. How awesome are these. I love the abstraction, and I love how they're reusable for different routes. It makes my controller classes very clean.

  4. Continual improvements and implementation of new features to the Laravel framework. This gives me hope that Laravel will truly be at the forefront with it's aim of being a truly easy to use framework for anyone, while being able to keep up with emerging technologies and concepts. Take for example Broadcasting. I haven't tried it out yet, but it's a cool feature for 5.0!

I'm still exploring Laravel so there will be many more things that I will learn and come to love.

The point is, I appreciate your work Taylor, without it, I might have still been writing spaghetti server side code for my mobile applications. :)


iOS developer