Hi,
I made a JSON API with laravel. and I'm trying to test it with POSTMAN before continuing to build a front end for it.
My API is a NewsDashboard backend that does the CRUD functions.
Here are the routes:
Route::get('/news', 'App\Http\Controllers\NewsController@index')->name('news.index');
Route::get('/news/{newsItem}', 'App\Http\Controllers\NewsController@show')->name('news.show');
Route::post('/news', 'App\Http\Controllers\NewsController@store')->name('news.store');
Route::patch('/news/{newsItem}', 'App\Http\Controllers\NewsController@update')->name('news.update');
Route::delete('/news/{newsItem}', 'App\Http\Controllers\NewsController@destroy')->name('news.destroy');
Route::get('/news/create', 'App\Http\Controllers\NewsController@create')->name('news.create');
Route::get('/news/{newsItem}/edit', 'App\Http\Controllers\NewsController@edit')->name('news.edit');
The /news showing me and empty array [] , because the DB is empty for now. the postman GET is returning 200 OK too. I tried to post JSON payload using postman :
{
"title": "Example News Item",
"content": "This is the content of the news item.",
"category_id": 1,
"tags": [1, 2, 3]
}
At first I get the error 419 unknown status ; then I moved my routes from web.php to api.php and the index is /api/news instead of /news.
So I'm testing /api/news
GET http://127.0.0.1:8000/api/news/ returns 200 OK
but
POST http://127.0.0.1:8000/api/news/ returns 405 Method Not Allowed
why is this? is there something wrong with my code?
Here is the store() method in the newscontroller:
public function store(Request $request)
{
$request->validate([
'title' => 'required',
'body' => 'required',
'category_id' => 'nullable|exists:categories,id',
'tags' => 'array',
'tags.*' => 'exists:tags,id'
]);
$newsItem = new NewsItem;
$newsItem->title = $request->title;
$newsItem->body = $request->body;
$newsItem->category_id = $request->category_id;
$newsItem->url = $request->url;
$newsItem->save();
$newsItem->tags()->attach($request->tags);
return response()->json($newsItem, 201);
}
If I remove the validation I get the error 500 instead with the body:
500Internal Server Error Integrity constraint violation: 1048 Column 'title' cannot be null (SQL: insert into `news_items` (`title`, `body`, `category_id`, `url`, `updated_at`, `created_at`) values (?, ?, ?, ?, 2022-12-31 14:52:26, 2022-12-31 14:52:26))
But the thing is that my payload contains the required fields.
I don't know where the problem is originating, somehow the payload is not going to the database.
- I can post new items directly from database and the App\Model is working fine too because I can post with laravel tinker and save it. But I cannot post using the postman.