如何使用Laravel進行CRUD(建立、讀取、更新和刪除)

如何使用Laravel進行CRUD(建立、讀取、更新和刪除)

在當今快節奏、不斷髮展的網路開發環境中,Laravel 是一種流行的 PHP 框架,用於構建現代、動態的網路應用程式。Laravel Eloquent 是它的核心功能之一,它是一個物件關係對映器 (ORM),能讓開發人員高效地在資料庫上執行建立、讀取、更新和刪除 (CRUD) 操作。

本教程演示瞭如何使用 Laravel 的 Eloquent ORM 在 Laravel 應用程式中執行這些操作,以及如何使用伺服器部署 Laravel CRUD 應用程式。

Laravel中的CRUD功能

CRUD 操作是任何資料庫驅動應用程式的支柱。它們允許您執行最基本、最重要的資料庫操作,如建立新記錄、讀取現有記錄、更新和刪除記錄。這些操作對於任何與資料庫互動的 Laravel 應用程式的功能都至關重要。

Eloquent 提供了一種簡單直觀的資料庫互動方式,減少了資料庫管理的複雜性,讓你可以專注於構建應用程式。它內建的方法和類可以讓你輕鬆地對資料庫中的記錄進行 CRUD。

前提條件

要學習本教程,請確保您具備以下條件:

步驟

  1. 安裝 Laravel 並建立新應用程式
  2. 建立資料庫
  3. 建立表格
  4. 建立控制器
  5. 設定模型
  6. 新增路由
  7. 生成 Blade 檔案
  8. 部署和測試 CRUD 應用程式

如需獲得指導,請檢視教程的完整程式碼

安裝Laravel並建立新應用程式

開啟要建立 Laravel 應用程式的終端,然後按照以下步驟操作。

  1. 要安裝 Laravel,請執行:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
composer global require laravel/installer
composer global require laravel/installer
composer global require laravel/installer
  1. 要建立一個新的 Laravel 應用程式,請執行:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
laravel new crudposts
laravel new crudposts
laravel new crudposts

建立資料庫

為應用程式建立新資料庫:

  1. 在 XAMPP 控制面板中啟動 Apache 和 MySQL 伺服器,並在瀏覽器中訪問 http://localhost/phpmyadmin
  1. 單擊左側邊欄上的 “New“,建立資料庫表單。您將看到以下內容:

建立資料庫表單

  1. 新增資料庫名稱,然後單擊 Create
  1. 編輯 Laravel 應用程式根目錄下的 .env 檔案。該檔案包含應用程式使用的所有環境變數。找到以 DB_ 為字首的變數,並用你的資料庫憑據編輯它們:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
DB_CONNECTION=
DB_HOST=
DB_PORT=
DB_DATABASE=
DB_USERNAME=
DB_PASSWORD=
DB_CONNECTION= DB_HOST= DB_PORT= DB_DATABASE= DB_USERNAME= DB_PASSWORD=
DB_CONNECTION=
DB_HOST=
DB_PORT=
DB_DATABASE=
DB_USERNAME=
DB_PASSWORD=

建立表

應用程式中的資料行儲存在表中。本應用程式只需要一個使用 Laravel 遷移建立的表。

  1. 要使用 Laravel 的命令列介面 Artisan 建立表格並生成遷移檔案,請執行:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
php artisan make:migration create_posts_table
php artisan make:migration create_posts_table
php artisan make:migration create_posts_table

上述命令將在database/migrations建立一個新檔案yyyy_mm_dd_hhmmss_create_posts_table.php.

  1. 開啟 yyyy_mm_dd_hhhmmss_create_posts_table.php,在 up 函式中定義資料庫表中需要的列:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('body');
$table->timestamps();
});
}
public function up() { Schema::create('posts', function (Blueprint $table) { $table->id(); $table->string('title'); $table->text('body'); $table->timestamps(); }); }
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('body');
$table->timestamps();
});
}

這段程式碼定義了帖子表的內容。它有四列: idtitlebody, 和 timestamps

  1. 執行database/migrations中的遷移檔案,在資料庫中建立表格:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
php artisan migrate
php artisan migrate
php artisan migrate

執行遷移,輸出結果如下:

執行遷移

  1. 轉到之前建立的資料庫,確認已建立表格:

