Ricky Reza Muhammad
Ricky Reza Muhammad

Reputation: 373

There is nothing happening when store data for Laravel API

I making laravel API where i can store a new data where the value in body raw json. but when i try to send request using post, i got nothing but the status is 200 OK. when i chek my mysql there is no data inputed. So, what should i do?

mysql data

enter image description here

Laravel Controller, and API,

// function in controller
use App\Models\ChartAge;
class ChartController extends Controller
{
   public function saveChart(Request $request)
   {
    $data = $request->validate([
        'entity' => 'required|string|max:10',
        'code' => 'required|string|max:10',
        'year' => 'required|int|max:10',
        'under_age_15' => 'required|string|max:50',
        'age_15_64' => 'required|string|max:50',
        'age_65_over' => 'required|string|max:50',
    ]);

    $values = ChartAge::create($request);

    return response()->json(
        [
            'status' => true,
            'message' => "the videos has been favorites",
            'data' => $values,
        ],
        201
    );
   }
}
//in api.php
Route::post("charts", [ChartController::class, 'saveChart']);

and here is when i tried to send request using postman.

enter image description here

because there is no error, i don't know what's wrong??

Upvotes: 1

Views: 448

Answers (2)

Rajen Trivedi
Rajen Trivedi

Reputation: 1302

First double check your ChartAge model, does it have $fillable or not?

and Edit your code:

From

$values = ChartAge::create($request);

To:

$values = ChartAge::create($request->all());

Hope this will be useful.

With validation:

$data = \Validator::make($request->all(),[
    'entity' => 'required|string|max:10',
    'code' => 'required|string|max:10',
    'year' => 'required|int|max:10',
    'under_age_15' => 'required|string|max:50',
    'age_15_64' => 'required|string|max:50',
    'age_65_over' => 'required|string|max:50',
]);

if($data-> fails()){
  return back()->withErrors($data)->withInput();
}

$values = ChartAge::create($request->all());

Upvotes: 2

Alexandr Blyakher
Alexandr Blyakher

Reputation: 180

Do you set fillable fields in your 'ChartAge' model? protected $fillable = ['entity','code','year'...]; Do you try to test code with disabling validation? Please try to put dd($request) in the first row of the controller code.

Method create expects a plain PHP array, not a Request object.

Upvotes: 0

Related Questions