此代码与我们的小组项目有关。当我使用下面的代码时,它是
调用未定义的方法stdClass :: subjects()。
我尝试了很多方法,但无法解决。
以下代码部分给出错误
<td>{{$user->subjects()->get()[0]->name}},{$user->subjects()->get()[1]->name}} </td>
@foreach($users as $user)
<tr><td>{{$user->name }} </td>
<td>{{$user->email}} </td>
<td>{{$user->id}} </td>
<td>{{$user->subjects()->get()[0]->name}},{$user->subjects()->get()[1]->name}} </td>
</tr>
@endforeach
Subject.php的代码
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Subject extends Model
{
protected $table='subject';
protected $fillable = ['id','name','created_at','updated_at','user_id'];
protected $primaryKey='id';
public function user(){
return $this->belongsTo('App\User');
}
User.php的代码
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
protected $table='users';
protected $fillable = [
'usertype','name','lname', 'email','dob','school','phone','gender','password','verifyToken'
];
protected $hidden = [
'password', 'remember_token',
];
)
}
public function subjects()
{
return $this->hasMany('App\Subject','user_id','id');
}
}
控制器的代码如下所示。我删除了一些代码部分以避免这很长。它们不会导致错误
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\User;
use App\Subject;
use PDF;
class pdfGenerator extends Controller
{
public function reportPdf()
{
$users = DB::table('users')->get();
$pdf = PDF::loadview('reports', ['users' => $users]);
return $pdf->download('report.pdf');
}
public function report()
{
$users = DB::table('users')->get();
return view('reports', ['users' => $users]);
}
}
答案 0 :(得分:1)
更改此行
$users = DB::table('users')->get();
要
$users = User::all();
如果您希望only
主题名称加上comma separated
,请在view
中执行此操作,
<?php $subject_names = $user->subjects()->pluck('name');
$subject_names_in_string = implode(',',$subject_names);
?>
<td>{{$subject_names_in_string}} </td>