Developer Snippet Diary

Add to favorite item laravel tutorial

  1. add to fav button in view ie jobs.blade.php
<button type="button" class="add_to_fav btn btn-block apply_btnis" data-id="{{$job->id}}" data-table="data_jobs"> Faverite it 
   <i class="far fa-heart @if($job->is_fav) fas @endif"></i>
</button>

2. Add javascript code for ajax request in jobs.blade.php

<script type="text/javascript">
  js_click(".add_to_fav", function() {

    var product_id = attr(this,"data-id");
    var table_name=attr(this,"data-table");
    var element = this;
      js_ajax('/add_fav', 'POST', {'_token': '<?php echo csrf_token() ?>',user_id: '{{auth()->id()}}', table_name: table_name,product_id:product_id}, function(response) {
        var resp = JSON.parse(response);
        if(resp.flag){
            var message = resp.message;
            if(message=="added"){
                addClass(".add_to_fav[data-id='"+product_id+"'] i","fas");
            }else{
                removeClass(".add_to_fav[data-id='"+product_id+"'] i","fas");
            }
        }
      }, function(error) {
      console.error(error);
    });
  });


  function js_ajax(url, method, data, successCallback, errorCallback) {
	  const xhr = new XMLHttpRequest();
	  xhr.open(method, url);
	  xhr.setRequestHeader('Content-Type', 'application/json');
	  xhr.onload = function() {
	    if (xhr.status === 200) {
	      successCallback(xhr.responseText);
	    } else {
	      errorCallback(xhr.statusText);
	    }
	  };
	  xhr.onerror = function() {
	    errorCallback(xhr.statusText);
	  };
	  xhr.send(JSON.stringify(data));
	}

	function attr(element, attribute, value) {
	  if (typeof value === 'undefined') {
	    return element.getAttribute(attribute);
	  } else {
	    element.setAttribute(attribute, value);
	    return element;
	  }
	}
		
	function addClass(selector, className) {
	  const elements = document.querySelectorAll(selector);
	  elements.forEach(element => {
	    element.classList.add(className);
	  });
	}

	function removeClass(selector, className) {
	  const elements = document.querySelectorAll(selector);
	  elements.forEach(element => {
	    element.classList.remove(className);
	  });
	}
</script>

3. Add Route to add new item or remove

Route::controller(\App\Http\Controllers\APIController::class)->group( function () {
    Route::post('/add_fav','add_to_fav')->name('add_fav');
});

4. Add controller code ie apiController.php

public function add_to_fav(Request $request){ //add to fav if already exit remove fav
        $validatedData = $request->validate([
            'product_id' => 'required',
            'table_name' => 'required'
        ]);
        if(auth()->id()){
            $fav = Fav_items::where("product_id",$request->product_id)->where("table_name",$request->table_name)->where("user_id",auth()->id())->first();
            if($fav){
                //delete it 
                $fav->delete();
                return response()->json(['flag' => true, 'message' => "removed"],200);
            }else{
                //insert it 
                $fav = new Fav_items;
                $fav->product_id = $request->product_id;
                $fav->table_name = $request->table_name;
                $fav->user_id = auth()->id();
                $fav->save();
                return response()->json(['flag' => true, 'message' => "added"],200);
            }            
        }
     
    }

    public function isFavoritedByCurrentUser($product_id,$table_name)
    {
        if(auth()->id() && $product_id && $table_name){
            $is_fav = Fav_items::where("product_id",$product_id);
            $is_fav = $is_fav->where("table_name",$table_name);
            $is_fav = $is_fav->where("user_id",auth()->id())->exists();
            if($is_fav){
                return 1;
            }else{
                return null;
            }
        }
    }

 

5. Add logic to view controller to display filled or not JobsController.php

$jobs=$jobs->paginate(10)->withQueryString();
foreach($jobs as $job){
   $job->is_fav = \App\Http\Controllers\APIController::isFavoritedByCurrentUser($job->id,'data_jobs');
}

6. add table to db

DROP TABLE IF EXISTS `fav_items`;
CREATE TABLE `fav_items` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` varchar(255) NOT NULL,
  `product_id` varchar(255) NOT NULL,
  `table_name` varchar(255) NOT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  PRIMARY KEY (`id`)
)
Posted by: R GONDAL
Email: rizikmw@gmail.com