I have a User object that has a one-to-many relationship with a Profile object. I require the fields of the profile object in order to dynamically display it's variables on the web page. i.e. How many 'posts', Their 'description' etc. I ran into some problems regarding this retrieval a few days back. Naturally thinking it was a front-end error, I tried to add '@' tags - however, this seemed to only suppress the errors being flagged and not solve the problem. So I decided to check if when I used my edit profile page, and filled in fields and 'saved', if, on the back end, the fields were updated: that didn't work, and tinker flagged the attached error.
Dynamic calling of user object attributes in html:
<input id="title"
type="text"
class="form-control
@error('title') is-invalid
@enderror"
name="title"
value="{{ old('title') ?? @$user->profile->title}}" required
autocomplete="title" autofocus>
Update Function in ProfilesController (note that the 'profile' property is underlined as yellow)
public function update(User $user)
{$data = request()->validate([
'title' => 'required',
'description' => 'required',
'url' => 'url',
/*'image' => '', */
]);
$user->profile->update($data);
return redirect("/profile/{$user->id}");
}
Note that: the error flagged from this is
'Call to a member function update() on null'
Profile method in the User class:
public function profile()
{return $this->hasOne(Profile::class);}
User method in the Profile class:
public function user()
{return $this->belongsTo(User::class);}
and Finally the error flagged when using Tinkers all();
>>> Profile::all();
[!] Aliasing 'Profile' to 'App\Profile' for this Tinker session.
=> Illuminate\Database\Eloquent\Collection {#3080
all: [],
}
>>>
Removed '@' tags error:
Facade\Ignition\Exceptions\ViewException
Trying to get property 'title' of non-object (View: C:\Users\(PCNAMEfoo)\(PROJECTNAMEfoo)\resources\views\profiles\index.blade.php)
Edit 1 : I thought it would also be helpful to show what happens if I remove the '@' tags and navigate to the index page (under 'Dynamic calling of user object attributes in html').
Edit 2: More information added.
This is my first post, so I hope it's been formatted correctly. Thanks for ANY level of input.