建立的格

建立控制器

控制器包含從資料庫對帖子進行 CRUD 的所有功能。

使用 Artisan 在 Laravel 應用程式中生成控制器檔案:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
php artisan make:controller PostController --api
php artisan make:controller PostController --api
php artisan make:controller PostController --api

執行此命令可在 app/Http/Controllers 中建立 PostController.php 檔案,其中包含模板程式碼和空函式宣告 index、store、show、updatedestroy

建立函式

接下來,建立用於儲存、索引、更新、銷燬、建立、顯示和編輯資料的函式。

您可以將它們新增到下圖所示的 app/Http/Controller/PostController.php 檔案中。

 store 函式

store 功能將帖子新增到資料庫中。

滾動到 store 函式,在空的大括號內新增以下程式碼:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$request->validate([
'title' => 'required|max:255',
'body' => 'required',
]);
Post::create($request->all());
return redirect()->route('posts.index')
->with('success','Post created successfully.');
$request->validate([ 'title' => 'required|max:255', 'body' => 'required', ]); Post::create($request->all()); return redirect()->route('posts.index') ->with('success','Post created successfully.');
$request->validate([
'title' => 'required|max:255',
'body' => 'required',
]);
Post::create($request->all());
return redirect()->route('posts.index')
->with('success','Post created successfully.');

這段程式碼獲取一個包含帖子標題和正文的物件,驗證資料,如果資料有效,則在資料庫中新增一個新帖子,並將使用者重定向到主頁,同時給出一條成功資訊。

 index 函式

index 函式從資料庫中獲取所有帖子,並將資料傳送到 posts.index 頁面。

update 函式

update 函式包含要更新的帖子 id 、新帖子 title 和 body。驗證資料後,它會查詢具有相同 id 的帖子。如果找到, update 函式就會在資料庫中用新 title 和 body更新帖子。然後,它會將使用者重定向到主頁,並提示成功。

 destroy 函式

destroy 函式查詢具有給定 id 的帖子,並將其從資料庫中刪除,然後將使用者重定向到主頁,並給出成功訊息。

上述函式是用於從資料庫中對帖子進行 CRUD 的函式。不過,您必須在控制器中定義更多函式,以便在 resources/views/posts/ 中呈現必要的頁面。

 create 函式

create 函式渲染 resources/views/posts/create.blade.php 頁面,該頁面包含向資料庫新增帖子的表單。

 show 函式

show 函式會在資料庫中找到帶有給定 id 的帖子,並在 resources/views/posts/show.blade.php 檔案中顯示該帖子。

 edit 函式

edit 函式會在資料庫中找到帶有給定 id 的帖子,並在表單中顯示帶有帖子詳細資訊的 resources/views/posts/edit.blade.php 檔案。

設定模型

Post 模型與資料庫中的 posts 表互動。

  1. 要使用 Artisan 建立模型,請執行
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
php artisan make:model Post
php artisan make:model Post
php artisan make:model Post

這段程式碼會在 App/Models 資料夾中建立一個 Post.php 檔案。

  1. 建立一個 fillable 陣列(可填充陣列)。在 Post 類中的 use HasFactory; 行下面新增以下程式碼:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
protected $fillable = [
'title',
'body',
];
protected $fillable = [ 'title', 'body', ];
protected $fillable = [
'title',
'body',
];

這段程式碼建立了一個 fillable 陣列,允許你在 Laravel 應用程式中向資料庫新增專案。

  1.  like:將 Post 模型連線到 PostController.php 檔案。開啟 PostController.php,在 use Illuminate\Http\Request; 下新增下面一行。看起來像這樣
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
use Illuminate\Http\Request;
use App\Models\Post;
use Illuminate\Http\Request; use App\Models\Post;
use Illuminate\Http\Request;
use App\Models\Post;

