传递给Illuminate \ Database \ Eloquent \ Relations \ HasOneOrMany :: save()的参数1必须是Illuminate \ Database \ Eloquent \ Model的一个实例

时间:2016-10-20 09:47:46

标签: laravel-5.2

我是Laravel的新手,我正在尝试添加帖子,由用户创建到数据库中。但是当我这样做时,会出现以下错误:

  

参数1传递给Illuminate \ Database \ Eloquent \ Relations \ HasOneOrMany :: save()   必须是一个   Illuminate \ Database \ Eloquent \ Model的实例,字符串给出,   在C:\ xampp \ htdocs \ lar \ app \ Http \ Controllers \ PostController.php中调用在线上
  25并定义

用户模型:

<?php

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()
    {
        return $this->hasMany('App\Post');
    }
}

发布模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    public function user()
    {
        return $this->belongsTo('App\User') ;
    }
}

PostController中:

<?php

namespace App\Http\Controllers;

use App\Post;
use Illuminate\Http\Request;

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

邮政路线:

Route::post('/createpost',[
    'uses' => 'PostController@postCreatePost',
    'as'=>'post.create'
]);

表格行动:

<form action="{{route('post.create')}}" method="post">

请告诉我如何解决这个问题..如何解决这个问题? 提前谢谢.. :))

1 个答案:

答案 0 :(得分:3)

我认为你想要的是:

<?php

namespace App\Http\Controllers;

use App\Post;
use Illuminate\Http\Request;

class postController extends Controller
{
    public function postCreatePost(Request $request){
        // Validation
        $post = new Post();

        // here you set the body of the post like that
        $post->body = $request->body;

        // here you pass the $post object not as string
        $request->user()->posts()->save($post);
        return redirect()->route('dashboard');
    }
}

您需要将$post对象作为对象传递给save方法。您正在执行此操作:$user->posts()->save('$post')当您需要执行此操作时:$user->posts()->save($post)

希望它有所帮助。