Nabil Farhan
Nabil Farhan

Reputation: 1536

How to automatically update data in laravel view?

I have a view which will show the list important tasks from database. I have a function in controller which returns the collection of data to the view.

My controller function is

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

My view is like

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

What I want to essentially do is to call the list function whenever a new important task is added into the database. How can I do that?

Upvotes: 2

Views: 5589

Answers (2)

Khan Shahrukh
Khan Shahrukh

Reputation: 6401

To achieve this kind of setup you may use Pusher or any other similar provider, once you signup on pusher you can send 200k notifications per day for free, you can check the limits after login to pusher. Before we proceed please install pusher's official php package

composer require pusher/pusher-php-server

From your pusher dashboard obtain app_id, key, secret and cluster now in your controller/model where you are inserting the data in database add the following code

//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);  

Now in your view before the </body> tag paste the following code

<!-- 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>

Upvotes: 2

Saurabh Mistry
Saurabh Mistry

Reputation: 13689

in your web.php

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

inside your controller :

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'));
}

inside your blade view :

<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>

Upvotes: 6

Related Questions