I'm currently building a laravel 5.4 powered page to manage users. I've done all basic pages such as home, login, register, dashboard using blade templating engine. Now I'm building the User Management page. I've successfully implemented VueJS for this particular page. All components are working perfectly.
Now the problem I'm facing now is using Axios to get logged in user data from API route. At first I'm using usual api route to get auth()->user() data but it doesn't work.
I've learned that I must use Laravel Passport to do this API operation.
These are the steps I made after that:
- composer require laravel/passport
- php artisan migrate
- php artisan passport:install
- Added the Laravel\Passport\HasApiTokens trait to your App\User model
- Called the Passport::routes method within the boot method of your AuthServiceProvider
- Set the driver option of the api authentication guard to passport
- Added the CreateFreshApiToken middleware to your web middleware group
- Edited bootstrap.js file like the following :
window.axios.defaults.headers.common = { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'), 'X-Requested-With': 'XMLHttpRequest' };
- Axios Code :
axios.post('/api/getmydata', { params: { type: 'raw' } }) .then((response) => { console.log(response); }).catch((error) => { console.log(error); });
- Changed route (api.php) :
Route::group(['middleware' => 'api'], function(){ Route::post('getmydata', 'ApiController@test'); });
- Added function inside ApiController :
public function test() { $user = Auth::user(); return $user; }
- The problem here is axios somehow return error: Unauthenticated
Is there anything wrong with my code? Or is there any other way of achieving this? Thank you
'middleware' => 'api'
insideapi.php
its automatically done by laravel – Niklesh RautAuth::user()
will not work viaapi.php
its sateless – Niklesh Raut<meta name="csrf-token" content="{{ csrf_token() }}">
– Joe