Laravel 5.4.9 API Route Fix
Quick Fix on Laravel 5.4.9 on API Route
Update Migration, Model Factory and User
model as per above.
Run php artisan tinker
and create new user:
Psy Shell v0.8.1 (PHP 7.0.8 — cli) by Justin Hileman
>>> factory(App\User::class)->create();
=> App\User {#695
name: "Dr. Dewitt Rippin III",
email: "chaya.gerlach@example.org",
api_token: "z0DANKhTH7H4mIBPIZL1qyqQ3qJjmz9r3A4XOwqFRtrGyjM8XyM9ppqou0Lj",
updated_at: "2017-02-07 04:00:31",
created_at: "2017-02-07 04:00:31",
id: 1,
}
>>>
Now in Postman, use header Authorization
, value is Bearer [api_token]
. Then submit to http://localhost:8000/api/user
.
You should get current user logged in.
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password', 'api_token',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
<?php
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/
/** @var \Illuminate\Database\Eloquent\Factory $factory */
$factory->define(App\User::class, function (Faker\Generator $faker) {
static $password;
return [
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'api_token' => str_random(60),
'password' => $password ?: $password = bcrypt('secret'),
'remember_token' => str_random(10),
];
});
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->char('api_token', 60)->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}