drxgfxlara's avatar

Need help passing a variable to the Store function request

I previously simplified the posts request below to a shorter and cleaner code in my opinion which is also show below.

        $post = new Posts;
        $post->title = $request->input('title');
        $post->body = $request->input('body');
        $post->user_id = auth()->user()->id;
        $post->save();
       auth()->user()->publish(
            new Posts(request(['title', 'body', 'user_id']))
        );

I added the ability to upload file images and the cover_img table needs to be equal to a variable but I don't know how to include it in the 'simplified' code request. I tried to add a comma and put 'cover_img' but that didn't seem to work very well.

        $post = new Posts;
        $post->title = $request->input('title');
        $post->body = $request->input('body');
        $post->user_id = auth()->user()->id;
        $post->cover_img = $fileNameToStore;  // new variable added
        $post->save();
       auth()->user()->publish(
            new Posts(request(['title', 'body', 'user_id'])) // not sure how to add $fileNameToStore to this request... any thoughts?
        );
0 likes
2 replies
Snapey's avatar
Snapey
Best Answer
Level 122

It could be a case of simplified is not necessarily better, or clearer.

auth()->user()->publish(
            new Posts(
            array_merge(
                request(['title', 'body', 'user_id']),
                ['cover_img'=>$filenameToStore]
            )
        );

Personally,

    $post = new Post([
        'title' => $request->title,
        'body' => $request->body,
        'cover_img' => $filenameToStore
    ]);

    auth()->user()->publish($post);

1 like
drxgfxlara's avatar

agreed, still working out the kinks. Actually do kind of prefer your method of writing it. Seems easier to read and understand what's going on.

Thanks Snapey

1 like

Please or to participate in this conversation.