I am trying to get Store details, belong to a specific user in blade template
getting this error:
"ErrorException Trying to get property 'name' of non-object"
I can get all details in User table, error comes when i am trying to get store table data.
#forelse ($users as $user)
<span class="col-span-1 px-2 py-1 border">{{ $user->store->name }} </span>
#endforeach
User Model
public function store()
{
return $this->hasOne('App\Models\store');
}
store Model
public function user()
{
return $this->belongsTo('App\Models\User' );
}
It works when i added below code to the livewire component class
use Illuminate\Database\Eloquent\Model;
Related
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)
post.php
class post extends Model
{
use HasFactory;
public function publisher()
{
return $this->belongsTo('App\Models\User');
}
protected $fillable = ['title','image','price','Describtion','image1','image2','image3','image4','publisher'];
}
Fetchpost.php
class Fetchpost extends Component
{
use WithPagination;
public function render()
{
return view('livewire.fetchpost', ['posts' => post::orderBy('created_at', 'desc')->paginate(10)],);
}
}
fetchpost.blade.php
<div>
#foreach($posts as post)
<img class="rounded" src="{{ $post->publisher->profile_photo_path }}">
<h1>{{ $post->publisher }}</h1>
<h3>{{ $post->title }}</h1>
<p>{{ $post->Description }}</p>
#endforeach
</div>
so what i'm trying to achieve is to show post with publisher profile info like name and profile photo (like facebook), but i am getting error
Trying to get property 'profile_photo_path' of non-object
the problem here is, you are not passing a foreign key explicitly in relationship. so using naming convention for relationship definition, laravel is looking for a publisher_id (relationship method name _ primary key of the parent table) column in your post table. but there's none as your foreign key is publisher only and laravel can't a build a relationship. thus you are getting your error trying to get property of non object. it's a good practice to reference the foreign key in relationship. or make the foreign key using laravel convention.
public function publisher()
{
return $this->belongsTo('App\Models\User', 'publisher');
}
Need print user name using user_id in File table in my laravel application. This is relationship between User model and File Model .
File Model
public function user()
{
return $this->belongsTo(User::class);
}
This is blade file
#if($files)
#foreach( $files as $file)
<div>
<div>
<span>
{{ $file->user->name }} //line 16
</span>
</div>
</div>
#endforeach
#endif
Controller
class PfilePDFController extends Controller
{
public function getPFPDF($id){
$files = File::where('project_id',$id)->get();
$pdf = PDF::loadView('pdf.projectfiles',['files'=>$files]);
return $pdf->stream('projectfiles.pdf');
}
}
But got this error:
ErrorException in bd52d760518dfb36a05daedee198eefcb7b87914.php line 16: Trying to get property of non-object (View: C:\Users\dnk\Desktop\acxian\resources\views\pdf\projectfiles.blade.php)
How to fix this problem?
Probably user_id is null or has an invalid user id and $file->user returns null. So, you are trying to get name from null.
A good way to avoid this is using or in your code. Ex:
{{ $file->user->name or '-' }}
This will print - if any information in the line is null.
So i have a 3 tables. Users-Inventory-Item. User hasmany Items, so far i have no problem. I can reach Items of User with this relationship.
Item table contains : user_id, item_id
So my problem is to reach item info of the Inventory of the User by item_id(which will find id of Item table and bring the info). I couldn't manage it, I need you advices about which relations would be the proper for my aim.
Models
class User extends Authenticatable
{
public function Inventory(){
return $this->hasMany('App/Item');
}
class UserItem extends Authenticatable
{
public function Item(){
return $this->hasMany('App/Item');
}
Code in my controller
public function profile(){
$inventory_items = Auth::user()->Inventory;
return view('profile', compact('inventory_items'));
}
So i can get User's items with these code but. When i would like to get item info via this $inventory_items->item its not working. I think this is because of relationship mistakes of mine.
Codes in Profile
#foreach($inventory_items as $inventory_item)
{{$inventory_item->Item}}<br><br>
#endforeach
Error
(2/2) ErrorException Class 'App/Item' not found (View:
C:\xampp\htdocs\X-GOTL\resources\views\profile.blade.php)
I think that there is a few errors in your code, no? See my inline comments. Also, you seem to be forgetting that there are many inventories per user and many items per inventory so you need a double-foreach loop.
class User extends Authenticatable
{
# There are many inventories per user so put a plural 's' on items
public function inventories()
{
# This should NOT be App\Item
return $this->hasMany('App\Inventory');
}
...
# This should NOT be UserItem but Inventory, right? (Remember to rename that file too!)
class Inventory extends Authenticatable
{
# There are many items per inventory so put a plural 's' on items
public function items()
{
return $this->hasMany('App\Item');
}
Also your error tells you that you have not created a file App\Item so run php artisan make:model Item.
then in your controller do:
public function profile()
{
$inventories = Auth::user()->inventories;
return view('profile', compact('inventories'));
}
and in your view
#foreach($inventories as $inventory)
#foreach($inventory->items as $item)
{{ $item->name }} or {{ $item->id }}
#endforeach
#endforeach
Dev tend to make mistake \ (correct) and / (wrong).. ErrorException Class 'App/Item' show it cant find 'App/Item' which actually wrong syntax
return $this->hasMany('App/Item');
change to
return $this->hasMany(Item::class);
So guys actually i found the answer i needed. I just needed to create pivot table to make connection between Users and Items. So if someone will have same problem he can watch this video https://www.youtube.com/watch?v=akKWC_vP7sE . Thanks to you for your answers anyways!
I'm using Laravel 5.2. In my application, if a user is an admin, he can see all groups. Otherwise, he can only see his groups.
Model
public function groups() {
if ($this->isAdmin()) {
return \App\Group::get();
}
return $this->belongsToMany('App\Group');
}
View
#foreach($user->groups as $group)
{{ $group->name }}
#endforeach
Result
The code above works if the user is not an admin, but I get this error if the user is an admin
Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation
I tried this instead: $user->groups() as $group, it works when the user is an admin, but show nothing when it's not an admin.
Question
I know when I call a relation as a property ($user->groups), it returns a collection of objects. Instead, if I call it as a function ($user->groups()), I get a QueryBuilder instance.
What can I do to use the same syntax as in my view ?
Note: I cannot add all groups in the database to the admin, as admins must have no group.
The way is not using directly relationship for this but using extra method to handle this.
First in your model create simple relationship:
public function groups()
{
return $this->belongsToMany('App\Group');
}
and then create extra method:
public function availableGroups()
{
if ($this->isAdmin()) {
return \App\Group::get();
}
return $this->groups;
}
Now in view you can use:
#foreach($user->availableGroups() as $group)
{{ $group->name }}
#endforeach