現在,PostController.php 檔案應該是這樣的:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;
class PostController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$posts = Post::all();
return view('posts.index', compact('posts'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'title' => 'required|max:255',
'body' => 'required',
]);
Post::create($request->all());
return redirect()->route('posts.index')
->with('success', 'Post created successfully.');
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$request->validate([
'title' => 'required|max:255',
'body' => 'required',
]);
$post = Post::find($id);
$post->update($request->all());
return redirect()->route('posts.index')
->with('success', 'Post updated successfully.');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$post = Post::find($id);
$post->delete();
return redirect()->route('posts.index')
->with('success', 'Post deleted successfully');
}
// routes functions
/**
* Show the form for creating a new post.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('posts.create');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$post = Post::find($id);
return view('posts.show', compact('post'));
}
/**
* Show the form for editing the specified post.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$post = Post::find($id);
return view('posts.edit', compact('post'));
}
}
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Post; class PostController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $posts = Post::all(); return view('posts.index', compact('posts')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $request->validate([ 'title' => 'required|max:255', 'body' => 'required', ]); Post::create($request->all()); return redirect()->route('posts.index') ->with('success', 'Post created successfully.'); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $request->validate([ 'title' => 'required|max:255', 'body' => 'required', ]); $post = Post::find($id); $post->update($request->all()); return redirect()->route('posts.index') ->with('success', 'Post updated successfully.'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $post = Post::find($id); $post->delete(); return redirect()->route('posts.index') ->with('success', 'Post deleted successfully'); } // routes functions /** * Show the form for creating a new post. * * @return \Illuminate\Http\Response */ public function create() { return view('posts.create'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $post = Post::find($id); return view('posts.show', compact('post')); } /** * Show the form for editing the specified post. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $post = Post::find($id); return view('posts.edit', compact('post')); } }
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;
class PostController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$posts = Post::all();
return view('posts.index', compact('posts'));
}
/**
* Store a newly created resource in storage.
*
* @param  \Illuminate\Http\Request  $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'title' => 'required|max:255',
'body' => 'required',
]);
Post::create($request->all());
return redirect()->route('posts.index')
->with('success', 'Post created successfully.');
}
/**
* Update the specified resource in storage.
*
* @param  \Illuminate\Http\Request  $request
* @param  int  $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$request->validate([
'title' => 'required|max:255',
'body' => 'required',
]);
$post = Post::find($id);
$post->update($request->all());
return redirect()->route('posts.index')
->with('success', 'Post updated successfully.');
}
/**
* Remove the specified resource from storage.
*
* @param  int  $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$post = Post::find($id);
$post->delete();
return redirect()->route('posts.index')
->with('success', 'Post deleted successfully');
}
// routes functions
/**
* Show the form for creating a new post.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('posts.create');
}
/**
* Display the specified resource.
*
* @param  int  $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$post = Post::find($id);
return view('posts.show', compact('post'));
}
/**
* Show the form for editing the specified post.
*
* @param  int  $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$post = Post::find($id);
return view('posts.edit', compact('post'));
}
}

新增路由

建立控制器函式和 Post 模型後,必須為控制器函式新增路由。

  1. 開啟 routes/web.php,刪除應用程式生成的模板路由。用下面的程式碼替換,將控制器函式連線到各自的路由:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// returns the home page with all posts
Route::get('/', PostController::class .'@index')->name('posts.index');
// returns the form for adding a post
Route::get('/posts/create', PostController::class . '@create')->name('posts.create');
// adds a post to the database
Route::post('/posts', PostController::class .'@store')->name('posts.store');
// returns a page that shows a full post
Route::get('/posts/{post}', PostController::class .'@show')->name('posts.show');
// returns the form for editing a post
Route::get('/posts/{post}/edit', PostController::class .'@edit')->name('posts.edit');
// updates a post
Route::put('/posts/{post}', PostController::class .'@update')->name('posts.update');
// deletes a post
Route::delete('/posts/{post}', PostController::class .'@destroy')->name('posts.destroy');
// returns the home page with all posts Route::get('/', PostController::class .'@index')->name('posts.index'); // returns the form for adding a post Route::get('/posts/create', PostController::class . '@create')->name('posts.create'); // adds a post to the database Route::post('/posts', PostController::class .'@store')->name('posts.store'); // returns a page that shows a full post Route::get('/posts/{post}', PostController::class .'@show')->name('posts.show'); // returns the form for editing a post Route::get('/posts/{post}/edit', PostController::class .'@edit')->name('posts.edit'); // updates a post Route::put('/posts/{post}', PostController::class .'@update')->name('posts.update'); // deletes a post Route::delete('/posts/{post}', PostController::class .'@destroy')->name('posts.destroy');
// returns the home page with all posts
Route::get('/', PostController::class .'@index')->name('posts.index');
// returns the form for adding a post
Route::get('/posts/create', PostController::class . '@create')->name('posts.create');
// adds a post to the database
Route::post('/posts', PostController::class .'@store')->name('posts.store');
// returns a page that shows a full post
Route::get('/posts/{post}', PostController::class .'@show')->name('posts.show');
// returns the form for editing a post
Route::get('/posts/{post}/edit', PostController::class .'@edit')->name('posts.edit');
// updates a post
Route::put('/posts/{post}', PostController::class .'@update')->name('posts.update');
// deletes a post
Route::delete('/posts/{post}', PostController::class .'@destroy')->name('posts.destroy');
  1. 要連線路由,請開啟 app/Http/Controllers/PostController.php,在 use Illuminate\Support\Facades\Route; 行下新增下面一行:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;
use Illuminate\Support\Facades\Route; use App\Http\Controllers\PostController;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;

routes/web.php 檔案現在應該是這樣的:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;
// returns the home page with all posts
Route::get('/', PostController::class .'@index')->name('posts.index');
// returns the form for adding a post
Route::get('/posts/create', PostController::class . '@create')->name('posts.create');
// adds a post to the database
Route::post('/posts', PostController::class .'@store')->name('posts.store');
// returns a page that shows a full post
Route::get('/posts/{post}', PostController::class .'@show')->name('posts.show');
// returns the form for editing a post
Route::get('/posts/{post}/edit', PostController::class .'@edit')->name('posts.edit');
// updates a post
Route::put('/posts/{post}', PostController::class .'@update')->name('posts.update');
// deletes a post
Route::delete('/posts/{post}', PostController::class .'@destroy')->name('posts.destroy');
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\PostController; // returns the home page with all posts Route::get('/', PostController::class .'@index')->name('posts.index'); // returns the form for adding a post Route::get('/posts/create', PostController::class . '@create')->name('posts.create'); // adds a post to the database Route::post('/posts', PostController::class .'@store')->name('posts.store'); // returns a page that shows a full post Route::get('/posts/{post}', PostController::class .'@show')->name('posts.show'); // returns the form for editing a post Route::get('/posts/{post}/edit', PostController::class .'@edit')->name('posts.edit'); // updates a post Route::put('/posts/{post}', PostController::class .'@update')->name('posts.update'); // deletes a post Route::delete('/posts/{post}', PostController::class .'@destroy')->name('posts.destroy');
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;
// returns the home page with all posts
Route::get('/', PostController::class .'@index')->name('posts.index');
// returns the form for adding a post
Route::get('/posts/create', PostController::class . '@create')->name('posts.create');
// adds a post to the database
Route::post('/posts', PostController::class .'@store')->name('posts.store');
// returns a page that shows a full post
Route::get('/posts/{post}', PostController::class .'@show')->name('posts.show');
// returns the form for editing a post
Route::get('/posts/{post}/edit', PostController::class .'@edit')->name('posts.edit');
// updates a post
Route::put('/posts/{post}', PostController::class .'@update')->name('posts.update');
// deletes a post
Route::delete('/posts/{post}', PostController::class .'@destroy')->name('posts.destroy');

生成Blade檔案

有了路由之後,就可以建立 Laravel Blade 檔案了。在使用 Artisan 生成 Blade 檔案之前,先建立 make:view 命令,用它來生成 blade.php 檔案。

  1. 在 CLI 中執行以下程式碼,在 app/Console/Commands 資料夾中建立 MakeViewCommand 命令檔案:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
php artisan make:command MakeViewCommand
php artisan make:command MakeViewCommand
php artisan make:command MakeViewCommand
  1. 用下面的程式碼替換 MakeViewCommand 檔案中的程式碼,建立一條從 CLI 生成 .blade.php 檔案的命令:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use File;
class MakeViewCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'make:view {view}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new blade template.';
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$view = $this->argument('view');
$path = $this->viewPath($view);
$this->createDir($path);
if (File::exists($path))
{
$this->error("File {$path} already exists!");
return;
}
File::put($path, $path);
$this->info("File {$path} created.");
}
/**
* Get the view full path.
*
* @param string $view
*
* @return string
*/
public function viewPath($view)
{
$view = str_replace('.', '/', $view) . '.blade.php';
$path = "resources/views/{$view}";
return $path;
}
/**
* Create a view directory if it does not exist.
*
* @param $path
*/
public function createDir($path)
{
$dir = dirname($path);
if (!file_exists($dir))
{
mkdir($dir, 0777, true);
}
}
}
<?php namespace App\Console\Commands; use Illuminate\Console\Command; use File; class MakeViewCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'make:view {view}'; /** * The console command description. * * @var string */ protected $description = 'Create a new blade template.'; /** * Execute the console command. * * @return mixed */ public function handle() { $view = $this->argument('view'); $path = $this->viewPath($view); $this->createDir($path); if (File::exists($path)) { $this->error("File {$path} already exists!"); return; } File::put($path, $path); $this->info("File {$path} created."); } /** * Get the view full path. * * @param string $view * * @return string */ public function viewPath($view) { $view = str_replace('.', '/', $view) . '.blade.php'; $path = "resources/views/{$view}"; return $path; } /** * Create a view directory if it does not exist. * * @param $path */ public function createDir($path) { $dir = dirname($path); if (!file_exists($dir)) { mkdir($dir, 0777, true); } } }
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use File;
class MakeViewCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'make:view {view}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new blade template.';
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$view = $this->argument('view');
$path = $this->viewPath($view);
$this->createDir($path);
if (File::exists($path))
{
$this->error("File {$path} already exists!");
return;
}
File::put($path, $path);
$this->info("File {$path} created.");
}
/**
* Get the view full path.
*
* @param string $view
*
* @return string
*/
public function viewPath($view)
{
$view = str_replace('.', '/', $view) . '.blade.php';
$path = "resources/views/{$view}";
return $path;
}
/**
* Create a view directory if it does not exist.
*
* @param $path
*/
public function createDir($path)
{
$dir = dirname($path);
if (!file_exists($dir))
{
mkdir($dir, 0777, true);
}
}
}

