📅  最后修改于: 2023-12-03 15:32:33.133000             🧑  作者: Mango
Laravel is a powerful PHP framework for building web applications. One of the most common tasks in web development is creating a resource and then being able to retrieve that resource by its ID. In this tutorial, we will demonstrate how to create a resource in Laravel and then retrieve it by its ID.
Before we begin, make sure you have the following installed:
To create a resource in Laravel, we first need to create a migration. A migration is a way of defining the database schema for our resource.
Let's create a migration for a books
table. Each book will have an id
(which will be automatically generated), a title
, and an author
. Run the following command to create a migration:
php artisan make:migration create_books_table --create=books
This will create a new migration file in the database/migrations
directory.
Now, open the migration file and define the schema for the books
table:
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateBooksTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('books', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title');
$table->string('author');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('books');
}
}
This migration will create a books
table with the specified columns.
Next, we need to run the migration to create the books
table in the database. Run the following command:
php artisan migrate
At this point, we have created a resource in our database. Now, we need to be able to retrieve it.
In Laravel, we can retrieve a resource by its ID using a route parameter. Let's create a route to retrieve a book by its ID:
Route::get('/books/{id}', function ($id) {
$book = App\Book::find($id);
return $book;
});
This route will retrieve a book from the books
table by its ID and return it as a JSON response.
Now, if we navigate to http://localhost:8000/books/{id}
in our browser (replacing {id}
with an actual ID), we should see the book returned as JSON.
In this tutorial, we have demonstrated how to create a resource in Laravel and then retrieve it by its ID using a route parameter. In a real-world application, you would likely want to add more functionality, such as creating, updating, and deleting resources, but this tutorial should serve as a good starting point.