I'm new to PHP and I've tried to make the small test full-stack project. I have Vue.js app on the client (frontend) and PHP (Lumen) on the server (backend). The code looks as following:
Client:
Vue component:
async createPerson() {
const optionAxios = {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}
try {
await axios.post(`http://localhost:8000/api/persons/`, {
firstName: 'Edward',
lastName: 'Edwardson',
address: 'Address8'
}, optionAxios)
} catch (error) {
console.log(error)
}
},
Server:
Router:
$router->group(['prefix' => 'api'], function () use ($router) {
$router->post('persons', ['uses' => 'PersonController@create']);
});
Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Person extends Model
{
protected $connection = 'mysql';
protected $table = 'person';
protected $primaryKey = 'id';
public $incrementing = true;
public $timestamps = false;
protected $fillable = [
'firstName', 'lastName', 'address'
];
protected $hidden = [];
}
Controller:
<?php
namespace App\Http\Controllers;
use App\Person;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class PersonController extends Controller
{
public function __construct() {
header("Access-Control-Allow-Origin: *");
}
public function create(Request $request)
{
$person = Person::create($request->all());
error_log($person);
return response()->json($person, 201);
}
}
Database:
Debug session on server side - $request value:
The issue is the new record was added to database, but with default values that I set on database level. I'm not sure why the object I've passed on the client is not added.
{
firstName: 'Edward',
lastName: 'Edwardson',
address: 'Address8'
}
And the last thing - it works if I use Postman. But, as you can see, it doesn't work with Axios.