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
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.
because there is no error, i don't know what's wrong??
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());
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.
Related
I have a Laravel 8 setup that utilises Intertia.js. I'm trying to test my post routes to store new resources and want to assert that the database has the new record stored, using the assertDatabaseHas() method.
Controller.php
public function store(SlotCreate $request): RedirectResponse
{
$slot = CreateSlot::dispatchNow($request);
return redirect()->back()->with([
'message' => 'Slot Created Successfully.',
'slot' => new SlotResource($slot)
]);
}
CreateSlotTest.php
public function testCreateSlot()
{
$response = $this->actingAs($this->teamAdminOne)->post('/slots', [
'start_time' => '09:00',
'end_time' => '10:00',
'max_bookings' => 3
]);
$response->assertStatus(302);
$this->assertDatabaseHas('slots', [
'id' => ???
'team_id' => $this->teamAdminOne->currentTeam(),
'start_time' => '09:00',
'end_time' => '10:00',
'max_bookings' => 3
]);
}
When I debug the session I can see the slot that I added to the with() method but I can't figure out how to access it.
I'd like to know if I'm returning the slot correctly in the controller and if yes, how do I access the response to assert if the database has this record?
Actually when you call redirect()->with(), it adds the variables into the session by calling the session()->flush() method. So in this case you can retrieve the variables via Illuminate\Support\Facades\Session facade.
$slot = Illuminate\Support\Facades\Session::get('slot')
Good Afternoon,
I'm trying to create a Laravel factory where 2 of the 'columns' have the same values every time its called and the rest of the factory can be random.
For instance, I have the following columns in my DB
name
email
phone_number
status_message
status_code
I currently have my factory as follows;
$factory->define(Brand::class, function (Faker $faker) {
return [
'name' => $faker->unique()->company,
'email' => $faker->companyEmail,
'phone_number' => $faker->phoneNumber
];
});
This part works perfectly, as it should, the problem is that each specific status message comes with an individual status code. Is there a way I could add an array of status messages with a status code and have the factory pick a set at random for that record?
The status code / messages are listed below in array format;
[
'3e2s' => 'tangled web',
'29d7' => 'get certified',
'2r5g' => 'art of war',
]
I hope this makes sense. any help would be greatly appreciated.
as i can understand u need to pick random from this array u mentioned in above
$factory->define(Brand::class, function (Faker $faker) {
$data = [
'3e2s' => 'tangled web',
'29d7' => 'get certified',
'2r5g' => 'art of war',
];
$statusCode = array_rand($data);
$statusMessage = $data[$statusCode];
return [
'name' => $faker->unique()->company,
'email' => $faker->companyEmail,
'phone_number' => $faker->phoneNumber,
'status_message' => $statusMessage,
'status_code' => $statusCode,
];
});
I am trying to access json in a nested array but it is not working yet.
I am developing in laravel an have this
public function rave(Request $request){
$vars = [
'id' => Request::get('id'),
'txref' => Request::get('txRef'),
'flwref' => Request::get('flwRef'),
'created_at' => Request::get('createdAt'),
'amount' => Request::get('amount'),
'status' => Request::get('status'),
'name' => Request::get('fullName'),
'email' => Request::get('customer'),
];
I am able to get and display all in view but name and email which comes back in the response as
"customer":{
"id":15672,
"phone":"7667866 ",
"fullName":"john doe ",
"customertoken":null,
"email":"kely#gmail.com",
"createdAt":"2019-06-09T08:28:56.000Z",
"updatedAt":"2019-06-09T08:28:56.000Z",
"deletedAt":null,
"AccountId":33519
},
How do I access the data under customer because this
'name' => Request::get('fullName'),
'email' => Request::get('customer'),
doesn't seem to work like the others
You use Request $request as function parameter,
and check output of
echo $request->input('customer.fullName');
echo $request->input('customer.email');
Here is my code :
$user = \App\User::where('id', $uid)->firstOrFail();
$user->token()->updateOrCreate(['user_id' => $uid, 'type' => $type], [
'auth' => $auth_token,
'refresh' => $refresh_token,
'type' => $type
]);
I've got two models User and Token with an 'one to one' relationship.
On the first line, I try to catch a User into the database, then I update my model with the updateOrCreate() method.
However, as you can read it, I must use a selector 'user_id' => $uid before to successfully update my model. I think Eloquent should be able to manage it in a different way without making two requests.
You don't have to use the user_id => $uid on that query. It's injected based on the relationship already. You can rewrite that to:
$token = \App\User::where('id', $uid)->firstOrFail()->token()->updateOrCreate(['type' => $type], [
'auth' => $auth_token,
'refresh' => $refresh_token,
'type' => $type
]);
I'm using Gazzle 6 with Laravel 5.1 and I'm having a strange behaviour returning my data from the APIs I'm using. This is my code:
$data = array(
'id' => '112233'
);
$from = \Carbon\Carbon::now()->subDays(1)->format('d/m/Y');
$to = \Carbon\Carbon::now()->subMonths(1)->format('d/m/Y');
$first_report = $this->client->post('https://my.service.com/reporting/execute/', [
'auth' => ['myemail#email.com', 'mypassword'],
'form_params' => ['data' => json_encode($data)]
]);
$second_report = $this->client->get('mysecondservice.com/reports', [
'query' => [
'account_auth_token' => '000011122223333444455556667778889999',
'start_date' => $to,
'end_date' => $from
]
]);
return array(
'first_report' => $first_report,
'second_report' => $second_report
);
If I return the data as an array like the previous one the first_report and second_report are empty. But if I return only for example
return $first_report;
or
return $second_report;
The data is returned correctly for each report but I don't know what is the issue there, because I have tried with: json_encode or even return $response()->json... but still not working.
Do you have any idea about what's going on?
I think you need to run the send() function on the object you have to get the response, then run getBody() on that to get the response object, then run getContents() on that to get the contents of the response as a string. So in total it would look like
$first_report = $this->client->post('https://my.service.com/reporting/execute/', [
'auth' => ['myemail#email.com', 'mypassword'],
'form_params' => ['data' => json_encode($data)]
])->send()->getBody()->getContents();
$second_report = $this->client->get('mysecondservice.com/reports', [
'query' => [
'account_auth_token' => '000011122223333444455556667778889999',
'start_date' => $to,
'end_date' => $from
]
])->send()->getBody()->getContents();
I find the Guzzle documentation does not match up with the actual methods I use to get the results. Not sure if it's out of date or if I'm doing it wrong, but this method works for me.