I am using Laravel 5. I have been following this tutorial about using a form to create an article with 'tags'. I have replaced tags with categories. My articles 'belong to many' categories and my categories 'belong to many' articles. I have a form to create a new article but it only creates an entry in the articles table and not in the 'article_category' pivot table.
I get this error: "FatalErrorException in ArticlesController.php line 77: Call to a member function categories() on array". I think the problem is with fourth line in the 'store' function. I can't find anyone with the same problem. That line is supposed to attach the article id to the category ids but it's not working. Grateful for any help.
My ArticlesController:
public function store(CreateArticleRequest $request)
{
$article = $request->all();
Article::create($article);
$categoriesId = $request->input('categories');
$article->categories()->attach($categoriesId);
return redirect()->route('articles_path');
}
The 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'
]
]);
Article Model:
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');
}
Category Model
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();
});
from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1PRSLVm
via IFTTT
Aucun commentaire:
Enregistrer un commentaire