ErrorException in HasRelationships.php - php

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');
}

Related

Eloquent belongsToMany returns empty json?

So, Iam trying to make a conversation/message system.
So I have a problem right now. When I use the following line, I get [] (Empty Json):
$this->auth->user()->conversations
User model:
public function conversations()
{
return $this->belongsToMany(\App\Models\Conversation\Conversation::class);
}
But if I use this line, I get data that I want:
$this->auth->user()->messages()->first()->conversation->messages
Also when a line like the following one is used, I get an error
Property [conversation] does not exist on this collection instance.
$this->auth->user()->messages->conversation->messages
Here are Messages model line:
public function conversation()
{
return $this->belongsTo(\App\Models\Conversation\Conversation::class);
}
Here are User model line:
public function messages()
{
return $this->hasMany(\App\Models\Conversation\Messages::class);
}
Here are My database schema:
So my question is, do I do something wrong here or this is just some kind of bug? Thanks for any answers/help.

Relation two tables in Yii2

I have made relation between Buku and Guest. I want to add link download ebook in guest's email. Field link_dl in table Buku.
In common\models\Buku
public function getGuest()
{
return $this->hasOne(Guest::className(), ['id_buku' => 'id_buku']);
}
In common\models\Guest
public function getBuku()
{
return $this->hasMany(Buku::className(), ['id_buku' => 'id_buku']);
}
In Controller
if($model->load(Yii::$app->request->post()))
{
$value = Yii::$app->mailer->compose()
->setFrom('myaccount#gmail.com')
->setTo($model->email)
->setSubject('Download Ebook')
->setTextBody($model->buku->link_dl) //link download ebook $model->relationName->field_name
->send();
$model->save();
But I get an error,
exception 'yii\base\ErrorException' with message 'Trying to get property of non-object'
What is the issue in here? Thankyou. It's Solved
Your relation getBuku is declared as One-to-Many, so when you access buku with $model->buku you get array of Buku models.
If it's really a relation of type One-to-Many you have to choose (with any kind of logic, or simple get the 0 index) the Buku model you need like:
->setTextBody($model->buku[0]->link_dl)
If the relation suppose to be One-to-One, you need to change the relation in Guest model and then to access link_dl as in your code:
// common\models\Guest
public function getBuku()
{
return $this->hasOne(Buku::className(), ['id_buku' => 'id_buku']);
}
// Controller
->setTextBody($model->buku->link_dl)

Laravel Proper Relationship

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!

laravel get last related model

class Keyword extends Model {
public function results()
{
return $this->hasMany('App\Result');
}
}
class Result extends Model {
public function keywords()
{
return $this->belongsTo('App\Keyword');
}
}
these are my classes, but when i access
$keyword->results->where('engine','Google')->last()->created_at
I get error : Trying to get property of non-object
if I var_dump($keyword->results->where('engine','Google')->last()), it show object of Result class
So what I am doing wrong here? i need to filter results that is working fine, but can't access properties/attributes of result
I was accessing results for all keyewords in loop even if there was no related result, I did like
#if($ranking = $keyword->results->where('engine',$engine)->last())
{!! $ranking->created_at !!}
#endif
and the issue is solved, got help from : Laravel 5: “Trying to get property of non-object”

Laravel 5.1 - Relationship method must return an object of type

My application takes payment from users but sub accounts must not be allowed to see the payment screen.
I have a Route::group which checks if the user is allowed to pay through Middleware. The handle function look like this
if(!\Auth::user()->isTeacher)
{
\Auth::logout();
return redirect('/login')->withErrors([$error = 'Sorry there was a problem. Please notify your School']);
}
return $next($request);
and the isTeacher() function
if($this->school_id) {
$teachers = $this->school->find($this->id)->teachers;
$isTeacher = false;
foreach ($teachers as $teacher) {
if ($teacher->id == \Auth::user()->id) {$teacher = true;}
}
return $isTeacher;
}
Finally the School relationship looks like the following
return $this->hasOne('App\School', 'id', 'school_id');
The error I keep receiving is
LogicException in Model.php line 2667:
Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation
In part of the error tree?? it shows this which is from the Middleware
at Model->__get('isTeacher') in MustBeTeacherToMakePayment.php line 19
which is the if statement on the first line above.
Is anyone able to tell me what I'm doing wrong? This is driving me mad
Instead of calling the isTeacher() function you are accessing isTeacher attribute. Eloquent sees a method of that name and identifies it as a method that should return relation definition. And then you get the error because relation definition methods should return Relation object.
You have to replace
if(!\Auth::user()->isTeacher)
with
if(!\Auth::user()->isTeacher())
and the error will be gone.

Categories