2018年12月14日 星期五

資料增刪查範例

*資料增刪查範例:

1.routes:

routes\web.php

<?php
Route::get('/', function () {
    return view('welcome');
});

Route::get('/todo', 'TodoController@index');

Route::post('/todo', 'TodoController@update');

Route::delete('/todo/{todo}', 'TodoController@destroy');

-------------------
2.controller:

app\Http\Controllers\TodoController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Todo; //model

class TodoController extends Controller
{
    public function index()
    {
        $todos=Todo::all();
        // dd($todos); //列出資料

        return view('todo.index',[
            'todos'=>$todos
        ]);
    }

    //新增資料
    public function update(Request $request)
    {
        //驗證
        $validated=$request->validate([
            'title' => 'required|min:3'
        ]);

        //測試
        //return $request->all();
       
        //方法1
        // $todo=new Todo();
        // $todo->title=$request->title;
        // $todo->save();
        // return $todo;
       
        //方法2
        // $todo=Todo::create([
        //     'title' => $request->title
        // ]);
        // return $todo;

        //方法3
        // $todo=Todo::create($request->all()); //$request為未驗證資料
        $todo=Todo::create($validated); //$validated為已驗證資料
        //return $todo;
        return redirect('todo');
    }

    //刪除資料
    public function destroy(Request $request,Todo $todo)
    {
        //測試
        // dd($todo);
        // return $todo;

        $todo->delete();
        return redirect('todo');
    }
}

-------------------
3.view:

resources\views\todo\index.blade.php

{{-- {{ $todos }} --}}
{{-- {{ $errors }} --}}

@if ($errors->has('title'))
    <strong>{{ $errors->first('title') }}</strong>
@endif

@foreach ($todos as $todo)
    <p>
        {{ $todo->id.'.'.$todo->title }}
        <form action="{{url('todo/'.$todo->id)}}" method="POST">
            @csrf
            @method('DELETE')
            <input type="submit" value="刪除">
        </form>
    </p>
@endforeach

<form action="{{url('todo')}}" method="POST">
    @csrf
    <input type="text" placeholder="請輸入" name="title">
    <input type="submit" value="送出">
</form>

-------------------
4.model:

app\Todo.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Todo extends Model
{
    protected $fillable = [
        'title'
    ];
}



沒有留言:

張貼留言