Я пытаюсь получить имя пользователя, который создает сообщение ведьма: (модель проблемы) , я не знаю, что не так, я попробую Eager Загрузка в laravel документации, и я должен проверить эти Вопросы 1 Вопросы 2 и все равно получить нулевое значение или Trying to get property 'name' of non-object
, если я использую dd( $problem->user->name);
Я использую laravel 5.8
ЗадачиКонтроллер. php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use App\Problems ;
use App\Rules\Checkbox;
use Validator;
[...]
public function index()
{
//$users_row_num = User::count();
// $problems_row_num = Problems::count();
$problems = Problems::all();
foreach ($problems as $problem) {
/* Here should get name to send with view but I get null
* if I try $problem->user->name I get Trying to get property 'name' of non-object because user is null
*/
dd( $problem->user);
}
return view('problems.index', [
'problems' => $problem,
'user_numder' => $users_row_num,
'problem_number' => $problems_row_num,
]);
}
[...]
Проблемы. php (модель)
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Problems extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
}
Usre. php (модель)
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
[...]
public function problem()
{
return $this->hasMany('App\Problems');
}
[...]
}
index.blade. php
@foreach ($problems as $problem)
<tr>
<td>{{ $problem->accountNumber }}</td>
<td>{{ $problem->accountName }}</td>
<td>{{ $problem->accountEmail }}</td>
<td>{{ $problem->date }}</td>
<td>{{ $problem->problem }}</td>
<td>{{ $problem->addedBy }}</td> <!-- Here I get user id (foreign key) I want to get name of that user -->
<td>{{ $problem->comment }}</td>
<td>{{ $problem->solvedBy }}</td>
<td>{{ $problem->solved }}</td>
<td>{{ $problem->created_at->format('d/m/Y H:i') }}</td>
<td class="text-right"> </td>
</tr>
@endforeach
Таблица задач
[...]
public function up()
{
Schema::create('problems', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('accountNumber');
$table->string('accountName');
$table->string('accountEmail');
$table->date('date');
$table->longText('problem');
$table->bigInteger('addedBy')->unsigned()->nullable();
$table->longText('comment')->nullable();
$table->string('solvedBy')->nullable();
$table->boolean('solved');
$table->timestamps();
});
}
[...]
ForingkeyAddedby миграция
[...]
public function up()
{
Schema::table('problems', function(Blueprint $table){
$table->foreign('addedBy')->references('id')->on('users')->onDelete('set null')->onUpdate('CASCADE');
});
}
[...]
Я хочу использовать $problem->user->name
, чтобы получить имя пользователя, создавшего сообщение, для отображения его в таблице
Пожалуйста, помогите.
СПАСИБО ВСЕМ.