I'm trying to build an authentication endpoint where a user's key is returned when they are authenticated using Laravel 5.6
.
When testing on Postman
using localhost:8000
, I find that it accepts the request but fails to output anything. please click here to see the image .
Take a look at the AuthController
below:
<?php
namespace App\Http\Controllers\Api;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;
use Hash;
class AuthController extends Controller
{
public function register(Request $request)
{
$request->validate([
'email' => 'required',
'name' => 'required',
'password' => 'required'
]);
$user = User::firstOrNew(['email' => $request->email]);
$user->name = $request->name;
$user->email = $request->email;
$user->password = bcrypt($request->password);
$user->save();
$http = new Client;
$response = $http->post(url('oauth/token'), [
'form_params' => [
'grant_type' => 'password',
'client_id' => '2',
'client_secret' =>'5G7yDJFNDsqzVNSJU85ff8DWW6EiKFLGXDDmMmt9',
'username' => $request->email,
'password' => $request->password,
'scope' => '',
],
]);
return response(['data'=>json_decode((string)$response->getBody(),true)]);
}
public function login(Request $request)
{
$request->validate([
'email' => 'required',
'password' => 'required'
]);
$user = User::where('email', $request->email)->first();
if (!$user) {
return response(['status' => 'error', 'message' => 'user not found']);
}
if (Hash::check($request->password, $user->password)) {
$http = new Client;
$response = $http->post(url('oauth/token'), [
'form_params' => [
'grant_type' => 'password',
'client_id' => '2',
'client_secret' => 'JhzSRlU6dnJxI1vb8MpWWksjaOo3AdyuL3Mm6ANf',
'username' => $request->email,
'password' => $request->password,
'scope' => '',
],
]);
}
}
}
this is the code of user model
<?php
namespace App;
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
this is the code of api
<?php
use Illuminate\Http\Request;
Route::post('/register', 'Api\AuthController@register');
Route::post('/login', 'Api\AuthController@login');
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
The first thing in here is that, you may change your postman request as follows,
Most importantly check your port is correct that the laravel server is running. Default port is port 8000. Then your url should formed as
http://localhost:8000/api/register (note that this url is only an example format)
Try to make above changes and give us what you've got. Think this may help.
Thanks