Difference between revisions of "Laravel API"
Jump to navigation
Jump to search
Line 37: | Line 37: | ||
php artisan make:controller API/APIController | php artisan make:controller API/APIController | ||
− | + | Pada routes/api.php, tambahkan (misal untuk register) | |
− | Route::namespace('App\Http\Controllers')->group(function(){ | + | Route::namespace('App\Http\Controllers\API')->group(function(){ |
− | Route::post('register-user','APIController@registerUser') | + | Route::post('register-user','APIController@registerUser'); |
}); | }); | ||
− | + | Pada APIController.php ditambahkan | |
+ | public function registerUser(Request $request){ | ||
+ | if($request->isMethod('post')){ | ||
+ | $data = $request->input(); | ||
+ | //echo "<pre>"; print_r($data); die; | ||
+ | |||
+ | $user = new User; | ||
+ | $user->name = $data['name']; | ||
+ | $user->email = $data['email']; | ||
+ | $user->password = bcrypt($data['password']); | ||
+ | $user->status = 1; | ||
+ | $user->save(); | ||
+ | } | ||
+ | } | ||
====Referensi==== | ====Referensi==== | ||
* https://www.youtube.com/@StackDevelopers | * https://www.youtube.com/@StackDevelopers |
Revision as of 07:54, 26 March 2023
Kasus ini adalah untuk menampilkan users
Konfigurasi awal
Edit .env, pastikan konfigurasi database sesuai.
Untuk data dummy bisa gunakan yang sudah disediakan oleh laravel
php artisan migrate
Konfigurasi API
GET Data
Buat file API (misal APIController) di app/Http/Controllers/
php artisan make:controller APIController
Edit file /routes/api.php. Untuk GET, tambahkan pada baris akhir
Route::get('users','App\Http\Controllers\APIController@getUsers');
Pada APIController.php tambahkan
use App\Models\User;
Untuk GET dapat menambahkan fungsi
public function getUsers(){ $getUsers = User::get(); //return $getUsers; return response()->json(["users"=>$getUsers],200); }
REST
Buat file API (misal APIController) di app/Http/Controllers/API
php artisan make:controller API/APIController
Pada routes/api.php, tambahkan (misal untuk register)
Route::namespace('App\Http\Controllers\API')->group(function(){ Route::post('register-user','APIController@registerUser'); });
Pada APIController.php ditambahkan
public function registerUser(Request $request){ if($request->isMethod('post')){ $data = $request->input();
//echo "
"; print_r($data); die; $user = new User; $user->name = $data['name']; $user->email = $data['email']; $user->password = bcrypt($data['password']); $user->status = 1; $user->save(); } }Referensi
* https://www.youtube.com/@StackDevelopers