在非对象

时间:2016-04-16 08:43:29

标签: laravel laravel-5.1

我正在构建一个小级的laravel应用程序。我在代码中遇到错误,我无法解决。 这是代码

发布模型

namespace App;

use Illuminate\Database\Eloquent\Model;

class post extends Model
{
    public function user()
    {
      return $this->belongsTo('app\user');
    }
}

用户模型

namespace App;

use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;


class user extends Model implements Authenticatable
{
  use \Illuminate\Auth\Authenticatable;
  public function posts()
  {
    $this->hasMany('app\post');
  }
}

PostController中

namespace App\Http\Controllers;
use App\post;
use Illuminate\Http\Request;

class postcontroller extends Controller{
  public function postCreatePost(Request $request){
    $post = new post();
    $post->body = $request['body'];
    $request->user()->posts()->save($post);
    return redirect()->route('dashboard');
  }
}

提前感谢您尝试解决此问题。

2 个答案:

答案 0 :(得分:4)

确保在您的用户模型中恢复关系。

class user extends Model implements Authenticatable
{
   use \Illuminate\Auth\Authenticatable;
   public function posts()
   {
       return $this->hasMany('app\post');
   }
}

您发布的代码在return函数中没有posts

答案 1 :(得分:1)

我认为这应该解决

将您的表字段添加到受保护的$ fillable = []数组

用户

namespace App;

use Illuminate\Database\Eloquent\Model;

class post extends Model
{
    protected $fillable = ['body'];

    public function user()
    {
      return $this->belongsTo('app\user');
    }
}

namespace App;

use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;


class user extends Model implements Authenticatable
{

  use \Illuminate\Auth\Authenticatable;

  protected $fillable = ['username', 'field2', 'blabla'];

  public function posts()
  {
    return $this->hasMany('app\post');
  }
}

PostController中

namespace App\Http\Controllers;
use App\post;
use Illuminate\Http\Request;

class postcontroller extends Controller{
  public function postCreatePost(Request $request){
    $post = new post(['body' => $request->body]);
    $request->user->posts()->save($post);
    return redirect()->route('dashboard');
  }
}