vendredi 1 novembre 2019

How to retrieve only records that are not deleted from database in Laravel?

I have recommends table that has product_id, user_id and deleted_at columns and I want to display the most viewed products in the view and it works fine but the problems is when user deletes the product I get an error trying to get property of non object and the column deleted_at in recommends table still showing null even if the product is deleted. How can I make the product disappear in recommends table after the product has been deleted and the view should display only the products which are not deleted?

Controller

  $recommends = Recommends::with('product')
    ->select('product_id', DB::raw('COUNT(*) AS total'))
    ->whereNotNull('product_id')
    ->groupBy('product_id')
    ->orderby('total', 'DESC')
    ->take(12)
    ->get();

Recommends.php

 <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Recommends extends Model
{
public function product()
{
    return $this->belongsTo('App\Product','product_id')
}
}

Product.php

 public function recommends()
 {
    return $this->hasMany('App\Recommends','product_id');
 }


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2N6mAXx
via IFTTT

Aucun commentaire:

Enregistrer un commentaire