Laravel 基礎操作

數據遷移(創建表結構)

根目錄下運行命令(創建遷移文件):

php artisan make:migration create_posts_table

生成文件於 /database/migrations/xxx_xxx_xx_create_posts_table.php,編輯:

// 設計表結構
public function up(){
    Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title', 100)->default("");
        $table->text('content');
        $table->integer('user_id')->default(0);
        $table->timestamps();
    });
}

public function down(){
    Schema::dropIfExists('posts');
}

運行(開始生成):

 php artisan migrate

數據填充(填充假數據)

使用模型工廠填充,首先創建 /database/factories/PostFactory.php,添加以下代碼:

// Faker\Generator $faker 是一個開源的創建測試數據的工具類(數據填充)
$factory->define(App\Post::class, function (Faker\Generator $faker) {
    return [
        'title' => $faker->sentence(10),
        'content' => $faker->paragraph(15),
    ];
});

tinker 執行命令:

 $ php artisan tinker

Psy Shell v0.9.9 (PHP 7.1.23 — cli) by Justin Hileman

>>> factory(App\Post::class, 50)->create();

# 插入 50 條測試數據

詳情查看GitHub 庫:https://github.com/fzaninotto/Faker

查詢(數據分頁)

路由:

Route::get("posts","PostController@index");

控制器層,如 PostController.php

public function index(){
    // 每頁展示 10
    $posts = Post::orderBy("created_at","desc")
        ->paginate(10);
    return view("post/index",compact('posts'));
}

視圖層,如 /resources/views/post/index.blade.php

@foreach ($posts as $post)
    <div class="blog-post">
        <h2 class="blog-post-title"><a href="/posts/{{$post->id}}" >{{$post->title}}</a></h2>
        <p class="blog-post-meta">{{$post->created_at->toFormattedDateString()}}</p>
        {{str_limit($post->content,255,"...")}}
    </div>
@endforeach

{{$posts->links()}}

 查詢(模型參數)

路由:

Route::get("posts/{post}","PostController@show") ->where(["post" => "[0-9]+"]);

控制器層,如 PostController.php

// $post 爲Post模型類
public function show(Post $post){
    return view("post/show",compact('post'));
}

跳轉鏈接:

<a href="/posts/{{$post->id}}" >{{$post->title}}</a>

視圖層:

新增( CSRF)

打開表單頁面時,需要記錄一個值保存到 session,在提交之後判斷所提交的值是否和刷新表單時創建的值一致。

路由:

// 表單頁面
Route::get("posts/create",function(){
    return view("post/create");
});
// 處理
Route::post("posts/","PostController@store");

視圖層,/resources/views/post/create.blade.php

<form action="/posts" method="POST">
    {{csrf_field()}}
    <div class="form-group">
        <label>標題</label>
        <input name="title" type="text" class="form-control" placeholder="這裏是標題">
    </div>
    <div class="form-group">
        <label>內容</label>
        <textarea id="content"  style="height:400px;max-height:500px;" name="content" class="form-control" placeholder="這裏是內容"></textarea>
    </div>
    <button type="submit" class="btn btn-default">提交</button>
</form>

控制器保存:

父類 Controller 已經 use ValidatesRequests (使用了Trait), 可以直接使用驗證器類,一般 web 請求的錯誤會保存到 $errors 中,ajax 異步請求的錯誤會發送 JSON 響應。

public function store(Request $request){
    $this->validate($request, [
        'title' => 'required|string|unique:posts|max:255|min:5',
        'content' => 'required|string|min:5',
    ]);
    // 批量注入安全問題,laravel 默認不允許,可通過模型屬性 fillable|guarded 打開
    $post = Post::create($request->all());
    return redirect("/posts");
}

表單驗證:https://learnku.com/docs/laravel/5.4/validation/1234

修改

路由:

// 頁面
Route::get("posts/{post}/edit",function (\App\Post $post)
{
    return view("post/edit",compact("post"));
});
// 邏輯
Route::put("posts/{post}","PostController@update");

視圖:

<form action="/posts/{{$post->id}}" method="POST">
    {{method_field("PUT")}}
    {{csrf_field()}}
    // ...
</form>

控制器:

public function update(Request $request, Post $post)
{
    // 驗證
    $this->validate($request, [
        'title' => 'required|string|unique:posts|max:255|min:5',
        'content' => 'required|string|min:5',
    ]);

    // 處理
    $post->title = $request->input('title');
    $post->content = $request->input('content');
    $post->save();

    // 渲染
    return redirect("/posts");
}

刪除

路由:

Route::get("posts/{post}/delete","PostController@destroy");

操作:

public function destroy(Post $post)
{
    // TODO::權限驗證
    $post->delete();
    return redirect("/posts");
}

# 總結 # 

增刪改查走一遍就會涉及一些基礎功能,如路由route、模板blade、模型model、控制器controller、數據遷移migrate、數據填充seeds、命令tinker、分頁paging、驗證器validate、csrf 等等。。。

很少使用laravel做開發所以經常不記得laravel優雅的寫法,現在tp特別tp6的寫法幾乎完全模仿laravel所以很容易上手。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章