Support the ongoing development of Laravel.io →
posted 10 years ago
Eloquent
Last updated 2 years ago.
0

This is my route where I'm trying to attach a category to a newly created News item.

Route::post('news', function(){
  $data = Input::only('title', 'body');
  $news = News::create($data);
  $category = Category::find(Input::get('tags')['id']);
  $news->noms()->save($category);
  $news->noms();
  return $category;
});

This is my Category model.

class Category extends \Eloquent {
  protected $table = 'categories';
  protected $fillable = array('title');    
  public function news()
  {
    return $this->morphedByMany('News', 'categoryable');
  }
}

This is my News model.

class News extends \Eloquent {
  protected $table = 'news';
  protected $softDelete = true;
  protected $fillable = array('title', 'body');    
  public function categories()
  {
    return $this->morphToMany('Category', 'categoryable');
  }
}

The error is pointing to this method in Eloquent model.php

public function morphToMany($related, $name, $table = null, $foreignKey = null, $otherKey = null, $inverse = false)
{
  $caller = $this->getBelongsToManyCaller();

  // First, we will need to determine the foreign key and "other key" for the
  // relationship. Once we have determined the keys we will make the query
  // instances, as well as the relationship instances we need for these.
  $foreignKey = $foreignKey ?: $name.'_id';

  $instance = new $related;

  $otherKey = $otherKey ?: $instance->getForeignKey();

  // Now we're ready to create a new query builder for this related model and
  // the relationship instances for this relation. This relations will set
  // appropriate query constraints then entirely manages the hydrations.
  $query = $instance->newQuery();

  $table = $table ?: str_plural($name);

  return new MorphToMany(
    $query, $this, $name, $table, $foreignKey,
    $otherKey, $caller, $inverse
  );
}

More specifically it's complaining that this method (morphToMany) doesn't know the class "Category" (my class), on this line.

$instance = new $related;

I've used composer dump-autoload in both my workbench dir and the root laravel dir, but it doesn't help.

Last updated 2 years ago.
0

Of course, when I finally create a form post I manage to solve it myself.

Adding the whole namespace in the models helped.

class News extends \Eloquent {
  protected $table = 'news';
  protected $softDelete = true;
  protected $fillable = array('title', 'body');    
  public function categories()
  {
    return $this->morphToMany('Wetcat\Board\Models\Category', 'categoryable');
  }
}
Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

agoransson agoransson Joined 24 Mar 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.