new Article($validatedAttributes);
$validatedAttributes is a variable, not a method, and it is in the same scope so there is not $this
I am going through Laravel from scratch using Laravel 8. on Episode 33 - Attach and Validate Many-to-Many Inserts.
Have have added the tags array in my blade view and No issues there. This is a multi select so I named the select field tags[] When I submit my form I get error: "Method name must be a string" Showing line 75 in my ArticleController
$article = new Article($this->$validatedAttributes());
ArticleController store function
public function store(){
// dd(request()->all());
// validate request and store as $validatedAttributes for mass insertion.
$validatedAttributes = request()->validate([
'title' => 'required',
'excerpt' => 'required',
'body' => 'required',
'tags' => 'required|array'
]);
// Persist the new resource/Article
//Article::create($validatedAttributes);
$article = new Article($this->$validatedAttributes());
$article->user_id = 1; // auth()->id()
$article->save();
$article->tags()->attach(request('tags'));
return redirect('/articles');
}
My Model
namespace App\Models;
use App\User;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
use HasFactory;
protected $fillable = ['title', 'excerpt', 'body', 'tags'];
// protected $guarded = []; // turns off the need for protected $fillable for mass assignment.
public function author()
{
// an ar
return $this->belongsTo(User::class, 'user_id');
}
// an article has many tags, tags can have many articles
public function tags(){
return $this->belongsToMany(tag::class);
}
}
What am I missing? I would be grateful for any assistance.
Sorry a small error in my example, but remember that $validatedAttributes is a variable and not a method, it should be like this:
$article = new Article(Arr::except($validatedAttributes, 'tags'));
note the difference from before, i removed the () after $validatedAttributes now.
Please or to participate in this conversation.