Access attribute of a 'hasOne' related object - php

In my User class I have this function:
public function profile() {
return $this->hasOne('App\Profile');
}
In the controller I used $users = User::all() to get all the users and then pass it to the view using with('users', $users)
In the view where I want to display all of my users profiles I used foreach loop to get to each user data like:
#foreach($users as $user)
<div> {{ $user->profile->some_prfiles_table_column_name }} </div>
But i got an error, So I had to access it using square brackets like this:
{{ $user->profile['some_profiles_table_column_name'] }}
And in another view, where i retrieved only one user by id User::find($id) then i can access the user profile attributes normally as an object NOT array, Like:
{{ $user->profile->some_profiles_table_column_name }}
What i want to understand is Why i'm getting an array instead of an object? Is there is something wrong or this is normal in laravel?
Thanks in advance

You're not getting an array. Eloquent Models implement PHP's ArrayAccess interface, which allows you to access the data as if it were an array.
The problem you're having is that one of your users does not have an associated profile. When that happens, $user->profile will be null. If you attempt to access an object property on null, you'll get a "Trying to get property of non-object" error. However, if you attempt to access an array property of null, it'll just return null without throwing an error, which is why your loop appears to work as an array.
Illustrated with code:
foreach ($users as $user) {
// This will throw an error when a user does not have a profile.
var_export($user->profile->some_profiles_table_column_name);
// This will just output NULL when a user does not have a profile.
var_export($user->profile['some_profiles_table_column_name'];
}
So, presumably, you'll want to handle the situation in your code when the user does not have a profile:
#foreach($users as $user)
<div> {{ $user->profile ? $user->profile->some_profiles_table_column_name : 'No Profile' }} </div>
#endforeach

Related

Why does Livewire run a new query on each render and why are relationships lost

Scenario
What i try to do
I am creating a multicolumn user index page, where the right column shows details from the user selected in the left column.
When selected, the user is not pulled out of the collection but freshly out of the database, so the data is up to date.
I defer the loading of the user list using the described method in the livewire documentation.
The user has a 'roles' relationship, which is displayed in the list column.
What I'd expect
I would expect that once the $this→users is set as a collection of the users and a user is selected, only the query will fire for getting the data for this user.
What actually happens
When a user is selected, a query for getting all users from the database is run (again), and because of the fact that the roles from the user are displayed in the list view, for each user, a new query is executed.
After that, a query for getting the selected user is executed. Afterwards another query for getting the roles of the user is fired to.
So my questions
Why does Livewire lose the relations that were eager loaded in the first declaration of public $users?
Why is it that Livewire reruns the query for getting all users, while the public $users is already defined as a collection of users?
Files:
UserListDetail.php
<?php
namespace App\Http\Livewire;
use App\Models\User;
use Livewire\Component;
class UsersListDetail extends Component {
public string $search = '';
public $users;
public $selectedUser;
public int $timesRun = 0;
public bool $readyToLoadUserList = false;
protected $queryString = [
'search' => [ 'except' => '' ],
];
// Defer loading users
public function readyToLoadUserList()
{
// Get all users with roles relationship
$this->users = User::with('roles')->get();
$this->readyToLoadUserList = true;
}
public function selectUser(int $userId)
{
$this->selectedUser = User::with('roles')->find($userId);
}
public function render()
{
return view('livewire.users-list-detail', [
'selectedUser' => $this->selectedUser,
]
);
}
}
simplified version of user-list-detail.blade.php
<div>
<div wire:init="readyToLoadUserList">
#if($readyToLoadUserList)
<ul>
#foreach($users as $user)
<li wire:click="selectUser({{ $user->id }})">
{{ $user→name_first }} {{ $user→name_last }},
#foreach($user→roles as $role)
{{ $role→label }},
#endforeach
</li>
#endforeach
</ul>
#endif
</div>
<div>
#isset($selectedUser)
{{ $name_first
#endisset
</div>
</div>
When selectUser() method is triggered, the livewire will re-render the blade and since wire:init="readyToLoadUserList" is there, it will load every user (again).
Replce readyToLoadUserList() with mount() and simply keep wire:init="" empty.
Also, condition with #if($users->count() > 0)

Laravel blade "undefined variable" error when using route()

As a project I am building a stackoverflow like forum. On the page on which a single question is shown I want the user to be able to click on the questioner's name and be forwarded to the respective user profile page. I am able to get the name from the database with {{ $question->user->name }}. The problem occurs when adding the part!
Also, the profile pages work. I can access them and the url then says for example: ../profile/1.
This is the route in the web.php file:
Route::get('/profile/{user}', 'PageController#profile')->name('profile');
This is the PageController part:
public function profile($id)
{
$user = User::with(['questions', 'answers', 'answers.question'])->find($id);
return view('profile')->with('user', $user);
}
This is the code from the show.blade View question page which does not work:
<p>
Submitted by {{ $question->user->name }}
</p>
The error message I get is Undefined variable: user.
Which surprises me because forwarding on the profile page to a specific question works with this blade code:
View Question
The respective route in the web.php file:
Route::resource('questions', 'QuestionController');
And QuestionController:
public function show($id)
{
$question = Question::findOrFail($id);
return view('questions.show')->with('question', $question);
}
I thought I defined the variable $user in the PageController like I defined $question in the QuestionController?
I can see you are using Eloquent models with relations. If you want to display the user id on the question, you can use the relation between the Question and User to find the id of the posting user.
Submitted by {{ $question->user->name }}
^^^^^^^^^
//just change your like this way
public function profile($id)
{
$user = User::with(['questions', 'answers', 'answers.question'])->find($id);
return view('profile',compact('user));
}

Laravel get record from database in blade view

I would like to known how to get data from database in blade like from User table:
{{ Auth::user()->name }}
I have table user_settings
I would like to get record from this table by logged user id like this:
{{ UserSettings::user()->my_field }}
How can I do that?
Try this on your blade view
{{ \App\UserSettings::where('user_id',Auth::user()->id)->first()->my_field }}
In default, model file is inside App folder.
Such direct access to database table is not preferred though, you can return this as a variable from controller function like,
$field = \App\UserSettings::where('user_id',Auth::user()->id)->first()->my_field;
return view('view_name',comapact('field'));
and use in blade like
{{$field}}
Another good way is posted by Orkhan in another answer using eloquent relationship.
Hope you understand.
You need to retrieve the UserSettings associated to the authenticated user:
UserSettings::where('user_id', Auth::id())->first()->my_field
You can defined a method named current() to return that for you.
class UserSettings extends Model
{
public static function current()
{
return UserSettings::where('user_id', Auth::id())->first()
}
}
Then use:
UserSettings::current()
On the other had it would better to use one-to-one relationship on user model:
class User extends Model
{
public function settings()
{
return $this->hasOne('App\UserSettings');
}
}
Then use:
Auth::user()->settings->my_field

Laravel Error: Property [id] does not exist on this collection instance. Yet it works on the local server

As mentioned in the title I get the error "Property [id] does not exist on this collection instance." Only when I run the code online here are my relevant codes.
1-EmployeeController (browser tells me that the error is here the second line)
public function show(Employee $employee)
{
$employee = Employee::find ($employee);
$edocument = EDocument::where ('employee_id',$employee->id)->first();
return view ('employee.show')->withEmployee($employee)->withEdocument($edocument);
}
2-show.blade.php
<div class="jumbotron">
<h1>{{$employee->name}} ({{$employee->position}})</h1>
#if (isset($edocument))
Go To Employee Database Page
#else
<p class="lead bg-danger">Employee documents are not uploaded</p>
#endif
Create Employee Contract
if anyone can explain to me this error in more details that would be great also. thanks
ps.. this is my first laravel project (;
You use route model binding in your controller method to get the Employee model. But you also run a find, which would fail since you're passing the model instead of the id. Do as one of the codes shown below and don't mix them.
Do this if you want to use route model binding.
public function show(Employee $employee)
{
$edocument = EDocument::where ('employee_id', $employee->id)->first();
return view ('employee.show')->with(compact('employee', 'edocument'));
}
Do this if you want to pass the employee id and fetch the model in controller.
public function show($employee)
{
$employee = Employee::find($employee);
$edocument = EDocument::where ('employee_id', $employee->id)->first();
return view ('employee.show')->with(compact('employee', 'edocument'));
}
Maybe this can help you. Why don't you pass the information in the controller using -
return view('employee.show', ['employee' => $employee, 'edocument'=>$edocument]);
It worked for me. (Do not have to change anything in the show.blade .php)

Laravel 4: Eloquent relationship get all data

I have 2 relationship data table; users table and memberdetails table.
Users.php
class Users extends Eloquent{
public function memberdetails()
{
return $this->hasOne('Memberdetails','user_id');
}
}
Memberdetails.php
class Memberdetails extends Eloquent{
public function user()
{
return $this->belongsTo('Users','user_id');
}
}
When I try to retrieve data, with $data = User::find($id); I only get data from users table.
Example of my blade form:
{{-- User's Name, stored on user table --}}
{{ Form::text('name',null, array('id'=>'name','class'=>'form-control','required')) }}
{{-- User's address, stored on member table --}}
{{ Form::text('address',null, array('id'=>'address','class'=>'form-control','required')) }}
When I visit, localhost/user/2/edit/, the name field is populated, but address field is empty. How can I retrieve data from both tables and put into a form for editing?
Thank you.
You could use eager loading.
$user = User::with('memberdetails')->find($id);
Using this, you will automatically get the memberdetails when retrieving the user. Then you can use $user->memberdetails
Using eager loading, you do only one query to the DB so it should be the preferred way. If you dont use the with('memberdetails'), you will perform a second query when accessing the memberdetails.
After getting the user instance, access the relationship, then you can access the other class properties
$user = User::find($id);
$userData = $user->memberdetails;

Categories