Как автоматически обновить данные в режиме Laravel? - PullRequest
0 голосов
/ 04 декабря 2018

У меня есть вид, который покажет список важных задач из базы данных.У меня есть функция в контроллере, которая возвращает коллекцию данных в представление.

Моя функция контроллера

public function list()
{
    $tasks= Task::where('category','1')->get();
    //category is 1 when the task is important
    return view('important', compact('tasks'));
}

Мой вид похож на

<ul>    
@foreach ($tasks as $task)  
    <li> {{$task->body}}</li>
@endforeach
</ul>

Что яПо сути, вы хотите вызывать функцию списка каждый раз, когда в базу данных добавляется новая важная задача.Как я могу это сделать?

Ответы [ 2 ]

0 голосов
/ 04 декабря 2018

Чтобы выполнить настройку такого типа, вы можете использовать Pusher или любого другого аналогичного провайдера. После регистрации в pusher вы можете бесплатно отправлять 200 тыс. Уведомлений в день, вы можете проверить ограничения после входа в систему в pusher.Прежде чем мы продолжим, пожалуйста, установите официальный php-пакет pusher

composer require pusher/pusher-php-server

. Из панели инструментов pusher получите app_id, key, secret и cluster теперь в вашем контроллере / модели, куда вы вставляете данные.в базу данных добавьте следующий код

//You will get cluster name from pusher.com replace it below
    $options = ['cluster' => 'mt1', 'encrypted' => true];

   //Replace your key, app_id and secret in the following lines 
    $pusher = new Pusher(
        'key',
        'secret',
        'app_id',
        $options
    );

    //this could be a single line of message or a json encoded array, in your case you want to pass some data to display in table I assume you have an array 
    $message= json_encode(['name' => 'John doe', 'age' => 42, 'etc' => 'etc']);

    //Send a message to users channel with an event name of users-list. Please mind this channel name and event name could be anything but it should match that with your view 
    $pusher->trigger('users', 'users-list', $message);  

Теперь перед вашим тегом </body> вставьте следующий код

<!-- Incldue Pusher Js -->
<script src="https://js.pusher.com/4.2/pusher.min.js"></script>
<script>
//Remember to replace key and cluster with the credentials that you have got from pusher.
var pusher = new Pusher('key', {
  cluster: 'mt1',
  encrypted: true
});

//In case you have decided to use a different channel and event name in your controller then change it here to match with the one that you have used
var channel = pusher.subscribe('users');
channel.bind('users-list', function(message) {
//if you will console.log(message) at this point you will see the data 
//that was sent from your controller is available here please consume as you may like 
    alert(message);
});

</script>
0 голосов
/ 04 декабря 2018

в вашем web.php

Route::get('/tasks','TasksController@list')->name('get_tasks');

внутри вашего контроллера:

use Illuminate\Http\Request;

public function list(Request $request)
{
    $tasks= Task::where('category','1')->get();
    if($request->ajax()){
       return response()->json(array('tasks'=>$tasks));
    }
    return view('important', compact('tasks'));
}

внутри вашего блэйда:

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
   $(document).ready(function(){
       setInterval(function(){
          $.ajax({
             url:'/tasks',
             type:'GET',
             dataType:'json',
             success:function(response){
                if(response.tasks.length>0){
                   var tasks ='';
                   for(var i=0;i<response.tasks.length;i++){
                      tasks=tasks+'<li>'+response.tasks[i]['body']+'</li>';
                   }
                   $('#tasklist').empty();
                   $('#tasklist').append(tasks);
                }
             },error:function(err){

             }
          })
       }, 5000);
   });
</script>



    <ul id="tasklist">    
        @foreach ($tasks as $task)  
        <li> {{$task->body}}</li>
       @endforeach
    </ul>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...