Search code examples
phpvue.jslumen

Lumen: The new record with default values was added to database


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:

enter image description here

enter image description here

Debug session on server side - $request value:

enter image description here

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.


Solution

  • Your problem is that you are changing what the content type of your request is. Do not write headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, as axios sends this as 'Content-Type': 'application/json', so when it arrives to Lumen, it "decodes" it correctly and you can do $request->all() and get any data you want. You don't even have to write any content-type header, it is all automatically done by axios in this case.

    So your javascript code should be like:

    async createPerson() {
      await axios.post('/api/persons/', {
        firstName: 'Edward',
        lastName: 'Edwardson',
        address: 'Address8'
      })
    },