I have Client<->Address relation defined in laravel as below
class Client extends Model
{
use HasFactory;
protected $keyType = 'string';
public $incrementing = false;
protected $fillable = [
'name',
'location',
'status',
];
public function address()
{
return $this->hasOne(ClientAddress::class);
}
}
class ClientAddress extends Model
{
use HasFactory;
public $timestamps = false;
protected $keyType = 'string';
public $incrementing = false;
protected $fillable = [
'street',
'zip',
];
public function client()
{
return $this->belongsTo(Client::class);
}
}
I am able to save it in database.
When I read it like below and print I get address
public function getAddress(Request $request)
{
$client=Client::with('address')->find($request->id);
Log::info($client);
Log::info($client->address);
return ClientAddressResource::make($client->address);
}
first log value is :
[2024-06-22 10:39:15] local.INFO: {“id”:”12cf02ff-fff7-4b8d-8eb5-64d5328afc8b”,”name”:”Client With address”,”location”:”Delhi”,”status”:”OK”,”address”:{“id”:”0b956710-3681-4042-96c2-877345167c46″,”street”:”str1″,”street2″:”str2″,”city”:”some city”,”state”:”stt”,”country”:”India”,”zip”:”1234″,”client_id”:”12cf02ff-fff7-4b8d-8eb5-64d5328afc8b”},”created_at”:”2024-06-20T21:14:50.000000Z”,”updated_at”:”2024-06-20T21:14:50.000000Z”}
second log is empty
[2024-06-22 10:39:15] local.INFO:
last line gives error
[2024-06-22 10:39:15] local.ERROR: Attempt to read property “street” on null {“userId”:”981cfca3-46ed-47a7-91df-5424b563e723″,”exception”:”[object] (ErrorException(code: 0): Attempt to read property “street” on null at …..
I tried a lot of google, and SO answers but none talks about reading of object and convert to json.
R.S is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.