You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

0 D铆as
5 Hrs
19 Min
52 Seg

Consulta de datos: rutas y controladores

6/30
Resources

How to configure controllers and routes in Laravel for an API?

To build an efficient and well-organized API in Laravel, it is essential to understand how to configure both controllers and routes. This process is essential to properly manage queries to our database. Below, we show you how to do it step by step.

How to create an API controller in Laravel?

We start by creating specific controllers for our API in Laravel, which helps to segment and organize the code in a professional way. Here's how to do it:

  1. Open the terminal in VS Code: this will allow you to execute Artisan commands.
  2. Create the controller using Artisan:
    php artisan make:controller API/CategoryController
    • This command creates an API folder and inside it CategoryController.
  3. Repeat the process for other controllers:
    • Create controllers for recipes and labels following the same steps.
    php artisan make:controller API/RecipeControllerphp artisanmake:controller API/TagController

How to configure routes for an API in Laravel?

Once the controllers are ready, it's time to configure the routes so that our APIs can be accessed correctly.

  1. Access the API routes file: Navigate to the API-specific routes file(routes/api.php).

  2. Configure routes using HTTP methods:

    • For example, to get all categories:
    Route::get('categories', [CategoryController::class, 'index']);
    • To get a specific category:
    Route::get('categories/{category}', [CategoryController::class, 'show']);
  3. Import required controllers: Make sure to import correctly the controllers using use.

How to check the routing configuration?

It is important to check that our routes are configured correctly. You can do this directly from the terminal with an Artisan command.

  1. Run command in terminal:
    php artisan route:list --path=api
    • This command shows all the routes configured for the API.

How to work with drivers to manage queries?

The controllers are the core that allows you to perform database queries:

  1. Index method to get all categories:

    • In CategoryController, define the index method:
    public function index() { return Category::all();}
  2. Show method for a specific category:

    public function show(Category $category) { return $category;}
  3. Do the same for recipes and tags:

    • Modify the corresponding controllers to work with Recipe and Tag.

How to test Laravel APIs.

To ensure that the endpoints work correctly, it is advisable to use professional tools:

  1. Use Postman:
    • Send requests: Configure the endpoint in Postman to send GET requests to your API.
    • Verify responses: Check that the responses are correct and reflect the data structure you expect.

Why use Postman?

Postman is essential for evaluating APIs because:

  • Saves your query history.
  • Displays the status of the response immediately.
  • It makes it easy to handle different HTTP methods and resources in an orderly fashion.

Performing these basic configurations and tests is crucial to ensure that your Laravel API is running efficiently and neatly, allowing interactions with the database to be fast and clear. Continue to explore and improve your Laravel skills to build robust and scalable web applications.

Contributions 9

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?

En caso de que no les aparezca el archivo api.php, deben instalar la api en laravel con el siguiente comando: ```js php artisan install:api ```Esto instala sanctum, a帽adiendo el crsf-token y el archivo api.php en la carpeta de rutas (routes)
Es buena practica tambien asignar una versi贸n para la api para que cuando haya una nueva versi贸n, tus usuarios puedan seguir utilizando la vieja mientras aprenden a usar la nueva, esto se puede hacer de varias maneras, pero en este caso yo utilice el metodo **prefix** . Ademas podemos hacer uso de apiResource que nos trae los 5 metodos de una api(index, store, show, update, destroy ) y si lo queremos podemos trabajar solo con algunos con el metodo **only.** Ahora bien, si tenemos varias rutas que tienen una configuraci贸n en com煤n podemos hacer grupos. En este caso todas van a pertenecer a la version 1 y probablemente mas adelante le agreguemos un middleware de autenticaci贸n. Esto lo logramos con el metodo **group.** Dejo mi codigo de ejemplo ```js Route::prefix("V1")->groups(function () { Route::apiResource("categories", CategoryController::class)->only(["index", "show"]); Route::apiResource("recipes", RecipeController::class)->only(["index", "show"]); Route::apiResource("tags", TagController::class)->only(["index", "show"]); }); ```
Si trabajas con Vs Code puedes utilizar **RapidApi o ThunderClient** para hacer las pruebas de la api. Trabajan muy parecido a Postman.
como hacen para que se cree ese archivo api que tiene las rutas?, yo lo cree de manera manual y no funciona el codigo en ese archivo
![](https://static.platzi.com/media/user_upload/clase_6-d7508eaa-9bd2-4009-b66b-dd3594f62f44.jpg)
Hola. Tengo el error que se muestra en pantalla: ![](https://i.imgur.com/IzTUQc9.png)```js 驴Qu茅 puedo hacer al respecto? ```
Este curso deber铆a tener m谩s aportes. Vengo de los cursos de express y estoy entendiendo como se organiza una API
Si quieres ocultar los datos de registros creado y actualizado de tu respuesta ajusta tu modelo X `use HasFactory, SoftDeletes;` `protected $hidden = ['created_at','updated_at'];` aunque basta con: `use HasFactory;` `protected $hidden = ['created_at','updated_at'];`

la aplicacion mucho se lagea, deberian arreglar eso, hace que uno se pierda en los avances