Nindakake operasi CRUD(Create, Read, Update, Delete) ing a Laravel RESTful API minangka aspek penting kanggo mbangun aplikasi. Ing ngisor iki, aku bakal nuntun sampeyan saben operasi ing Laravel RESTful API aplikasi:
1. Create
Kanggo nambah rekaman anyar menyang database, sampeyan kudu nemtokake cara kanggo Controller nangani POST
panjalukan saka pangguna. Contone, kanggo create pangguna anyar:
use App\Models\User;
use Illuminate\Http\Request;
public function store(Request $request)
{
$user = User::create($request->all());
return response()->json($user, 201);
}
2. Read
Kanggo njupuk informasi saka database, sampeyan bisa nemtokake cara ing Controller kanggo nangani GET
panjalukan saka kedhaftar. Contone, kanggo njupuk dhaptar pangguna:
use App\Models\User;
public function index()
{
$users = User::all();
return response()->json($users);
}
3. Update
Kanggo update informasi rekaman sing wis ana, sampeyan kudu nemtokake cara kanggo Controller nangani PUT
panjalukan saka pangguna. Contone, kanggo update informasi pangguna:
use App\Models\User;
use Illuminate\Http\Request;
public function update(Request $request, $id)
{
$user = User::findOrFail($id);
$user->update($request->all());
return response()->json($user, 200);
}
4. Delete
Kanggo mbusak rekaman saka database, sampeyan bisa nemtokake cara kanggo Controller nangani DELETE
panjalukan saka pangguna. Contone, kanggo delete pangguna:
use App\Models\User;
public function destroy($id)
{
$user = User::findOrFail($id);
$user->delete();
return response()->json(null, 204);
}
Elinga yen sampeyan kudu mesthekake yen sampeyan wis nyiyapake rute sing cocog ing file routes/api.php
kanggo nyambung menyang metode ing file Controller.
Kanthi instruksi kasebut, sampeyan saiki bisa nindakake operasi CRUD ing Laravel RESTful API aplikasi sampeyan.