Reputation: 49
i'm using Laravel Framework 5.7.25
i'm trying to create a post by current user who has already logged in.
but i'm facing these Errors:
Call to a member function save() on null this is Error: this is my PostController :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
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');
}
}
and this is Post model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function user()
{
$this->belongsTo('App\User');
}
}
and this is 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()
{
$this->hasMany('App\Post');
}
}
Upvotes: 2
Views: 2330
Reputation: 180004
Your user()
and posts()
relationships aren't returning anything:
public function posts() {
$this->hasMany('App\Post');
}
needs to become:
public function posts() {
return $this->hasMany('App\Post');
}
and the same tweak made for user()
.
Upvotes: 6
Reputation: 3030
I would change your code slightly, this should work:
class PostController extends Controller
{
public function postCreatePost(Request $request)
{
$request->user()->posts()->create($request->only('body'));
return redirect()->route('dashboard');
}
}
Upvotes: 1