建立主頁

接下來,建立您的主頁。主頁是 index.blade.php 檔案,其中列出了所有帖子。

  1. 要建立主頁,請執行:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
php artisan make:view posts.index
php artisan make:view posts.index
php artisan make:view posts.index

這會在 /resources/views 資料夾內建立 posts 資料夾,並在其下建立 index.blade.php 檔案。結果路徑為 /resources/views/posts/index.blade.php

  1. index.blade.php 檔案中新增以下程式碼:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
<title>Posts</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-warning">
<div class="container-fluid">
<a class="navbar-brand h1" href={{ route('posts.index') }}>CRUDPosts</a>
<div class="justify-end ">
<div class="col ">
<a class="btn btn-sm btn-success" href={{ route('posts.create') }}>Add Post</a>
</div>
</div>
</div>
</nav>
<div class="container mt-5">
<div class="row">
@foreach ($posts as $post)
<div class="col-sm">
<div class="card">
<div class="card-header">
<h5 class="card-title">{{ $post->title }}</h5>
</div>
<div class="card-body">
<p class="card-text">{{ $post->body }}</p>
</div>
<div class="card-footer">
<div class="row">
<div class="col-sm">
<a href="{{ route('posts.edit', $post->id) }}"
class="btn btn-primary btn-sm">Edit</a>
</div>
<div class="col-sm">
<form action="{{ route('posts.destroy', $post->id) }}" method="post">
@csrf
@method('DELETE')
<button type="submit" class="btn btn-danger btn-sm">Delete</button>
</form>
</div>
</div>
</div>
</div>
</div>
@endforeach
</div>
</div>
</body>
</html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous"> <title>Posts</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-warning"> <div class="container-fluid"> <a class="navbar-brand h1" href={{ route('posts.index') }}>CRUDPosts</a> <div class="justify-end "> <div class="col "> <a class="btn btn-sm btn-success" href={{ route('posts.create') }}>Add Post</a> </div> </div> </div> </nav> <div class="container mt-5"> <div class="row"> @foreach ($posts as $post) <div class="col-sm"> <div class="card"> <div class="card-header"> <h5 class="card-title">{{ $post->title }}</h5> </div> <div class="card-body"> <p class="card-text">{{ $post->body }}</p> </div> <div class="card-footer"> <div class="row"> <div class="col-sm"> <a href="{{ route('posts.edit', $post->id) }}" class="btn btn-primary btn-sm">Edit</a> </div> <div class="col-sm"> <form action="{{ route('posts.destroy', $post->id) }}" method="post"> @csrf @method('DELETE') <button type="submit" class="btn btn-danger btn-sm">Delete</button> </form> </div> </div> </div> </div> </div> @endforeach </div> </div> </body> </html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
<title>Posts</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-warning">
<div class="container-fluid">
<a class="navbar-brand h1" href={{ route('posts.index') }}>CRUDPosts</a>
<div class="justify-end ">
<div class="col ">
<a class="btn btn-sm btn-success" href={{ route('posts.create') }}>Add Post</a>
</div>
</div>
</div>
</nav>
<div class="container mt-5">
<div class="row">
@foreach ($posts as $post)
<div class="col-sm">
<div class="card">
<div class="card-header">
<h5 class="card-title">{{ $post->title }}</h5>
</div>
<div class="card-body">
<p class="card-text">{{ $post->body }}</p>
</div>
<div class="card-footer">
<div class="row">
<div class="col-sm">
<a href="{{ route('posts.edit', $post->id) }}"
class="btn btn-primary btn-sm">Edit</a>
</div>
<div class="col-sm">
<form action="{{ route('posts.destroy', $post->id) }}" method="post">
@csrf
@method('DELETE')
<button type="submit" class="btn btn-danger btn-sm">Delete</button>
</form>
</div>
</div>
</div>
</div>
</div>
@endforeach
</div>
</div>
</body>
</html>

