0

I have Post and User Model with relationship as follows: user_id is the foreign key in posts table referenced to the id of the users table

Post Model

public function user () {
  return $this->belongsTo(User::class,'user_id','id');
}

User Model

public function posts () {
  return $this->hasMany(Posts::class, 'user_id', 'id');
}

And a PostController with store method:

public function store(Request $request){
 $this->validate($request, [
  'title' => 'required|max:255',
  'desc' => 'required|max:255'
 ]);

 $image = null;
 $files = $request->thumbnail;
 $thumb = time().'.'.$files->getClientOriginalExtension();
 $request->thumbnail->move(public_path('public'),$thumb);
 $image = $thumb;
 $post = Posts::create([
   'title' => $request->title,
   'thumbnail' => $image,
   'user_id' => __________
   'desc' => $request->desc
 ]);
 return $post->toJson();                     }

Considering that, I want to acheive a relationship as: a user can have many posts. So, how can I get the id of the user with the help of relationship between users and posts table to insert in the posts table.
Edit: in above controller how can I get user_id value??

Sami Khan
  • 31
  • 1
  • 8

1 Answers1

0

it's very easy.

you can get id by url:

localhost:8000/users/{id}

In your route [web.php]

Route::get('/users/{id}', 'UserController@show');

Your Controller:

<?php

namespace App\Http\Controllers;


class UserController extends Controller
{
    public function show($id)
    {
        return User::with('posts')->where('id',$id)->get()
    }

Question Updated so answer must to update:

after login you should use below code:

You will access the authenticated user via the Auth facade:

// Get the currently authenticated user...
$user = Auth::user();

// Get the currently authenticated user's ID...
$id = Auth::id();

Dont forget the namespace

use Illuminate\Support\Facades\Auth;
Ali Sharifi Neyestani
  • 4,162
  • 1
  • 14
  • 22