1
votes

OrganizationsController.php

public function user_index()
{   
    if(!is_null(Organization::find(Auth::user()->player->organization))) 
    $organization = Organization::find(Auth::user()->player->organization->id);
    else $organization=null;

    return view('organizations.user_index', [ 'organization' => $organization ]);
}

To avoid "Trying to get property of non-object" when "player" have no "organization" I used this code. But it doesnt seem very nice. There is a better way to obtain this? Maybe im wrong but with this method there is a useless query, am I right?

Table Player: id, name

Table Organization: id, name, player_id

2
Can you give me the the columns of your database? - aldrin27
yes,thx. but I think they are useless. - Manuel Vencato

2 Answers

1
votes

Yes, for this check you might get one unnecessary SQL query executed. You can get rid of this if you do:

if(Organization::find(Auth::user()->player->organization_id) 

instead of

if(!is_null(Organization::find(Auth::user()->player->organization))) 

This way you check organization_id that is stored in player before trying to fetch organization from the database.

1
votes

Assuming user hasOne player, and player hasOne organization, and these relationships are setup correctly, there is no need for either Organization::find() at all. The organization attribute is going to be the loaded Organization object already, so there is no need to re-find it.

public function user_index() {
    // default to null
    $organization = null;

    // make sure there is an authenticated user and it has a player
    if (Auth::user() && Auth::user()->player) {
        // if the player has an organization, this will be the Organzation object
        // if the player does not have an organization, this will be null
        $organization = Auth::user()->player->organization;
    }

    return view('organizations.user_index', [ 'organization' => $organization ]);
}