I have two tables: users and posts. I made relation between these two tables. When I try to save, the post created by the user to posts to a table. It does not pass the user's id. Please check the below code:
User Model ( App\User.php )
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable;
class User extends Model implements Authenticatable
{
use \Illuminate\Auth\Authenticatable;
public function posts()
{
$this->hasMany('App\Post');
}
}
Post Model ( App\Post.php )
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function user()
{
$this->belongsTo('App\User');
}
}
Post Controller ( App\Http\Controllers\PostController.php )
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Post;
class PostController extends Controller
{
public function postCreatePost(Request $request)
{
//validation here will come
$post = new Post();
$post->body = $request['body'];
$request->user()->posts()->save();
return redirect()->route('dashboard');
}
}
Errors