laravel - Two store() methods, one doesn't work (Call to undefined method save()) -
one of 2 similar store methods doesn't work. clarify me?
relations
- a team hasmany users <> user belongsto team
- a user hasmany characters <> character belongsto user
working code (charactercontroller)
public function store() { $fighters = fighter::pluck('name')->toarray(); $this->validate(request(), [ 'name' => 'required|min:3|max:25|alpha_num|not_in:'.rule::notin($fighters).'unique:characters', 'fighter' => 'required|in:'.rule::in($fighters), ]); auth()->user()->characters()->save(new character([ 'name' => request('name'), 'fighter' => request('fighter'), ])); return redirect()->route('character.index'); }
not working (teamcontroller)
public function store() { $this->validate(request(), [ 'name' => 'required|min:3|max:25|alpha_num|unique:teams', ]); auth()->user()->team()->save(new team([ 'name' => request('name'), 'fame' => 0, ])); return redirect()->route('team.index'); }
questions
- why same method not available? relation stuff?
- is create method better? should try use it?
thought know i'm doing, turns out don't... thank helping.
team()
belongsto
relation, have team_id col in user table want associate team.
public function store() { $this->validate(request(), [ 'name' => 'required|min:3|max:25|alpha_num|unique:teams', ]); // create , save team $team = new team([ 'name' => request('name'), 'fame' => 0, ]); $team->save(); // associate current authenticated user team (set foreign key) , save user auth()->user()->team()->associate($team)->save(); return redirect()->route('team.index'); }
Comments
Post a Comment