2017-09-06 16 views
0

私はプロジェクトで作業しています。アプリケーションの最初のページには、ランダムな順序で投稿の1つを表示するブロックがありますが、このランダムな投稿を更新して別のものを表示するボタンもあります代わりにユーザーがページを更新する必要はありません。laravel 5.5でランダムボタンを作成する

私の質問は、そのボタンを動作させる方法です。ここで

は私のコントローラです:

public function index() { 
     $randomfood = Food::where('status', 1)->inRandomOrder()->take(1)->get(); 
     return view('welcome', compact('randomfood')); 
} 

これが私の見解です:

@foreach($randomfood as $randfood) 
     <div class="col-md-2"><a href="{{ route('showrecipe', $food->slug) }}"><img src="{{url('/')}}/images/{{$randfood->image}}" class="thumbnail img-responsive" alt="food image"></a></div> 
     <div class="col-md-8"> 
       <h5><a href="{{ route('showrecipe', $food->slug) }}">{{$randfood->title}}</a></h5> 
       {!! str_limit($randfood->description, 100) !!} 
     </div> 
     <div class="col-md-2 text-center"> 
       <p>Don't like?</p> 
       <a class="bhover" href="#">Find another recipie</a> 
     </div> 
@endforeach 

enter image description here

UPDATE:で確認した後

JSコードは次のようにありますコンソールで

$(document).ready(function() { 
$("a.bhover").click(function() { 
$.ajax({ 
      url: "{{route('food.randompost')}}", 
      data: {"token_": "{{Session::token()}}"}, //session token, neccesary to use POST request 
      type: "food", 
      success: function (data) { 
      $("#live_content").empty(); //clean the actual post 
      $("#live_content").append(data); // add new post from the controller 
      }, 
      error: function(data){ 
       //handle errors here 
      } 
     }); 
}); 
}); 
}); 

エラー:

SyntaxError: expected expression, got '}'[Learn More] 
+1

使用Ajaxはランダムポストをリフレッシュするために呼び出す何かをundersandしていないなら、私が知っているすべてです:あまりにもボタンのクリック操作にバインドを追加します。 –

+0

@SagarGautamあなたはそれをやる方法を教えてもらえますか? – mafortis

+0

データベースからランダム投稿を取得するロジックについて知っているからです。ボタンをクリックすると、javascriptのボタンクリックのイベントを検出し、ajaxを呼び出して関数を呼び出す必要があります。関数では、ランダム投稿を取得し、関数からのjsonレスポンスとしてランダム投稿を返すコードを記述する必要があります。その後、ajaxの成功関数で、jsonレスポンスのデータを使ってhtmlで現在のポストデータをリフレッシュするコードを記述する必要があります。あなたが理解したいと思っています。 –

答えて

1

あなたが本当にここに何をしたいかは、次のとおりです。

public function index() { 
     $randomfood = Food::where('status', 1)->inRandomOrder()->first(); 
     return view('welcome', compact('randomfood')); 
} 

ですから、単一の要素としての代わりとして、あなたのランダムな食品のポストを使用することができますコレクション。ライブ、それを作るために必要なライブ要素をラップdiv要素を追加してみましょう:今

<div id="live_content"> 
        <div class="col-md-2"><a href="{{ route('showrecipe', $food->slug) }}"><img src="{{url('/')}}/images/{{$randomfood ->image}}" class="thumbnail img-responsive" alt="food image"></a></div> 
        <div class="col-md-8"> 
        <h5><a href="{{ route('showrecipe', $food->slug) }}">{{$randomfood->title}}</a></h5> 
         {!! str_limit($randomfood->description, 100) !!} 
        </div> 
</div> 
        <div class="col-md-2 text-center"> 
         <p>Don't like?</p> 
         <a class="bhover" href="#">Find another recipie</a> 
        </div> 

オーケー、のはすなわちlive.recipe.blade.php、更新されたデータを埋めるために、ブレードのビューを作成してみましょう:

<div class="col-md-2"><a href="{{ route('showrecipe', $food->slug) }}"><img src="{{url('/')}}/images/{{$randomfood ->image}}" class="thumbnail img-responsive" alt="food image"></a></div> 
         <div class="col-md-8"> 
         <h5><a href="{{ route('showrecipe', $food->slug) }}">{{$randomfood->title}}</a></h5> 
          {!! str_limit($randomfood->description, 100) !!} 
         </div> 

我々が必要としますルートと私たちのコントローラにAJAX呼び出しを処理する方法それでは、それを追加してみましょう:

web.php

Route::post('update-post', '[email protected]')->name('food.randompost'); 
私たちは、ビュー内のスクリプトのセクションでそれを追加し、AJAX呼び出しを使用してこのメ​​ソッドを呼び出すつもり

コントローラ

public function updateRandomPost(Request $request) { 
     $randomfood = Food::where('status', 1)->inRandomOrder()->first(); // get new random post 
     return view('live.recipe', compact('randomfood')); //fill our live post template and retrieve it to the view 
} 

<script 
    src="https://code.jquery.com/jquery-3.2.1.min.js" 
    integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" 
    crossorigin="anonymous"></script> 
<script> 
    $(document).ready(function() { 
    $("a.bhover").click(function() { 
     $.ajax({ 
       url: '{{route('food.randompost')}}', //our fresh route name 
       data: {"token_": '{{Session::token()}}'}, //session token, neccesary to use POST request 
       type: 'post', 
       success: function (data) { 
        $('#live_content').empty(); //clean the actual post 
        $('#live_content').append(data); // add new post from the controller 
       }, 
       error: function(data){ 
        //handle errors here 
       } 
      }); 
    }); 

    }); 
</script> 

そして、それはIMO、あなたが

+0

コメントは議論の延長ではありません。この会話は[チャットに移動]されています(http://chat.stackoverflow.com/rooms/153795/discussion-on-answer-by-aaron0207-creating-random-button-collect-in-laravel-5-5) 。 – Andy