:::

9-3 將資料寫進資料庫

  1. 修改路由 /專案/routes/web.php,儲存部份改用控制器:
    Route::post('/exam', 'ExamController@store')->name('exam.store');
  2. 接著編輯控制器 /專案/app/Http/Controllers/ExamController.php,修改 store 方法,儲存後本來應該要轉向到建立題目的頁面,但因為相關頁面都還沒做,所以還是暫時轉回測驗首頁。
    public function store(Request $request)
    {
        $exam          = new Exam;
        $exam->title   = $request->title;
        $exam->user_id = $request->user_id;
        $exam->enable  = $request->enable;
        $exam->save();
        return redirect()->route('exam.index');
    }
  3. 記得在上方告知要使用 App\Exam 模型
    <?php
    
    namespace App\Http\Controllers;
    
    use App\Exam;
    use Illuminate\Http\Request;
  4. $request 就是使用者輸入的內容,以物件方式存在。詳情可參考:https://laravel-china.org/docs/laravel/5.6/requests/1367#accessing-the-request
  5. Exam則是Eloquent Model,也就是用來操作exam資料表的模型。儲存部份可參考:https://laravel-china.org/docs/laravel/5.6/eloquent/1403#inserting-and-updating-models
  6. redirect() 用來轉向,詳細用法可參考:https://laravel-china.org/docs/laravel/5.6/responses/1368#c51dd1
  7. 接著可以試試看是否能儲存文章囉!(請暫時先到資料庫去看結果)

到GitHub觀看此單元程式異動


:::

書籍目錄

展開 | 闔起

http%3A%2F%2Fcampus-xoops.tn.edu.tw%2Fmodules%2Ftad_book3%2Fpage.php%3Ftbsn%3D37%26tbdsn%3D1168

計數器

今天: 779779779
昨天: 2335233523352335
總計: 7472787747278774727877472787747278774727877472787