Search code examples
laraveleager-loading

Laravel how to load specific column of related table?


I have the following code, what I want is to take specific columns of related tables.

auth()->user()->load(['business', 'passwordSecurity']);

Solution

  • To select only specific columns from a relationship you should be able to do it like this:

    auth()->user()->load([
        'business' => function ( $query ) {
            $query->select('id', 'title');
        },
        'passwordSecurity',
    ]);
    

    Or like this:

    auth()->user()->load(['business:id,name', 'passwordSecurity']);
    

    Please note that you have to select IDs and foreign key constraints that are needed to form this relationship.