试图获取非对象Laravel PHP 5.8的属性'cname'

时间:2019-06-07 10:57:38

标签: php laravel object error-handling laravel-5.8

我正在学习laravel 5.8,并且正在构建一个职业门户网站。

我的问题是为什么会发生此错误。我已经检查了我的表,很显然,在公司表中有一个列cname(公司名)。而且我还有一个对象。

以下是我的代码。如果有人帮助我,我真的很高兴。

此代码用于识别用户是求职者还是雇主。 我想注册为求职者。

this is my error page.

app.blade.php

<li class="nav-item dropdown">
                                <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
                                    @if(Auth::user()->user_type='company')
                                        {{Auth::user()->company->cname}}
                                    @else
                                        {{Auth::user()->name}}
                                    @endif
                                    <span class="caret"></span>
                                </a>

user.php

use App\Profile;
use App\Company;

public function profile(){
        return $this->hasOne(Profile::class);
        }

    public function company(){
        return $this->hasOne(Company::class);
        }

web.php

Route::POST('employer/register', 'EmployerRegisterController@employerRegister')->name('emp.register');

Route::view('employer/register','auth.employer-register')->name('employer.register');

CompanyController.php

public function store(Request $request){

        $user_id = auth()->user()->id;
        Company::where('user_id',$user_id)->update([
            'address'=>request('address'),
            'phone'=>request('phone'),
            'website'=>request('website'),
            'slogan'=>request('slogan'),
            'description'=>request('description')
        ]);
        return redirect()->back()->with('message','Company Successfully Updated !');
    }

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

因为Auth::user()->companyNull而引发错误。尝试获取类似Auth::user()->company->cname ?? ''

的关系属性时,请使用三元运算符
<li class="nav-item dropdown">
    <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
        @if(Auth::user()->user_type == 'company')
            {{Auth::user()->company->cname ?? ''}}
        @else
            {{Auth::user()->name}}
        @endif
        <span class="caret"></span>
    </a>
</li>

答案 1 :(得分:0)

结果似乎未返回任何内容。因为只有=而不是==,请尝试如下操作:

<li class="nav-item dropdown">
                                <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
                                    @if(Auth::user()->user_type=='company')
                                        {{Auth::user()->company->cname}}
                                    @else
                                        {{Auth::user()->name}}
                                    @endif
                                    <span class="caret"></span>
                                </a>