いつもお世話になります。質問させてください。
ユーザーのプロフィールページを作っています。
Usersテーブルに
user_id, url_name
のカラムがありurl_nameを任意にしたいと思っています。
そのため、url_nameをセットしてる人とそうでない人用のrouteをセットして
それぞれcontrollerを分けて同じテンプレートを表示しています。
URLとしては
url_nameがある場合のurl :http://domain/url_name
ない場合のurl :http://domain/user/{id}/profile
としたいです。
routesとcontrollerは下記の通りです。
PHP
1//routes/web.php 2 3//user_profile show 4Route::get('user/{id}/profile', 'UserProfileController@show')->name('user_profile.show'); 5Route::post('user/{id}/profile', 'UserProfileController@show')->name('user_profile.show'); 6//user_profile.showByName 7Route::get('{name}', 'UserProfileController@showByName')->name('user_profile.showByName'); 8Route::post('{name}', 'UserProfileController@showByName')->name('user_profile.showByNmae'); 9
コントローラーはこのような形です。
PHP
1//UserProfile.controller 2////showメソッド 3 public function show(Request $request, $id) 4 { 5 $user = User::find($id); 6 7 //redirect to static_url if the article has that. 8 if($user->url_name != null){ 9 return redirect() 10 ->action('UserProfileController@showByName', ['name' => $user->url_name]); 11 } 12 13 // 以降は処理 14 //諸々の値を作りそれを渡してテンプレートを表示 15 16 return view('user_profile.show', [ 17 'user' => $user, 18 'moderatings' => $moderatings, 19 'drafts' => $drafts, 20 'categoryName' => $categoryName, 21 'entry_type' => $entry_type, 22 ]); 23 24 25 26//showByNameメソッド 27 public function showByName(Request $request, $name) 28 { 29 $user = User::where('url_name', '=', $name)->first(); 30 31 // 以降はuser_profile showと同じ処理 32
controllerの冒頭の処理のところの違いで、URL中の $idで$userを作るか$nameで$userを作るか以外はほとんど同じなので共通の処理にしたいと考えています。
以下二点ご教示いただけると助かります。
①後続の処理を同一コントローラー内に記述する方法があれば記述の方法
②後続の処理を別の場所に記述する場合、その場所と記述方法
routes/web.phpに描く方法などあるのでしょうか。
よろしくおねがいいたします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/10/22 10:14
2017/10/22 10:51
2017/10/22 12:31
2017/10/22 13:21