How to make a CRUD REST API with LARAVEL 10?
Published: 2024-04-10 14:17:49


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gl0up3p9dmokd1wru9xi.png)

---

Hey you! Im glad you're here.
Before we begin, I want to clarify that this tutorial covers the basics of creating a CRUD REST API with Laravel 10. While I'll do my best to explain the concepts and provide a step-by-step guide, I want to emphasize that I'm not an expert in the field. It's important to delve deeper into the topic and consult the official documentation for a comprehensive understanding. This article serves as a starting point, but it won't cover everything you need to know. With that said, let's get started!

[Laravel documentation](https://laravel.com/docs/10.x/readme) is pretty complete and clear about all the functionalities of the framework, and PHP has such a big community, where you can ask and help everyone.

I'm gonna make an Product CRUD.

Open your terminal and create your Model, Controller and Migration.

```
php artisan make:model Product

php artisan make:controller ProductController

php artisan make:migration create_products_table
```

2. Let's configure the Products table.
Imagine that our product has title, description and price.

```
public function up(): void
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('description');
            $table->float('price');
            $table->timestamps();
        });
    }
```


After that, you must "tell" your model that you can put values in these columns.
3. Go to your product model and put this line of code.

```
protected $fillable = [
        'title',
        'description',
        'price',
    ];
```

I guess you can realize that if you had an column called "color" you would have to add it in the array. This is how you say that these inputs are able to be fill.
4. Go to your product controller.
Here is where the magic happens before you write the routes.
Inside the class, let's make our first function. I'm gonna call it 'index'.

```
use App\Models\Product;

class ProductController extends Controller{

  public function index(){
  
          $products = Product::all();
  
          return response()->json([
              'Products: ' => $products,
          ]);
      }
}
```

_Let's understand what is going on here…_
4.1 Everytime you refer to something that is on another file, you have to _tell _your code where is it. This is why the line **use App\Models\Product;** exists.

4.2 The variable $products is receiving all products from your database. Remember that you were on its models file? There it is.

4.3 We are returning a json script with our products (you will see them just after store on database).

5. Create Store, Show, Update and Delete functions.

```
public function store(Request $request){

        $input = $request->validate([
            'title' => ['required'],
            'description' => ['required'],
            'price' => ['required'],
        ]);

        $product = Product::create($input);

        if ($product->save()){

            return response()->json([
                'Message: ' => 'Success!',
                'Product created: ' => $product
            ], 200);

        }else {

            return response([

                'Message: ' => 'We could not create a new product.',

            ], 500);
        }

    }
```
Now you can create new products!
See more about validation here and HTTP client here.

```
public function show(string $id){

        $product = Product::find($id);

        if ($product){

            return response()->json([
                'Message: ' => 'Product found.',
                'Product: ' => $product
            ], 200);

        }else {

            return response([

                'Message: ' => 'We could not find the product.',

            ], 500);
        }
```
Now you can find a product by the id.

```
public function update(Request $request, string $id){

        $product = Product::find($id);

        if($product){

           $input = $request->validate([
              'title' => ['required'],
              'description' => ['required'],
              'price' => ['required'],
            ]);

            $product->title = $input['title'];
            $product->description = $input['description'];
            $product->price = $input['price'];

            if($product->save()){

                return response()->json([

                    'Message: ' => 'Product updated with success.',
                    'Product: ' => $product

                ], 200);

            }else {

                return response([

                    'Message: ' => 'We could not update the product.',
    
                ], 500);

            }
        }else {

            return response([

                'Message: ' => 'We could not find the product.',

            ], 500);
        }

    }
```
Now you can update the informations of your product by the id.

```
public function destroy(string $id){

        $product = Product::find($id);

        if($product){

            $product->delete();

            return response()->json([

                'Message: ' => 'product deleted with success.',

            ], 200);

        }else {

            return response([
                
                'Message: ' => 'We could not find the product.',

            ], 500);
        }

    }
```
Now you can delete a product by the id.

6. Now you have to create the routes, or you will can not access your api and test your functions.
Go to api.php.

```
use App\Http\Controllers\ProductController;

Route::controller(ProductController::class)->group(function () {

    Route::get('products', 'index');
    Route::post('product/create', 'store');
    Route::put('product/update/{id}', 'update');
    Route::get('product/read/{id}', 'show');
    Route::delete('product/delete/{id}', 'destroy');

});
```

For me, using an group route is the best way of make a clean code, but of course you can do it without the group. Here you have to understand what is get, post, put and delete, or you'll be just copying and pasting code.
The route you created could be totally diferent, but we have to follow the patterns of the documentation.
Don't forget to pass the id to the route if you passed it to the function.

---

That's it! Run your migrations, start your server and enjoy it!
When I made my first REST API, I didn't knew how it really works or where to see what was happening, that's why I use Postman today. Search about it and i'm sure you are gonna understand.
[Follow me on GitHub!](https://github.com/constpereiradev)
[See my Linkedin!](https://www.linkedin.com/in/amanda-pereira-dev/)