简体   繁体   中英

Why am I getting a 500 error even though post request's being sent to DB successfully?

I've come across a very strange error in my console where even though I submit data successfully in the database, I get a 500 error that says:

POST http://127.0.0.1:8000/posts 500 (Internal Server Error) .

This making is sense is beyond me as it just seems illogical.

What am I doing wrong?

Here's the post controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post;

class PostController extends Controller
{
    public function create(Request $request, Post $post) {
        // create post
        $createdPost = $request->user()->posts()->create([
            'body' => $request->body
        ]);

        // return response
        return response()->json($post->with('user')->find($createdPost->id));
    }
}

Here are routes:

<?php

Auth::routes();

Route::group(['middleware' => ['auth']], function () {
    Route::get('/', 'TimelineController@index');
    Route::post('/posts', 'PostController@create');
});

I think the error is located in your response line. You are calling the find() method in an single model object instead of a Model class , a Collection object or a Relationship object . Check the signalled line:

class PostController extends Controller
{
    public function create(Request $request, Post $post) {

        // ...

        return response()->json($post->with('user')->find($createdPost->id)); // <----
    }
}

Try this instead:

        return response()->json(Post::with('user')->find($createdPost->id));
        // or even easier:
        return response()->json($createdPost->load('user'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM