前提・実現したいこと
モデル側(Article.php)モデル側で書いた検索処理メソッドを、コントローラー側(ArticleController.php)で呼び出し
検索処理機能を使用できる様にしたい。
発生している問題・エラーメッセージ
モデル側で記述した検索処理メソッドを呼び出したいが、記述の仕方がわからない。
###ソースコード
ArticleController
1<?php 2 3namespace App\Http\Controllers; 4 5use App\Article; 6use Illuminate\Http\Request; 7use Illuminate\Support\Facades\DB; 8use Illuminate\Support\Facades\Auth; 9 10class ArticleController extends Controller 11{ 12 /** 13 * Display a listing of the resource. 14 * 15 * @return \Illuminate\Http\Response 16 */ 17 18 public function index() 19 { 20 $articles = Article::paginate(10);; 21 22 return view('articles.index',compact('articles')); 23 24 } 25 26 public function show($id) 27 { 28 $article = Article::find($id); 29 30 return view('articles.show', ['article' => $article]); 31 } 32 33 public function edit($id) 34 { 35 $article = Article::find($id); 36 37 return view('articles.edit',['article' => $article]); 38 } 39 40 public function update(Request $request,$id) 41 { 42 $article = Article::find($id); 43 44 $article->title = $request->input('title'); 45 $article->content = $request->input('content'); 46 $article->save(); 47 return redirect('articles'); 48 } 49 50 public function destroy($id) 51 { 52 $article = Article::find($id); 53 $article->delete(); 54 55 return redirect('articles'); 56 } 57 58 public function like(Article $article) 59 { 60 $id = Auth::id(); 61 $article->likes()->attach($id); 62 63 return [ 64 'id' => $article->id, 65 'countLikes' => $article->count_likes, 66 ]; 67 } 68 69 public function unlike(Article $article) 70 { 71 $id = Auth::id(); 72 $article->likes()->detach($id); 73 74 return [ 75 'id' => $article->id, 76 'countLikes' => $article->count_likes, 77 ]; 78 } 79} 80
Article
1<?php 2 3namespace App; 4 5use Illuminate\Database\Eloquent\Model; 6use Illuminate\Database\Eloquent\Relations\BelongsTo; 7use Illuminate\Database\Eloquent\Relations\BelongsToMany; 8 9class Article extends Model 10{ 11 public function user(): BelongsTo 12 { 13 return $this->belongsTo('App\User'); 14 } 15 16 public function likes(): BelongsToMany 17 { 18 return $this->belongsToMany('App\User', 'likes')->withTimestamps(); 19 } 20 21 public function isLikedBy(?User $user): bool 22 { 23 return $user 24 ? (bool)$this->likes->where('id', $user->id)->count() 25 : false; 26 } 27 28 public function getCountLikesAttribute(): int 29 { 30 return $this->likes->count(); 31 } 32 33 public function search(Request $request) 34 { 35 $search = $request->input('search'); 36 37 //検索フォーム用 38 $query = DB::table('articles'); 39 40 if($search !== null){ 41 //全角スペースを半角に 42 $search_split = mb_convert_kana($search,'s'); 43 44 //空白で区切る 45 $search_split2 = preg_split('/[\s]+/',$search_split,-1,PREG_SPLIT_NO_EMPTY); 46 47 //単語をループで回す 48 foreach($search_split2 as $value) 49 { 50 $query->where('title','like','%'.$value.'%'); 51 } 52 53 } 54 } 55}
回答1件
あなたの回答
tips
プレビュー