Search code examples
jsonlaravelapiforeign-keysresponse

laravel 8 API : how return user_id in store method with authentication?


i'm building an API with laravel 8 ,

i have a Post table that has this columns :

id category_id user_id title body picture study_time likes tags

i want when a user that has admin or author level, and logged in admin panel , can add a post and in form , i show his/her username and i don't want they changed this field(user_id).

and i don't know is it possible return it with JSON response or not?

how can i do that ??

my PostController :

public function store(Request $request )
    {
        $data = $request->all();

        $validator = Validator::make($data, [
            'category_id'=>'required',
            'title' => 'required|max:100|unique:categories',
            'body'=>'required',
            'picture'=>'required',
            'study_time'=>'required',
            'likes'=>'required',
            'tags'=>'null|string',
        ]);

        if ($validator->fails()) {
            return response(['error' => $validator->errors(), 'Validation Error']);
        }

        $tags = explode(",", $request->tags);


        $post = Post::create($data);
        $post->tag($tags);

        return response()->json([
        'data' => $post,
        'message' => 'xxx'
        ], 201);


    }


Solution

  • return response()->json([
        'data' => $post,
        'message' => 'xxx'
    ], 201);