隨手扎
30天成爲Laravel萌新(第22天) - 資源控制器(Resource Controller) 下篇
最終,我決定將index()和destroy()另外寫。一個是寫完create()和edit(),destroy()也就不怎麼難。但是index()意外也能有豐富內容能寫…(加上有另一種用法我還不太會)
總體來說,這篇程式還是有些趕工粗糙….
重點觀念
- @method的使用 相當於隱藏欄位- _method。
- @csrf的使用
建立頁面模板
同樣的,先建立一個編輯頁面的模板resource/views/blog/edit.blade.php:
@extends("base",['title'=>'編輯文章'])
@section('title', '編輯文章')
@section('body')
    <form method="post" action="{{($type=="edit") ?
                    route("blog/post.update", ["id"=>$id]) :
                    route("blog/post.store")}}">
        @csrf
        @method(($type=="edit")? "patch" : "post")
        <label for="title">標題:</label>
        <input name="title" type="text" value="{{$title}}" id="title" />
        <br/>
        <label for="content">內容:</label>
        <textarea cols="30" id="content" name="content" rows="10">{{$content}}</textarea>
        <br/>
        <input name="" type="submit" value="儲存"/>
    </form>
@endsection
這邊,建立新文章和編輯文章將會使用同一個頁面,只是行為有些不同。注意到有$type== "edit"的部份了嗎?在編輯時,action會是給於更新動作;而新建時會是使用儲存動作。
此外,前幾天談過,使用的Method也不同。不過網頁瀏覽器一般指允許GET和POST兩種方法。為了實現RESTful,Laravel在POST時,會而外檢查_method欄位,同時提供一個很簡單的方式插入這個隱藏欄位,沒錯,就是@method ()。
不過單純在這樣還是會出錯。為了安全性考慮,Laravel還會檢查來源,為此需要而外送出一個連線資訊,避免XSS攻擊。就是@csrf
完成處理實做
現在,快速看一下create()和edit()怎麼實現:
    public function create()
    {
        return view('blog/edit',[
            'title' => '未命名文章',
            'content' => '',
            'type' => 'create,'
        ]);
    }
    public function edit($id)
    {
        $post = BlogPost::find($id);
        return view('blog/edit',[
            'id' => $id,
            'title' => $post->title,
            'content' => $post->content,
            'type' => 'edit',
        ]);
    }
沒錯,兩者像極了,差就插在type。當然你還可以去而外檢查文章存不存在。
LINE Pay贊助 信用卡小額贊助寫這篇時,有些累… 恐怕有相當多地方沒寫好…
