Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() must be an instance of Illuminate\Database\Eloquent\Model

I am pretty new to Laravel and I am trying to add the post, create by a user into the database. But when I do so, following error comes:

Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() must be an instance of Illuminate\Database\Eloquent\Model, string given, called in C:\xampp\htdocs\lar\app\Http\Controllers\PostController.php on line
25 and defined

User model:

<?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');
    }
}

Post Model:

<?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');
    }
}

Post Route:

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

Form action:

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

Please tell me how to fix this.. How to fix this? Thank you in advance.. :)

Upvotes: 4

Views: 15055

Answers (1)

Luis Dalmolin
Luis Dalmolin

Reputation: 3486

I think what you want is this:

<?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');
    }
}

You need to pass the $post object as an object to the save method. You was doing this: $user->posts()->save('$post') when you need to do this: $user->posts()->save($post).

Hope it helps.

Upvotes: 4

Related Questions