朋友们算在社交网络的标题中

时间:2022-10-31 21:28:52

I'm still learning in Laravel and as project I chose my Social Network which I already have in CodeIgniter.

我还在Laravel学习,作为项目,我选择了我已经在CodeIgniter中使用的社交网络。

Someone who has more experience in Laravel as me recommended me to use in my header.blade this. Auth()->User()->GetFriendsCount()

我在Laravel有更多经验的人建议我在我的header.blade中使用。 AUTH() - >用户() - > GetFriendsCount()

My Users Model

我的用户模型

public function friends()
{
    return $this->hasMany('App\Models\Friends', 'receiver_id');
}

public function GetFriendsCount()
{
    return $this->friends->count(); //didn't help
    return $this->friends()->count(); //didn't help
}

I get following as error Call to undefined method Illuminate\Database\Query\Builder::GetFriendsCount()

我得到以下错误调用未定义的方法Illuminate \ Database \ Query \ Builder :: GetFriendsCount()

Who can help me and how will I reach my result?

谁可以帮助我,我将如何达到我的结果?

2 个解决方案

#1


0  

if you not connected Auth()->User() return null

如果你没有连接Auth() - > User()返回null

<?php   
if(Auth()->User())
    dd(Auth()->User()->GetFriendsCount());
else dd('not connect');

#2


0  

Try this code out:

试试这个代码:

User model:

用户模型:

public function friends()
{
    return $this->hasMany('App\Models\Friends', 'receiver_id');
}

public function getFriendsCount()
{
    return $this->friends()->count();
}

Try playing around with an instance of the model in artisan tinker before running it in your view. You could do something like this:

在您的视图中运行模型之前,请尝试在工匠修补匠中使用模型实例。你可以这样做:

php artisan tinker // get into tinker

$u = App\Models\User::first(); // grab the first user in the db, they should have some App\Models\Friends linked to them

$u->getFriendsCount(); // test out the method

You can run the method in your blade view like so:

您可以在刀片视图中运行该方法,如下所示:

Auth::user()->getFriendsCount()

#1


0  

if you not connected Auth()->User() return null

如果你没有连接Auth() - > User()返回null

<?php   
if(Auth()->User())
    dd(Auth()->User()->GetFriendsCount());
else dd('not connect');

#2


0  

Try this code out:

试试这个代码:

User model:

用户模型:

public function friends()
{
    return $this->hasMany('App\Models\Friends', 'receiver_id');
}

public function getFriendsCount()
{
    return $this->friends()->count();
}

Try playing around with an instance of the model in artisan tinker before running it in your view. You could do something like this:

在您的视图中运行模型之前,请尝试在工匠修补匠中使用模型实例。你可以这样做:

php artisan tinker // get into tinker

$u = App\Models\User::first(); // grab the first user in the db, they should have some App\Models\Friends linked to them

$u->getFriendsCount(); // test out the method

You can run the method in your blade view like so:

您可以在刀片视图中运行该方法,如下所示:

Auth::user()->getFriendsCount()