上面的程式碼使用 Bootstrap 建立了一個簡單的 HTML 頁面。該頁面使用  @foreach  Blade 助手建立了一個導航欄和一個網格模板,其中列出了資料庫中所有帖子的詳細資訊和兩個操作按鈕–編輯和刪除。

Edit 按鈕會將使用者帶入 “Edit post” 頁面,使用者可以在這裡編輯帖子。Delete 按鈕使用 {{ route('posts.destroy', $post->id) }} 這個 DELETE 方法從資料庫中刪除帖子。

注:所有檔案的導航條程式碼與前一個檔案相同。

  1. 建立 create.blade.php 頁面。名為 create 的 Blade 檔案會將帖子新增到資料庫中。使用以下命令生成該檔案:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
php artisan make:view posts.create
php artisan make:view posts.create
php artisan make:view posts.create

這會在 /resources/views/posts 資料夾中生成 create.blade.php 檔案。

  1. create.blade.php 檔案中新增以下程式碼:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// same as the previous file. Add the following after the nav tag and before the closing body tag.
<div class="container h-100 mt-5">
<div class="row h-100 justify-content-center align-items-center">
<div class="col-10 col-md-8 col-lg-6">
<h3>Add a Post</h3>
<form action="{{ route('posts.store') }}" method="post">
@csrf
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" id="title" name="title" required>
</div>
<div class="form-group">
<label for="body">Body</label>
<textarea class="form-control" id="body" name="body" rows="3" required></textarea>
</div>
<br>
<button type="submit" class="btn btn-primary">Create Post</button>
</form>
</div>
</div>
</div>
// same as the previous file. Add the following after the nav tag and before the closing body tag. <div class="container h-100 mt-5"> <div class="row h-100 justify-content-center align-items-center"> <div class="col-10 col-md-8 col-lg-6"> <h3>Add a Post</h3> <form action="{{ route('posts.store') }}" method="post"> @csrf <div class="form-group"> <label for="title">Title</label> <input type="text" class="form-control" id="title" name="title" required> </div> <div class="form-group"> <label for="body">Body</label> <textarea class="form-control" id="body" name="body" rows="3" required></textarea> </div> <br> <button type="submit" class="btn btn-primary">Create Post</button> </form> </div> </div> </div>
// same as the previous file. Add the following after the nav tag and before the closing body tag.
<div class="container h-100 mt-5">
<div class="row h-100 justify-content-center align-items-center">
<div class="col-10 col-md-8 col-lg-6">
<h3>Add a Post</h3>
<form action="{{ route('posts.store') }}" method="post">
@csrf
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" id="title" name="title" required>
</div>
<div class="form-group">
<label for="body">Body</label>
<textarea class="form-control" id="body" name="body" rows="3" required></textarea>
</div>
<br>
<button type="submit" class="btn btn-primary">Create Post</button>
</form>
</div>
</div>
</div>

