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.
Related
I want to show uploaded pictures of users at my Blade, so I added this:
#foreach($users as $user)
#if($user->photo_id)
<td class="center">
<img src="{{ $user->photos->path }}" width="80">
</td>
#else
<td class="center">
</td>
#endif
#endforeach
But it returns this error:
Exception Property [path] does not exist on this collection instance.
I have already added these relationships to the Models as well:
Photo.php:
public function user()
{
return $this->belongsTo(User::class);
}
User.php:
public function photos()
{
return $this->hasMany(Photo::class);
}
So what is going wrong here ? How can I solve this issue ?
Also when I say: {{ dd($user->photos) }}, it retuns:
Illuminate\Database\Eloquent\Collection {#1231 ▼
#items: []
}
And here is also table photos:
In your User model, you defined one to many relationship. So laravel will return an array of collection.
If you path will not be in array, I suggest you to change the relation to one-to-one.
User.php
public function photos()
{
return $this->hasOne(Photo::class);
}
As far as I understand, you defined your one to many relationship contrariwise.
You're getting multiple photos for a user. So, it is normal to get a collection of photos instead of an instance of photo.
In the result, you don't have path property on photos collection, probably you can handle this error by getting first instance $user->photos->first()->path, but you need to have a clear definition for your model relationship.
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)
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;
Im gettings this error, but i'm not sure is it because of the relationship or something else?
Error
ErrorException in HasRelationships.php line 487:
Class 'Company' not found
User.php
public function company(){
$this->belongsTo('Company', 'user_id');
}
Company.php
public function user(){
$this->belongsTo('User') ;
}
Now my goal is to hide "Create Listing" button in navigation bar, if user doesn't have relation with companies table. I know i can make it with roles or middleware, but my friend send me something like that and told me its easier to make that way.
if(count($user->company) > 0)
So now i'm trying to figure out how, but still can't figure out how to fix the error.
Navigation view
#inject('user', 'App\User')
#if(count($user->company) > 0)
<li>Add listing</li>
#endif
///UPDATE
It didn't find class 'Company', because i wasn't using full namespaces in my relationships, but now i'm getting this new error.
Error
ErrorException in HasAttributes.php line 403:
Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation
(View: /Users/username/Desktop/laravel/resources/views/layouts/partials/_navigation.blade.php)
(View: /Users/username/Desktop/laravel/resources/views/layouts/partials/_navigation.blade.php)
(View: /Users/username/Desktop/laravel/resources/views/layouts/partials/_navigation.blade.php)
Use full namespace in the relationship code:
public function company()
{
return $this->belongsTo('App\Company', 'user_id');
}
I am trying to get data from database and pass values to controller. I am new at laravel and thats the first query. Here is my code:
class Cars extends Eloquent
{
}
FleetController.php
public function index()
{
$fleet = Cars::all()->first()->Description;
return View::make('pages.home')->with('fleet', $fleet);
}
home.blade.php
#extends('layouts.default')
#section('content')
{{ $fleet }}
#stop
The problem is that it shows this at log
Next exception 'ErrorException' with message
'Undefined variable: fleet (View: C:\wamp\www\laravel\app\views\pages\home.blade.php)' in C:\wamp\www\laravel\app\storage\views\7da5cff457f71f3156f90053865b6cb1:2
Stack trace:
You should try using
#if(Session::has('fleet'))
{{Session::get('fleet')}}
#endif
Your '->with()' just flashes the variable to your session. You still need to retrieve it from there though.
Also, you should try creating a model with the same name as your table. If you were to create a model Car that extends Eloquent, it will automatically be linked to your Cars table. Laravel docs:
The lower-case, plural name of the class will be used as the table
name unless another name is explicitly specified.
This part is important as well:
Eloquent will also assume that each table has a primary key column
named 'id'.
Once you got that configured, you'll be able to get the description of a car by simple doing
Car::all()->first()->description;
See also: Laravel docs on eloquent
Update
What should work:
Car.php
class Car extends Eloquent{
//Let's try setting these manually. Make sure they are correct.
protected $table = 'cars';
protected primaryKey = 'id';
}
FleetController.php
public function index()
{
//You have to call the model here, so singular 'Car'.
$fleet = Car::all()->first()->Description;
return View::make('pages.home')->with('fleet', $fleet);
}
home.blade.php
#extends('layouts.default')
#section('content')
//You can use blade's #if as well:
#if(Session::has('fleet'))
{{Session::get('fleet')}}
#endif
#stop