Featured image of post Day 13. 第二個頁面: 個人資料維護

Day 13. 第二個頁面: 個人資料維護

資源

Laravel7 30天: 目錄
專案連結: github - laravel7 之 30 天分享

前言

專案連結: github - laravel7 之 30 天分享

上一篇: Day 12. Eloquent: Model
今天我們要做第二個頁面了

主要

這次要來更新個人資料,
我們把會員跟個人資料表分開,所以這次要更新兩張表 usersuser_profiles

建立 route

開啟檔案 route/web.php 設定路由

1
2
3
4
Route::group(['prefix' => 'profile', 'as' => 'profile.' ], function() {
    Route::get('/', 'ProfileController@edit')->name('edit');
    Route::post('/', 'ProfileController@update')->name('update');
});

建立 controller

1
php artisan make:controller ProfileController

建立 controller function 們

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class ProfileController extends Controller
{
   /**
     * 顯示
     */
    public function edit() 
    {

    }

    /**
     * update
     */
    public function update(Request $reqest) 
    {

    }
}

建立 view及入口

我把入口放在右上角登出的下拉選單中,
route('profile.edit') 為我們剛剛設定的路由的名稱

1
2
3
4
5
6
7
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown">
   <!-- ... -->
    <a class="dropdown-item" href="{{ route('profile.edit') }}">
        個人資料維護
    </a>
   <!-- ... -->
</div>

建立 view

我是直接複製 home.blade.php 的內容變 profile.blade.php
old() 是 Laravel 表單的神奇魔法可以保留送出的值,
之後 驗證(validation) 的單元會詳細解說

調整 ProfileController 的 edit()

view('profile', compact('user')) 為顯示 view 的畫面,
第一個參數是 view 的頁面,第二個參數是要傳入的參數

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
use Illuminate\Support\Facades\Auth;

class ProfileController extends Controller
{
    public function edit() 
    {
        $user = Auth::user();
        
        return view('profile', compact('user'));
    }
    // ...
}

Auth 為目前登入的使用者,記得要 use Illuminate\Support\Facades\Auth;

調整 ProfileController 的 update()

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class ProfileController extends Controller
{
   public function update(Request $reqest) 
    {
        $user = Auth::user();
        
        $user->update([
            'name' => $reqest->name
        ]);

        UserProfile::updateOrCreate([
            'user_id' => $user->id
        ], [
            'gender' => $reqest->gender,
            'birthday' => $reqest->birthday,
            'address' => $reqest->address,
        ]);

        session()->flash('status', '更新成功。');
        return redirect()->route('home');
    }
}

這樣就完成簡單的會員基本資料更新了。

comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy