user
,departments
,user_department
テーブルを作成し、
こちらを参考にそれぞれのモデル内でリレーションを定義しています。
ログインユーザーの情報から部署名を取得したいのですが、下記のエラーが出ます。
どうしたらdepartmentsテーブルの部署名を取得できるでしょうか?
Property [departments] does not exist on this collection instance.
UserController.php
namespace App\Http\Controllers\User; use Illuminate\Support\Facades\Auth; class AgentController extends Controller { public function show() { $department = Auth::user()->corp_user_department->departments->department_name; return view('user.show') ->with('department',$department); }
User.php
namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class User extends Model { protected $table = 'users'; use SoftDeletes, protected $fillable = [ 'name', 'email', 'tel', 'password', ]; protected $dates = ['created_at', 'updated_at', 'deleted_at']; public function user_department() { return $this->hasMany(UserDepartment::class); } }
UserDepartment.php
namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class UserDepartment extends Model { protected $table = 'user_department'; use SoftDeletes; public $timestamps = true; protected $dates = ['deleted_at', 'created_at', 'updated_at']; protected $fillable = [ 'user_id', 'department_id', 'role' ]; public function user() { return $this->belongsTo(User::class); } public function department() { return $this->belongsTo(Department::class); } }
Department.php
namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Department extends Model { protected $table = 'departments'; use SoftDeletes; public $timestamps = true; protected $dates = ['deleted_at', 'created_at', 'updated_at']; protected $fillable = [ 'corporation_id', 'branch_office_id', 'department_name', ]; public function corporation() { return $this->belongsTo(Corporation::class); } public function branch_office() { return $this->belongsTo(BranchOffice::class); } public function user_department() { return $this->hasMany(UserDepartment::class); } }