📜  Laravel Crud(1)

📅  最后修改于: 2023-12-03 15:17:12.370000             🧑  作者: Mango

Laravel CRUD

Laravel is a popular PHP framework used to build web applications. It comes with a set of powerful features that make it easy to create complex applications quickly. One of its most popular features is the ability to create CRUD operations.

CRUD stands for Create, Read, Update, and Delete, and represents the most common functions that you need to do with a database. Laravel makes it easy to perform these operations through built-in features and libraries.

In this article, we will explore how to implement CRUD operations using Laravel.

Requirements

Before we begin, we will need to have the following installed on our system:

  • PHP 7.2+
  • Composer
  • Laravel CLI
Setup

To get started, we can create a new Laravel application using the following command:

laravel new myapp

This will create a new Laravel application in a directory called myapp. Next, we can navigate to the directory and start the development server using the following commands:

cd myapp
php artisan serve

This will start the development server at http://localhost:8000. We can open this URL in a web browser to see the default Laravel welcome page.

Create

To create a new record in a database using Laravel, we can use the Model class. The Model class represents a database table and provides methods for interacting with the table.

Let's create a new model using the following command:

php artisan make:model Product -m

This will create a new Product model and a corresponding migration file. We can use the migration file to create the products table in the database.

Next, we can add the following fields to the products table using the migration file:

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

Now we can run the migration to create the products table in the database:

php artisan migrate

Next, let's create a new route that will display a form for creating a new product:

Route::get('/products/create', function () {
    return view('products.create');
});

We can create a new create.blade.php file in the resources/views/products directory containing the following HTML code:

<form method="post" action="/products">
    @csrf

    <div class="mb-3">
        <label for="name" class="form-label">Name</label>
        <input type="text" class="form-control" id="name" name="name">
    </div>

    <div class="mb-3">
        <label for="description" class="form-label">Description</label>
        <textarea class="form-control" id="description" name="description"></textarea>
    </div>

    <div class="mb-3">
        <label for="price" class="form-label">Price</label>
        <input type="number" class="form-control" id="price" name="price">
    </div>

    <button type="submit" class="btn btn-primary">Create</button>
</form>

This form contains input fields for the product name, description, and price. When the user submits the form, it will be sent to the /products route.

In the /products route, we can create a new product record using the create method of the Product model:

Route::post('/products', function () {
    $product = new \App\Models\Product();
    $product->name = request('name');
    $product->description = request('description');
    $product->price = request('price');
    $product->save();

    return redirect('/products');
});

This code creates a new Product model and sets its fields to the values submitted in the form. It then saves the model to the database and redirects the user to the /products route to see the list of products.

Read

To read records from a database using Laravel, we can use the Model class again. The Model class provides methods for retrieving records from the database.

Let's create a new route that will display a list of all products:

Route::get('/products', function () {
    $products = \App\Models\Product::all();
    return view('products.index', ['products' => $products]);
});

This code retrieves all product records from the database using the all method of the Product model. It then passes the $products variable to the index.blade.php file.

We can create a new index.blade.php file in the resources/views/products directory containing the following HTML code:

<table class="table">
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Description</th>
            <th>Price</th>
        </tr>
    </thead>
    <tbody>
        @foreach ($products as $product)
        <tr>
            <td>{{ $product->id }}</td>
            <td>{{ $product->name }}</td>
            <td>{{ $product->description }}</td>
            <td>{{ $product->price }}</td>
        </tr>
        @endforeach
    </tbody>
</table>

This code creates a table with the ID, name, description, and price fields of each product record. It uses the foreach loop to iterate over the $products variable passed from the controller.

Update

To update a record in a database using Laravel, we can use the Model class and the save method. The save method saves any changes made to a Model instance to the database.

Let's create a new route that will display a form for editing a product:

Route::get('/products/{product}/edit', function ($id) {
    $product = \App\Models\Product::find($id);
    return view('products.edit', ['product' => $product]);
});

This code retrieves a product record from the database using the find method of the Product model. It then passes the $product variable to the edit.blade.php file.

We can create a new edit.blade.php file in the resources/views/products directory containing the following HTML code:

<form method="post" action="/products/{{ $product->id }}">
    @csrf
    @method('PUT')

    <div class="mb-3">
        <label for="name" class="form-label">Name</label>
        <input type="text" class="form-control" id="name" name="name" value="{{ $product->name }}">
    </div>

    <div class="mb-3">
        <label for="description" class="form-label">Description</label>
        <textarea class="form-control" id="description" name="description">{{ $product->description }}</textarea>
    </div>

    <div class="mb-3">
        <label for="price" class="form-label">Price</label>
        <input type="number" class="form-control" id="price" name="price" value="{{ $product->price }}">
    </div>

    <button type="submit" class="btn btn-primary">Update</button>
</form>

This form is similar to the create form, but it has an additional hidden field that tells Laravel to use the PUT method when submitting the form.

In the /products/{product} route, we can update the product record using the save method:

Route::put('/products/{product}', function ($id) {
    $product = \App\Models\Product::find($id);
    $product->name = request('name');
    $product->description = request('description');
    $product->price = request('price');
    $product->save();

    return redirect('/products');
});

This code retrieves the product record from the database using the find method of the Product model. It then sets its fields to the values submitted in the form and saves the model to the database. It finally redirects the user to the /products route to see the updated list of products.

Delete

To delete a record from a database using Laravel, we can use the Model class and the delete method. The delete method deletes a Model instance from the database.

Let's create a new route that will delete a product record:

Route::delete('/products/{product}', function ($id) {
    $product = \App\Models\Product::find($id);
    $product->delete();

    return redirect('/products');
});

This code retrieves the product record from the database using the find method of the Product model. It then deletes the model using the delete method and redirects the user to the /products route to see the updated list of products.

We can add a delete button to the index.blade.php file to allow the user to delete a product:

@foreach ($products as $product)
<tr>
    <td>{{ $product->id }}</td>
    <td>{{ $product->name }}</td>
    <td>{{ $product->description }}</td>
    <td>{{ $product->price }}</td>
    <td>
        <form method="post" action="/products/{{ $product->id }}">
            @csrf
            @method('DELETE')

            <button type="submit" class="btn btn-danger">Delete</button>
        </form>
    </td>
</tr>
@endforeach

This code creates a delete button for each product record that submits a DELETE request to the /products/{product} route.

Conclusion

In this article, we explored how to implement CRUD operations using Laravel. We created a new model and migration, created, read, updated, and deleted records, and displayed a list of records. Laravel makes it easy to perform these operations through built-in features and libraries, and can help you create powerful web applications quickly.