I am using Laravel 5. I am following this tutorial on using a form to create tagged articles. I replaced the tags with categories. My articles belong to many categories, and my categories belong to many articles. I have a form for creating a new article, but it only creates an entry in the table articles
, not in the pivot table article_category
.
I get this error:
FatalErrorException in ArticlesController.php line 77:
Calling member functions () in an array
I think the problem is with the fourth line in the function store
. I can not find anyone with the same problem. This line should attach the article id
to the category ids
, but it does not work. Grateful for any help.
My articles Controller:
public function store(CreateArticleRequest $request)
{
$article = $request->all();
Article::create($article);
$categoriesId = $request->input('categories');
$article->categories()->attach($categoriesId);
return redirect()->route('articles_path');
}
Namespaces:
namespace App\Http\Controllers;
use App\Article;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Requests\CreateArticleRequest;
use App\Http\Controllers\Controller;
use App\Category;
use App\Day;
Routes
Route::resource('articles', 'ArticlesController', [
'names' => [
'index' => 'articles_path',
'show' => 'article_path',
'edit' => 'articleEdit_path',
'update' => 'articleUpdate_path',
'create' => 'articleCreate_path',
'store' => 'articleStore_path'
]
]);
:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
public function categories()
{
return $this->belongsToMany('App\Category', 'article_category', 'category_id', 'article_id')->withTimestamps();
}
protected $fillable = array('title', 'description', 'image', 'lat', 'lng');
}
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
public function articles()
{
return $this->belongsToMany('App\Article', 'article_category', 'article_id', 'category_id')->withTimestamps();
}
protected $fillable = array('name');
}
PivotTable:
Schema::create('article_category', function (Blueprint $table) {
$table->integer('article_id')->unsigned()->index();
$table->foreign('article_id')->references('id')->on('articles')->onDelete('cascade');
$table->integer('category_id')->unsigned()->index();
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
$table->timestamps();
});