【问题标题】:Trying to get property 'name' of non-object in Laravel (View: D:\...\resources\views\home.blade.php试图在 Laravel 中获取非对象的属性“名称”(视图:D:\...\resources\views\home.blade.php
【发布时间】:2020-06-03 01:26:23
【问题描述】:

我在这里遇到一个小问题,代码没有得到我猜想的名称的正确形式...... 这是它向我显示错误的地方:

                <div class="rank-label-container">
                    <span class="label label-default rank-label">{{$user ?? ''->name}}</span>
                </div>

有人试图让我相信我的错误在 create_user_table 中:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->string('avatar')->default('user.jpg');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

但是我在这里没有发现任何问题。 关于如何修复它的任何建议? 如果您需要代码中的其他内容,请告诉我,我不知道我还应该给您什么,以便您帮助我。 提前致谢!

【问题讨论】:

  • 这将起作用:{{$user-&gt;name ?? null }}
  • 它工作正常。谢谢!现在它已经开始工作了。非常感谢你,你在拯救我的皮肤。
  • 不客气

标签: php laravel


【解决方案1】:

试试这个..

{{dd($user)}}

如果你得到财产name 那么你可以像这样打电话..

{{$user['name']}}

将其作为数组而不是对象获取

【讨论】:

  • 它告诉我有未定义的变量:用户,它建议我转回它的形式:{{ $user ?? '' }}
  • 这意味着您必须将 $user 包含在 plade 中,就像您的控制器是 return view('your_view_name');你必须包括这样的使用 return view('your_view_name',compact('user'));并且几乎用户应该是这样的 $user = User::find(1) 或 Auth::user() ect
  • {{ $user ?? '' }} 表示如果没有变量是用户做任何事情..
  • 谢谢,下次知道。这解释了很多:)
【解决方案2】:

试试这个,我相信它会工作 {{$user->name}} 或者 {{$user['name']}}

【讨论】:

  • 在这两种情况下,它都向我表明存在未定义的变量:用户,并建议我将其转回形式:{{ $user ?? '' }}
  • 是的,您没有返回任何数组以查看因此获取未定义的变量,因此您从数据库中获取数据并存储在数组中并返回查看,然后您可以使用 foreach 语句对其进行迭代,然后使用此 {{ $user->name}} 或 {{$user['name']}} 显示它。
  • 谢谢,下次会使用这个,因为我尝试过其他人的建议,但正如我所见,这不是我第一次尝试使用/for web。
猜你喜欢
  • 2018-09-25
  • 1970-01-01
  • 1970-01-01
  • 2020-04-16
  • 2020-10-31
  • 2019-11-16
  • 1970-01-01
  • 2020-11-15
  • 2019-12-13
相关资源
最近更新 更多