上面的程式碼建立了一個帶有 title 和 body 欄位的表單,以及一個 submit 按鈕,用於通過 {{ route('posts.store') }} 操作和 POST 方法向資料庫新增帖子。

  1. 建立 Edit post 頁面,以編輯資料庫中的帖子。使用以下命令生成檔案:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
php artisan make:view posts.edit
php artisan make:view posts.edit
php artisan make:view posts.edit

這會在 /resources/views/posts 資料夾中建立 edit.blade.php 檔案。

  1. edit.blade.php 檔案中新增以下程式碼:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<div class="container h-100 mt-5">
<div class="row h-100 justify-content-center align-items-center">
<div class="col-10 col-md-8 col-lg-6">
<h3>Update Post</h3>
<form action="{{ route('posts.update', $post->id) }}" method="post">
@csrf
@method('PUT')
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" id="title" name="title"
value="{{ $post->title }}" required>
</div>
<div class="form-group">
<label for="body">Body</label>
<textarea class="form-control" id="body" name="body" rows="3" required>{{ $post->body }}</textarea>
</div>
<button type="submit" class="btn mt-3 btn-primary">Update Post</button>
</form>
</div>
</div>
</div>
<div class="container h-100 mt-5"> <div class="row h-100 justify-content-center align-items-center"> <div class="col-10 col-md-8 col-lg-6"> <h3>Update Post</h3> <form action="{{ route('posts.update', $post->id) }}" method="post"> @csrf @method('PUT') <div class="form-group"> <label for="title">Title</label> <input type="text" class="form-control" id="title" name="title" value="{{ $post->title }}" required> </div> <div class="form-group"> <label for="body">Body</label> <textarea class="form-control" id="body" name="body" rows="3" required>{{ $post->body }}</textarea> </div> <button type="submit" class="btn mt-3 btn-primary">Update Post</button> </form> </div> </div> </div>
<div class="container h-100 mt-5">
<div class="row h-100 justify-content-center align-items-center">
<div class="col-10 col-md-8 col-lg-6">
<h3>Update Post</h3>
<form action="{{ route('posts.update', $post->id) }}" method="post">
@csrf
@method('PUT')
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" id="title" name="title"
value="{{ $post->title }}" required>
</div>
<div class="form-group">
<label for="body">Body</label>
<textarea class="form-control" id="body" name="body" rows="3" required>{{ $post->body }}</textarea>
</div>
<button type="submit" class="btn mt-3 btn-primary">Update Post</button>
</form>
</div>
</div>
</div>

