deevo's avatar

Accessing properties on a Collection right after fetching it from the Database

So I am trying to fetch a user and then immediately use the data from the object. But, I am not sure how to do that because I keep getting an error telling me I am trying to access a property that doesn't exist.

What I have is a simple contact form where a user contacts another user through the application. I don't want to publicly display email addresses so when the user submits the contact form, I am doing an ajax call passing in the username of the owner of the asset and then looking up that user to get the email address with the username, then getting the email address from that user.

public function contact(ContactSellerRequest $request){
        $input = $request->all();
        try{
            $user = User::where('username', $input['username'])->get();
            //dd($user);  Good here with the user object, but, I cannot access $user->email
        } catch (ModelNotFoundException $e) {
            // Do something here later
        }

        if($user){
            $data = [];
            $data['message'] = $input['message'];
            $message = new Messages($user->email, $user->username);
            $message->contactSeller($data);
            return Response::json(['sent' => true, 'data' => 'Su Correro ha sido Mandado Exitosamente.'], 200);
        }
        return Response::json('error', 400);
    }

Really I just need to know a way I can grab a user for the db and then use their email address immediatly within the same method. I appreciate any insight and you guys here are awesome!

0 likes
8 replies
Snapey's avatar

when you dd($user) you should be able to see the email address?

deevo's avatar

@Snapey yes I can see it, but, is burried somewhere in the object that I don't know how to access it because when I try, I get an error that I cannot access protected properties of the collection.

Cannot access protected property Illuminate\Database\Eloquent\Collection::$items

So yes, I can see the email address in that user object, but, because it is protected I can't seem to get access to it.

bobbybouwmann's avatar

You can simply access the property name like this

$email = $user->email;

Laravel will handle this for you ;)

Snapey's avatar

did you use the standard users table and users model?

deevo's avatar

Yep everything standard and follows the naming conventions. But, it is still giving me an undefined property when trying to access $user->email because that property doesn't exist. If you dd($user) what you get is the raw collection which doesn't have the properties set up yet and everything is protected.

Undefined property: Illuminate\Database\Eloquent\Collection::$email

I am going to try and show you the response when you dd($user) but I don't know how well it will parse out here.

Collection {#226
  #items: array:1 [
    0 => User {#227
      #table: "users"
      #fillable: array:7 [
        0 => "username"
        1 => "email"
        2 => "city"
        3 => "state"
        4 => "confirmed"
        5 => "confirmedstring"
        6 => "password"
      ]
      #hidden: array:2 [
        0 => "password"
        1 => "remember_token"
      ]
      #connection: null
      #primaryKey: "id"
      #perPage: 15
      +incrementing: true
      +timestamps: true
      #attributes: array:12 [
        "id" => 1
        "stripe_customer_id" => ""
        "username" => "Deevoweb"
        "email" => "andrew@deevoweb.com"
        "city" => "Guadalajara"
        "state" => "Jalisco"
        "confirmed" => 1
        "confirmedstring" => ""
        "password" => "$2y$10$3XrUfMIdsYS6kxpdTr8XA.3XR58zXU951ALEP7ekn7Bb6bNGFDpq6"
        "remember_token" => "LWqt1mp4n8UIbgxfdSgwy8Ck5cpAq0yaEeRD0TCuNwKrZtputXpqZAXka6jY"
        "created_at" => "2015-08-07 19:15:50"
        "updated_at" => "2015-08-07 22:18:23"
      ]
      #original: array:12 [
        "id" => 1
        "stripe_customer_id" => ""
        "username" => "Deevoweb"
        "email" => "andrew@deevoweb.com"
        "city" => "Guadalajara"
        "state" => "Jalisco"
        "confirmed" => 1
        "confirmedstring" => ""
        "password" => "$2y$10$3XrUfMIdsYS6kxpdTr8XA.3XR58zXU951ALEP7ekn7Bb6bNGFDpq6"
        "remember_token" => "LWqt1mp4n8UIbgxfdSgwy8Ck5cpAq0yaEeRD0TCuNwKrZtputXpqZAXka6jY"
        "created_at" => "2015-08-07 19:15:50"
        "updated_at" => "2015-08-07 22:18:23"
      ]
      #relations: []
      #visible: []
      #appends: []
      #guarded: array:1 [
        0 => "*"
      ]
      #dates: []
      #casts: []
      #touches: []
      #observables: []
      #with: []
      #morphClass: null
      +exists: true
    }
  ]
}

So that is the raw collection object that is returned when I do an eloquent query. Everything in that object is protected and I have no way to access those properties unless I "Do Something" to that collection so that I can access the data. I just don't know what it is I have to "do"

1 like
bobbybouwmann's avatar
Level 88

Aah I see the problem! Laravel returns a collection when you use get() on a query. If you only want one result you need to use the first() method

// Returns collection (multiple users or array of users)
$users = User::where('username', $input['username'])->get();

// Returns one user
$user = User::where('username', $input['username'])->first();

So you need to update get to first and it should work ;)

1 like
davorminchorov's avatar

That's because it's a collection of multiple items. Try dd($user[$indexNumber]->name) or do a

foreach($users as $user) 
{ 
    var_dump($user->name)
}
deevo's avatar

@Snapey that was it! Thank you. @Ruffles your answer also worked but I only needed the first and no need for an array. However, it is nice to know that I can loop through them if neccessary.

Please or to participate in this conversation.