質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
Laravel 5

Laravel 5は、PHPフレームワークLaravelの最新バージョンで、2014年11月に発表予定です。ディレクトリ構造がが現行版より大幅に変更されるほか、メソッドインジェクションやFormRequestの利用が可能になります。

Q&A

解決済

1回答

5843閲覧

[Laravel5.4]urlが別でほとんど同じ処理をする場合のcontrollerのコードの共通の仕方が知りたい

do_slice

総合スコア26

Laravel 5

Laravel 5は、PHPフレームワークLaravelの最新バージョンで、2014年11月に発表予定です。ディレクトリ構造がが現行版より大幅に変更されるほか、メソッドインジェクションやFormRequestの利用が可能になります。

0グッド

0クリップ

投稿2017/10/22 04:45

いつもお世話になります。質問させてください。

ユーザーのプロフィールページを作っています。

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に描く方法などあるのでしょうか。

よろしくおねがいいたします。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

処理が全く同じ場合は、同コントローラ内にメソッドに共通の処理を書いて呼び出せばできるかと思います。
コントローラにビジネスロジックを書きすぎるのはあまりよい習慣では無いので、ある程度の規模や試行錯誤が終わった後は、リポジトリパターン等でコントローラの外に処理を出してレイヤー構造を築くと、プログラムの見通しは良くなるかと思います。
Laravel リポジトリパターンの実装

public function show(Request $request, $id) { $user = User::find($id); return $this->getXXX($user); } public function showByName(Request $request, $id) { $user = User::where('url_name', '=', $name)->first(); return $this->getXXX($user); } protected function getXXX(User $user){ //redirect to static_url if the article has that. if($user->url_name != null){ return redirect() ->action('UserProfileController@showByName', ['name' => $user->url_name]); } // 以降は処理 //諸々の値を作りそれを渡してテンプレートを表示 return view('user_profile.show', [ 'user' => $user, 'moderatings' => $moderatings, 'drafts' => $drafts, 'categoryName' => $categoryName, 'entry_type' => $entry_type, ]); }

投稿2017/10/22 09:29

編集2017/10/22 09:30
aro10

総合スコア4106

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

do_slice

2017/10/22 10:14

aro10さん、いつも本当にありがとうございます。 実は$requestで、処理中でデータを作るときの検索用パラメーターをviewから色々渡していまして、それも合わせて protected function getXXX(User $user) の方に渡したいと考えています。 'category' => $category, 'create_month' => $create_month などのいくつかを毎回一定ではなく、リンクの種別ごとに違うパラメータをviewから受け取ったりしています。 $all = Request::all(); return $this->getUserProfile($user, $all); とやるのでは受け渡しができませんでした。 public function show(Request $request, $id) public function showByName(Request $request, $id) の方で、 if($request->has('category'){ //処理 }elseif$request->has('create_month'){ //処理 }... とやるしかないでしょうか。 またその場合の protected function getXXX(User $user){ の(User $user)のところは protected function getXXX(User $user, Category $category, Create_month $create_month) などその種別分追記という感じになるのでしょうか? 色々と質問ばかりで恐縮ですが、ご回答いただけると幸いです。
aro10

2017/10/22 10:51

$this->getUserProfileはどのようなコードになりますか? 複雑なパラメータを取り扱う時は、メソッドの引数をその分増やすかあるいは配列で渡す、受け渡し用にConfigクラスのようなものを作ってプロパティでまとめたりが考えられます
do_slice

2017/10/22 12:31

$this->getUserProfileはuser_profileページを生成する処理になってまして、user_id以外にもcreate_month, category, entry_typeなどのカラムを持っているコンテンツが入っているboardsテーブルを、フィルターのようなviewから送られる$requestパラメータでsortしてデータを作ってテンプレートに返すという処理が多いです。 下記のような検索条件をパラメータによって変えるという処理が書かれています。 //categoryName, entry_type, create_year_month //Filltered by category if($request->has('categoryName')){ $categoryName = $request->input('categoryName'); $entry_type = 'All'; $about_year_month = 'All'; $create_year_month = 'All'; $sortedTitle = $categoryName; $moderatings = DB::table('categories') ->where('name', $categoryName) ->join('board_category', 'categories.id', '=', 'board_category.category_id') ->join('boards', 'boards.id', '=', 'board_category.board_id') ->select('boards.*') ->where('appearance_policy', '<', $apparance_level ) ->where('boards.user_id', '=', $user->id) ->where('status', '!=', 'draft') ->where('published_at','<=', $now) ->where('showing_policy', '<', 150) ->paginate(5); }elseif($request->has('entry_type')){ //sort by entry_type $categoryName = 'All'; $entry_type = $request->input('entry_type'); $about_year_month = 'All'; $create_year_month = 'All'; $sortedTitle = $entry_type; if($entry_type === 'All' ){ //All list $moderatings = Board::where('user_id', '=', $id) ->where('appearance_policy', '<', $apparance_level ) ->where('status', '!=', 'draft') ->where('published_at','<=', $now) ->where('showing_policy', '<', 150) ->orderBy('updated_at', 'desc') ->paginate(5); }elseif($entry_type === 'board'){ //board lis $moderatings = Board::where('user_id', '=', $id) ->where('appearance_policy', '<', $apparance_level ) ->where('status', '!=', 'draft') ->where('published_at','<=', $now) ->where('showing_policy', '<', 150) ->where('entry_type', '=', $entry_type) ->orderBy('updated_at', 'desc') ->paginate(5); }else{ //article list $moderatings = Board::where('user_id', '=', $id) ->where('appearance_policy', '<', $apparance_level ) ->where('status', '!=', 'draft') ->where('published_at','<=', $now) ->where('showing_policy', '<', 150) ->where('entry_type', '=', $entry_type) ->orderBy('created_at', 'desc') ->paginate(5); }
do_slice

2017/10/22 13:21

送り出す側で各パラメータを生成するロジックを書いて、 受ける側を下記のようにしてとりあえず動くようになりました。 protected function getUserProfile(User $user, $categoryName, $create_year_month, $entry_type){ いただいたリンクなども拝見して、 配列で渡すのなどは勉強して試してみたいと思います。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問