上面的程式碼建立了一個帶有 title 和 body 欄位的表單,以及一個提交按鈕,用於通過 {{ route('posts.update') }} 操作和 PUT 方法編輯資料庫中指定 id 的帖子。

  1. 然後,使用下面的程式碼重啟應用伺服器:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
php artisan serve
php artisan serve
php artisan serve

在瀏覽器上訪問 http://127.0.0.1:8000 ,檢視新部落格。單擊 “Add Post” 按鈕新增新帖子。

部署和測試CRUD應用程式

為部署應用程式做如下準備

  1. 通過宣告公共資料夾,使部署工作順利進行。在應用程式資料夾根目錄下新增一個 .htaccess 檔案,其中包含以下程式碼:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<IfModule mod_rewrite.c >
RewriteEngine On
RewriteRule ^(.*)$ public/$1 [L]
</IfModule >
<IfModule mod_rewrite.c > RewriteEngine On RewriteRule ^(.*)$ public/$1 [L] </IfModule >
<IfModule mod_rewrite.c >
RewriteEngine On
RewriteRule ^(.*)$ public/$1 [L]
</IfModule >
  1. routes/web.php 檔案中的路由上方新增以下程式碼,強制應用程式使用 HTTPS
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
use Illuminate\Support\Facades\URL;
URL::forceScheme('https');
use Illuminate\Support\Facades\URL; URL::forceScheme('https');
use Illuminate\Support\Facades\URL;
URL::forceScheme('https');
  1. 將程式碼推送到 Git 倉庫。Kinsta 支援從 GitHub、GitLab 或 Bitbucket 進行部署。

