前提・実現したいこと
現在ログイン機能を持ったTodoアプリを制作しています。
そのアプリでUserモデルに紐づいたフォルダを保存したいのですが、
Auth::user()->folders()->save($folder);
と記述したときに folders() というメソッドはないと表示されます
発生している問題・エラーメッセージ
Undefined method 'folders'.
該当のソースコード
php
1<?php 2 3namespace App\Http\Controllers; 4 5use Illuminate\Http\Request; 6use App\Models\Folder; 7use App\Http\Requests\CreateFolder; 8use Illuminate\Support\Facades\Auth; 9 10class FolderController extends Controller 11{ 12 public function showCreateForm(){ 13 return view('folders/create'); 14 } 15 16 public function create(CreateFolder $request){ 17 //フォルダモデルのインスタンスを作成する 18 $folder = new Folder(); 19 //タイトルを入力する 20 $folder->title = $request->title; 21 //インスタンスの状態をデータベースに書き込む 22 23 24 //エラーが出ている箇所 25 Auth::user()->folders()->save($folder); 26 27 //tasks.indexのアドレスにリダイレクトする。パラメータには folder.id を引数に持つ 28 return redirect()->route('tasks.index', [ 29 'id' => $folder->id, 30 ]); 31 } 32 33} 34
該当のソースコード
php
1<?php 2 3namespace App\Models; 4 5use Illuminate\Contracts\Auth\MustVerifyEmail; 6use Illuminate\Database\Eloquent\Factories\HasFactory; 7use Illuminate\Foundation\Auth\User as Authenticatable; 8use Illuminate\Notifications\Notifiable; 9 10class User extends Authenticatable 11{ 12 use HasFactory, Notifiable; 13 14 /** 15 * The attributes that are mass assignable. 16 * 17 * @var array 18 */ 19 protected $fillable = [ 20 'name', 21 'email', 22 'password', 23 ]; 24 25 /** 26 * The attributes that should be hidden for arrays. 27 * 28 * @var array 29 */ 30 protected $hidden = [ 31 'password', 32 'remember_token', 33 ]; 34 35 /** 36 * The attributes that should be cast to native types. 37 * 38 * @var array 39 */ 40 protected $casts = [ 41 'email_verified_at' => 'datetime', 42 ]; 43 44 45 public function folders(){ 46 47 //このクラスにFolderモデルを紐づける 48 return $this->hasMany('App\Models\Folder'); 49 } 50} 51
試したこと
ここに問題に対して試したことを記載してください。
補足情報(FW/ツールのバージョンなど)
以下開発環境になります。
Laravel 8.50.0
docker 20.10.7
初めての質問なので、質問の仕方に関してご指摘等ありましたらよろしくお願いします。
あなたの回答
tips
プレビュー