After you require the package. You will automatically get access to the CrudController
which is a generic controller for doing CRUD (Create, Read, Update, and Delete)
actions.
This helper controller class has the following methods:
getAllRecords
: Gets all the records from the database (for a certain Model class)getRecordById
: Gets a specific single record from the database based on the specified idstoreRecord
: Creates a new record in the databaseupdateRecord
: Updates an existing record in the database based on the specified iddeleteRecord
: Delete an existing record from the database based on the specified idCreate a New Controller:
Extend the CrudController
for your specific model by creating a new controller class. For example, if you have a Post
model:
// app/Http/Controllers/PostController.php
namespace App\Http\Controllers;
use omarchouman\LaraUtilX\Http\Controllers\CrudController;
class PostController extends CrudController
{
public function __construct()
{
// Pass the model class to the parent constructor
parent::__construct(\App\Models\Post::class);
}
}
Routing: Define routes in your routes/web.php or routes/api.php file to map HTTP requests to the CRUD operations in your new controller:
// routes/web.php or routes/api.php
use App\Http\Controllers\PostController;
Route::get('/posts', [PostController::class, 'getAllRecords']);
Route::get('/posts/{id}', [PostController::class, 'getRecordById']);
Route::post('/posts', [PostController::class, 'storeRecord']);
Route::put('/posts/{id}', [PostController::class, 'updateRecord']);
Route::delete('/posts/{id}', [PostController::class, 'deleteRecord']);
Run Your Laravel Application: Start your Laravel development server:
php artisan serve
Make Requests: Use your preferred HTTP client (e.g., Postman, curl) or create a front-end interface to make requests to your CRUD endpoints. Below are examples using curl:
Get All Records:
curl http://localhost:8000/posts
Get Record by ID:
curl http://localhost:8000/posts/1
Store a Record:
curl -X POST -H "Content-Type: application/json" -d '{"title": "New Post", "content": "Lorem ipsum"}' http://localhost:8000/posts
Update a Record:
curl -X PUT -H "Content-Type: application/json" -d '{"title": "Updated Post", "content": "Updated content"}' http://localhost:8000/posts/1
Delete a Record:
curl -X DELETE http://localhost:8000/posts/1
Success Response:
For successful operations (e.g., fetching records, creating, updating, or deleting), the utility returns the corresponding model instance or HTTP status code 204 No Content for deletion.
Error Response:
If an operation encounters an error (e.g., record not found), the utility returns an appropriate error response.
This utility streamlines your CRUD operations, making your code cleaner and more maintainable. Customize it further based on your specific requirements and models.