Laravel 5 relationship belongsTo not working - php

First of all what I want to achieve it's quite simple : I want to use relationship belongsTo from Laravel 5 to get a value from another table. Like so
<?= $email->contact->first_name; ?>
But this is not working at all, instead, I get this error : Trying to get property of non-object. But when I do print_r($email) it shows me that $email is actually an object...So I really don't understand now.
This is (a part of) what I have in my Controller :
$emails = Email::where('user_id', '=', Auth::user()->id)->take(6)->orderBy('created_at', 'desc')->get();
This is what I have in my view :
foreach($emails as $key => $email) {
echo $email->contact->first_name; ?>
}
This is my model email
public function contact()
{
return $this->belongsTo('App\Contact', 'contact_id');
}
As you can see, I am using a second parameter inside belongsTo method, which is 'contact_id' because I don't want to use 'user_id' as the foreign key.
EDIT:
This is my output of print_r($email) :
App\Email Object ( [connection:protected] => [table:protected] => [primaryKey:protected] => id [perPage:protected] => 15 [incrementing] => 1 [timestamps] => 1 [attributes:protected] => Array ( [id] => 88 [user_id] => 1 [group_id] => 1 [contact_id] => 79 [reminder_id] => 31 [subject] => Test task #3 [view] => 0 [view_hash] => $2y$10$NZ3B.UUqtRRl2opH5UwXOeRNeRROeZGdid6Crs4ShT1VptbZJS.iu [content] => blablabla
EDIT 2 :
This is my output of print_r($email->contact) :
App\Contact Object ( [fillable:protected] => Array ( [0] => title [1] => content ) [table:protected] => contacts [connection:protected] => [primaryKey:protected] => id [perPage:protected] => 15 [incrementing] => 1 [timestamps] => 1 [attributes:protected] => Array ( [id] => 86 [user_id] => 1 [group_id] => 1 [first_name] => Matthieu [last_name] => Boistoule [email] => m.boistoule#gmail.com [phone] => [company] => [title] => [website] => [industry] => [address] => [city] => [country] => [province] => [postal_code] => [lead_source] => [notes] => [created_at] => 2015-06-04 12:13:00 [updated_at] => 2015-06-04 12:13:00 ) [original:protected] => Array ( [id] => 86 [user_id] => 1 [group_id] => 1 [first_name] => Matthieu [last_name] => Boistoule [email] => m.boistoule#gmail.com [phone] => [company] => [title] => [website] => [industry] => [address] => [city] => [country] => [province] => [postal_code] => [lead_source] => [notes] => [created_at] => 2015-06-04 12:13:00 [updated_at] => 2015-06-04 12:13:00 ) [relations:protected] => Array ( ) [hidden:protected] => Array ( ) [visible:protected] => Array ( ) [appends:protected] => Array ( ) [guarded:protected] => Array ( [0] => * ) [dates:protected] => Array ( ) [casts:protected] => Array ( ) [touches:protected] => Array ( ) [observables:protected] => Array ( ) [with:protected] => Array ( ) [morphClass:protected] => [exists] => 1 )

Related

Laravel Getting attributes data

I am new in laravel using Laravel 5.3.
I am creating a check() function in laravel model for user login
here i get all data form database useing default $this->all(); this return me a large multidymentional
array .
Illuminate\Database\Eloquent\Collection Object
(
[items:protected] => Array
(
[0] => App\wn_users Object
(
[table:protected] => wn_users
[timestamps] =>
[fillable:protected] => Array
(
[0] => role_id
[1] => firstname
[2] => lastname
[3] => username
[4] => email
[5] => password
[6] => companyname
[7] => country_id
[8] => description
[9] => ip
[10] => update_date
[11] => status
)
[connection:protected] =>
[primaryKey:protected] => id
[keyType:protected] => int
[incrementing] => 1
[with:protected] => Array
(
)
[perPage:protected] => 15
[exists] => 1
[wasRecentlyCreated] =>
[attributes:protected] => Array
(
[user_id] => 1
[role_id] => 1
[firstname] => Aman kumar
[lastname] => --
[username] => Aman kumar
[email] => aman.imaxtechnologies#gmail.com
[password] => e10adc3949ba59abbe56e057f20f883e
[companyname] => Imax
[country_id] => 123
[description] => Testing
[ip] => 192.168.1.1
[update_date] => 2017-03-20
[status] => 0
[created_at] =>
[updated_at] =>
)
[original:protected] => Array
(
[user_id] => 1
[role_id] => 1
[firstname] => Aman kumar
[lastname] => --
[username] => Aman kumar
[email] => aman.imaxtechnologies#gmail.com
[password] => e10adc3949ba59abbe56e057f20f883e
[companyname] => Imax
[country_id] => 123
[description] => Testing
[ip] => 192.168.1.1
[update_date] => 2017-03-20
[status] => 0
[created_at] =>
[updated_at] =>
)
[casts:protected] => Array
(
)
[dates:protected] => Array
(
)
[dateFormat:protected] =>
[appends:protected] => Array
(
)
[events:protected] => Array
(
)
[observables:protected] => Array
(
)
[relations:protected] => Array
(
)
[touches:protected] => Array
(
)
[hidden:protected] => Array
(
)
[visible:protected] => Array
(
)
[guarded:protected] => Array
(
[0] => *
)
)
)
)
But i want to get only 'attributes:protected' Form whole array in laravel . I have already tried
echo $data = $this->getAttributes()['firstname']; but this returns error
Undefined index: firstname
Please help me to resolve my issue
Thanks in Advance for your help and time .
A very simple way:
$arr = $this->all()->toArray();
var_dump($arr); // oh~ array data!
So you have a collection with properties. And you can access them just like $collection->first()->firstname Or if you want to do some operation with all items use each method:
$collection = $collection->each(function ($item, $key) {
$item->firstname .= ' Smith';
});

laravel assocation issue with user model

I have the association ads table with users how I can show the users
data. It shows me error trying to get property of non object
association.
Tables:
ads
users (default Laravel)
In User Model:
public function ads()
{
return $this->hasMany('App\Ad','user_id');
}
In Ad Model
public function user()
{
return $this->belongsTo('App\User');
}
in Routes
Route::get('/ads',function(){
$ads = Ad::get();
//print_r($ads);
foreach ($ads as $ad) {
echo $ad->user->name;// issue here
}
});
It prints this array when I print_r($ad->user);
App\User Object ( [fillable:protected] => Array ( [0] => name [1] => phone [2] => email [3] => password [4] => role ) [hidden:protected] => Array ( [0] => password [1] => remember_token ) [connection:protected] => [table:protected] => [primaryKey:protected] => id [perPage:protected] => 15 [incrementing] => 1 [timestamps] => 1 [attributes:protected] => Array ( [id] => 1 [name] => irfan [email] => irfan0786#gmail.com [phone] => 43434 [password] => $2y$10$dnUuC9yxQwSHcpWy1oZlpuxaU33eBz1VYCPFQgfJYtncDivmDfqym [role] => User [remember_token] => x3l3x1tkXUB3I7KiRggPRclnCR5JGnDLlzCxZxeAmfpGCYFR0ylSrKNwSSuy [created_at] => 2016-06-12 17:42:36 [updated_at] => 2016-06-22 03:26:28 ) [original:protected] => Array ( [id] => 1 [name] => irfan [email] => irfan0786#gmail.com [phone] => 43434 [password] => $2y$10$dnUuC9yxQwSHcpWy1oZlpuxaU33eBz1VYCPFQgfJYtncDivmDfqym [role] => User [remember_token] => x3l3x1tkXUB3I7KiRggPRclnCR5JGnDLlzCxZxeAmfpGCYFR0ylSrKNwSSuy [created_at] => 2016-06-12 17:42:36 [updated_at] => 2016-06-22 03:26:28 ) [relations:protected] => Array ( ) [visible:protected] => Array ( ) [appends:protected] => Array ( ) [guarded:protected] => Array ( [0] => * ) [dates:protected] => Array ( ) [dateFormat:protected] => [casts:protected] => Array ( ) [touches:protected] => Array ( ) [observables:protected] => Array ( ) [with:protected] => Array ( ) [morphClass:protected] => [exists] => 1 [wasRecentlyCreated] => )
To get all the ads you should use, Ad::all() not Ad::get().
Update your Ad model as one user has one ad:
public function ads()
{
return $this->hasOne('App\Ad','user_id');
}

array format issue PHP

I want to change an array format according to my needs. When I fetch data from a database using cakephp find('all') method, it returns something that is not in the format that I expected.
My resultant array is:
Array
(
[0] => Array
(
[DriverLocation] => Array
(
[id] => 15
[dispensary_id] => 1
[driver_id] => 85
[zip_code_id] => 43
[created] => 2015-05-20 12:25:34
)
[ZipCode] => Array
(
[id] => 43
[province_id] => 3846
[city] => Rohtak
[zip_code] => 15478
[status] => active
)
[UserProfile] => Array
(
[first_name] => Arman
[last_name] => Kumar
)
)
[1] => Array
(
[DriverLocation] => Array
(
[id] => 19
[dispensary_id] => 1
[driver_id] => 43
[zip_code_id] => 42
[created] => 2015-05-20 12:37:12
)
[ZipCode] => Array
(
[id] => 42
[province_id] => 3846
[city] => Rohtak
[zip_code] => 30215
[status] => active
)
[UserProfile] => Array
(
[first_name] => Pawan
[last_name] => Kumar
)
)
[2] => Array
(
[DriverLocation] => Array
(
[id] => 20
[dispensary_id] => 1
[driver_id] => 83
[zip_code_id] => 42
[created] => 2015-05-20 12:37:28
)
[ZipCode] => Array
(
[id] => 42
[province_id] => 3846
[city] => Rohtak
[zip_code] => 30215
[status] => active
)
[UserProfile] => Array
(
[first_name] => Ramesh
[last_name] => Saini
)
)
[3] => Array
(
[DriverLocation] => Array
(
[id] => 26
[dispensary_id] => 1
[driver_id] => 83
[zip_code_id] => 43
[created] => 2015-05-20 12:43:59
)
[ZipCode] => Array
(
[id] => 43
[province_id] => 3846
[city] => Rohtak
[zip_code] => 15478
[status] => active
)
[UserProfile] => Array
(
[first_name] => Ramesh
[last_name] => Saini
)
)
[4] => Array
(
[DriverLocation] => Array
(
[id] => 41
[dispensary_id] => 1
[driver_id] => 83
[zip_code_id] => 6
[created] => 2015-05-21 05:23:53
)
[ZipCode] => Array
(
[id] => 6
[province_id] => 3846
[city] => Whittier
[zip_code] => 90607
[status] => active
)
[UserProfile] => Array
(
[first_name] => Ramesh
[last_name] => Saini
)
)
)
And I want to convert it into something like this:
Array
(
[DriverLocation] => Array
(
[id] => 15
[dispensary_id] => 1
[driver_id] => 85
)
[ZipCode] => Array
(
[zip_code] => Array
(
[0] => 15478
)
[city] => Array
(
[0] => Rohtak
)
)
[UserProfile] => Array
(
[first_name] => Arman
[last_name] => Kumar
)
)
Array
(
[DriverLocation] => Array
(
[id] => 19
[dispensary_id] => 1
[driver_id] => 43
)
[ZipCode] => Array
(
[zip_code] => Array
(
[0] => 30215
)
[city] => Array
(
[0] => Rohtak
)
)
[UserProfile] => Array
(
[first_name] => Pawan
[last_name] => Kumar
)
)
Array
(
[DriverLocation] => Array
(
[id] => 20
[dispensary_id] => 1
[driver_id] => 83
)
[ZipCode] => Array
(
[zip_code] => Array
(
[0] => 30215
[1] => 15478
[2] => 90607
)
[city] => Array
(
[0] => Rohtak
[1] => Rohtak
[2] => Whittier
)
)
[UserProfile] => Array
(
[first_name] => Ramesh
[last_name] => Saini
)
)
Filter according to DriverLocation->driver_id
Seems that these arrays are exactly the same, except that you put every "record" of DriverLocation in its own variable. The idea here is that you receive the data from the DriverLocation Model in the fictional controller and put it in a variable; for example:
$allDriverLocations = $this->DriverLocation->find("all");
Now $allDriverLocations contains the first one of your mentioned arrays.
Next step is to pass it to the view:
$this->set(compact("allDriverLocations"));
And now to create a table in the associated view you should iterate through $allDriverLocations:
<table>
<tbody>
<?php
// Loop through the array with a foreach
foreach($allDriverLocations as $driverLocation){
// Create the table row here using the HtmlHelper.
// If you want to reach "Rohtak" for example, you use $driverLocation["Zipcode"]["city"] to print it.
}
?>
</tbody>
</table>
I wouldn't know why you should not follow Cake's easy conventions...

Laravel Eloquent Get Append Attributes With Find

I created a model with 10 append attributes and I can't get them with find() method. But when I convert returned object from find() to an array with method toArray() I can see them but I need them like an object.
This object was printed when I use find():
School Object
(
[table:protected] => schools
[fillable:protected] => Array
(
[0] => name
[1] => type_id
[2] => description
[3] => info_specialties
[4] => contacts
[5] => cover_name
[6] => financing_id
[7] => city
)
[guarded:protected] => Array
(
[0] => id
)
[appends:protected] => Array
(
[0] => type
[1] => short_type
[2] => school_url
[3] => cover_photo_url
[4] => cover_photo_thumbnail_url
[5] => city
[6] => municipality
[7] => appended_district_id
[8] => district
[9] => description_without_tags
)
[district_id] =>
[cover_photo] =>
[connection:protected] =>
[primaryKey:protected] => id
[perPage:protected] => 15
[incrementing] => 1
[timestamps] => 1
[attributes:protected] => Array
(
[id] => 24
[type_id] => 3
[name] => adasdasd
[description] =>
asdadasdasdasdqwdqd\qw\[dqw\d
[info_specialties] =>
qwqwdqwdqwdqwdqwd
[contacts] =>
qwdqwdqwdqwd
[cover_name] => SAbjfpe4m7.jpg
[financing_id] => 1
[city_id] => 18
[created_at] => 2015-01-31 20:56:06
[updated_at] => 2015-02-04 18:50:13
)
[original:protected] => Array
(
[id] => 24
[type_id] => 3
[name] => adasdasd
[description] =>
asdadasdasdasdqwdqd\qw\[dqw\d
[info_specialties] =>
qwqwdqwdqwdqwdqwd
[contacts] =>
qwdqwdqwdqwd
[cover_name] => SAbjfpe4m7.jpg
[financing_id] => 1
[city_id] => 18
[created_at] => 2015-01-31 20:56:06
[updated_at] => 2015-02-04 18:50:13
)
[relations:protected] => Array
(
)
[hidden:protected] => Array
(
)
[visible:protected] => Array
(
)
[dates:protected] => Array
(
)
[touches:protected] => Array
(
)
[observables:protected] => Array
(
)
[with:protected] => Array
(
)
[morphClass:protected] =>
[exists] => 1
)
And when I use toArray:
Array
(
[id] => 24
[type_id] => 3
[name] => adasdasd
[description] =>
asdadasdasdasdqwdqd\qw\[dqw\d
[info_specialties] =>
qwqwdqwdqwdqwdqwd
[contacts] =>
qwdqwdqwdqwd
[cover_name] => SAbjfpe4m7.jpg
[financing_id] => 1
[city_id] => 18
[created_at] => 2015-01-31 20:56:06
[updated_at] => 2015-02-04 18:50:13
[type] => qdasdasd
[short_type] => asdasdasd
[school_url] => http://localhost:8000/school/24
[cover_photo_url] => http://localhost:8000/storage/cover_photos/SAbjfpe4m7.jpg
[cover_photo_thumbnail_url] => http://localhost:8000/storage/cover_photos/thumbnails/SAbjfpe4m7.jpg
[city] => sdasdasd
[municipality] => ÐÑкаква община2 от нÑкакъв облаÑÑ‚2
[appended_district_id] => 6
[district] => ÐÑкакъв облаÑÑ‚2
[description_without_tags] => asdadasdasdasdqwdqd\qw\[dqw\d
)
Here's an example of my class:
<?php
class School extends Eloquent {
protected $appends = array('type');
public function getTypeAttribute()
{
return Type::find($this->type_id)->name;
}
}
That's the nature of custom attributes that you get with an attribute accessor. They will only be evaluated when used (and then cached for later use). When you convert it to and array, all $appends properties are loaded.
If you have your model object you can just access them like any other attribute:
$school->type;

Store a variable from the array of object php

I have a php variabl $purchase_data which when I did
print_r('purchase_data');
I got the output as
Array
(
[downloads] => Array
(
[0] => Array
(
[id] => 28
[options] => Array
(
)
[quantity] => 1
)
)
[fees] => Array
(
)
[subtotal] => 1
[discount] => 0
[tax] => 0
[price] => 1
[purchase_key] => a8d14e34ba425f9de6afe3ad4809587e
[user_email] => esh#test.com
[date] => 2014-05-11 20:07:22
[user_info] => Array
(
[id] => 1
[email] => eshtest.com
[first_name] => esh
[last_name] =>
[discount] => none
[address] =>
)
[post_data] => Array
(
[edd_email] => esh#test.com
[edd_first] => esh
[edd_last] =>
[edd_phone] => 919995871693
[edd-user-id] => 1
[edd_action] => purchase
[edd-gateway] => sample_gateway
)
[cart_details] => Array
(
[0] => Array
(
[name] => Shirt
[id] => 28
[item_number] => Array
(
[id] => 28
[options] => Array
(
)
[quantity] => 1
)
[item_price] => 1
[quantity] => 1
[discount] => 0
[subtotal] => 1
[tax] => 0
[price] => 1
)
)
[gateway] => sample_gateway
[card_info] => Array
(
[card_name] =>
[card_number] =>
[card_cvc] =>
[card_exp_month] =>
[card_exp_year] =>
[card_address] =>
[card_address_2] =>
[card_city] =>
[card_state] =>
[card_country] =>
[card_zip] =>
)
)
How can i store the value to edd_phone [edd_phone] into variable $mobileNo ?
Sorry for ths kind of a question.But badly need help
If you want to assign the value of [edd_phone] to $mobileNo , use this :
$mobileNo = $purchase_data['post_data']['edd_phone'];
As a side note : Your array is very complexly nested. If I were you, I would avoid such complex arrays.

Categories