在 MyKinsta 上建立專案

  1. 如果您還沒有 MyKinsta 賬戶,請建立一個。
  1. 登入賬戶,單擊控制面板上的 Add Service 按鈕建立新應用程式。
  1. 如果您是新使用者,請連線到您的 GitHub、GitLab 或 Bitbucket 賬戶,並賦予特定許可權。
  1. 填寫表格並新增 APP_KEY 。你可以在 .env 檔案中找到相應的值。
  1. 選擇構建資源,以及是使用應用程式構建路徑還是使用 Dockerfile 構建應用程式。在本演示中,讓 MyKinsta 根據你的版本庫構建應用程式。
  1. 指定部署過程中要執行的不同程序。此時可以留空。
  1. 最後,新增您的付款方式。

確認付款方式後,MyKinsta 將部署您的應用程式併為您分配一個 URL,如下所示:

成功部署

成功部署。

您可以訪問該連結,但會出現 500 | Server Error 頁面,因為應用程式需要有效的資料庫連線才能執行。下面的部分將解決這個問題。

通過 MyKinsta 建立資料庫

  1. 要建立資料庫,請轉到 MyKinsta 面板並單擊 Add Service
  1. 選擇 Database 並填寫表格,輸入首選資料庫名稱、型別、使用者名稱和密碼。新增資料中心位置和適合您應用程式的資料庫大小。
  1. 下一頁顯示費用摘要和您的付款方式。單擊 “Create Database” 完成建立過程。
  1. 建立資料庫後,MyKinsta 會將您重定向到服務列表。單擊剛剛建立的資料庫,向下滾動到 External Connections。複製資料庫憑證。
  1. 返回應用程式的 “Deployment” 頁面並單擊 “Settings“。然後向下滾動到 Environment Variables,單擊 Add Environment Variables。按以下順序將資料庫憑據新增為環境變數:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
DB_CONNECTION=mysql
DB_HOST=External hostname
DB_PORT=External port
DB_DATABASE=Database name
DB_USERNAME=Username
DB_PASSWORD=Password
DB_CONNECTION=mysql DB_HOST=External hostname DB_PORT=External port DB_DATABASE=Database name DB_USERNAME=Username DB_PASSWORD=Password
DB_CONNECTION=mysql
DB_HOST=External hostname
DB_PORT=External port
DB_DATABASE=Database name
DB_USERNAME=Username
DB_PASSWORD=Password

應用程式環境變數列表現在應該如下所示:

.env 變數列表

.env 變數列表。

  1. 轉到應用程式的 “Deployments” 頁面,單擊 “Deploy Now” 手動部署應用程式,以應用這些更改。到目前為止,您已經建立了一個資料庫並將其連線到了應用程式。
  1. 最後,要在 MyKinsta 資料庫中建立資料庫表,請使用在 MyKinsta 應用程式中輸入的相同憑據更新 .env 檔案,並執行以下命令將資料庫連線到本地應用程式:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
php artisan migrate
php artisan migrate
php artisan migrate

此命令執行所有遷移檔案。它會在 MyKinsta 應用程式中建立所有已定義的表。

現在,您可以使用首次部署後分配的 URL 測試應用程式。

小結

Laravel 是一個全面的框架,可用於建立需要 CRUD 功能的健壯、可擴充套件的網路應用程式。憑藉直觀的語法和強大的功能,Laravel 可以輕鬆地在應用程式中構建 CRUD 操作。

本文介紹了 CRUD 操作的基本概念,以及如何使用 Laravel 的內建功能實現它們。它還解釋了:

  • 如何在 MyKinsta 中建立資料庫並將其連線到應用程式
  • 如何使用 Laravel 的遷移功能來定義資料庫表、建立控制器檔案及其函式
  • 定義模型並將其連線到控制器。通過 Laravel 的路由生成 Blade 檔案,建立相應的頁面和表單,並使用 MyKinsta 部署和測試應用程式。

評論留言