dimanche 16 mai 2021

Return top 3 grouped results from relationship

I have a table, comments, that looks like this:

+====+=========+
| id | message |
+====+=========+
|  1 |      Hi |
|  2 |   World |
+====+=========+

I have a second table, comment_stats, which keeps track of the total number of votes on each comment, that looks like this:

+====+============+=======+
| id | comment_id | votes |
+====+============+=======+
|  1 |          1 |    10 |
|  2 |          2 |     0 |
+====+============+=======+

And lastly, I have a third table, comment_votes, which keeps track of each individual user's vote for each comment, that looks like this:

+====+============+=========+=========+
| id | comment_id | user_id |    type |
+====+============+=========+=========+
|  1 |          1 |      10 |       0 |
|  2 |          1 |       9 |       0 |
|  3 |          1 |       8 |       1 |
|  4 |          1 |       7 |       2 |
|  5 |          1 |       6 |       1 |
|  6 |          1 |       5 |       5 |
|  7 |          1 |       4 |       3 |
|  8 |          1 |       3 |       3 |
|  9 |          1 |       2 |       1 |
| 10 |          1 |       1 |       0 |
+====+============+=========+=========+

As you can see, each comment can be voted on by other users (comment_votes) and the total votes are kept track of in comment_stats. Each vote has a type. There are a total of 6 possible types (0-5).

My current Comment.php class looks like:

class Comment extends Model
{
    protected $with = [
        'votes', 'stats'
    ];

    public function votes()
    {
        return $this->hasMany('App\Vote');
    }

    public function stats()
    {
        return $this->hasOne('App\Stat');
    }
}

My Stat.php class looks like:

class Stat extends Model
{
    protected $with = [
        'topTypes'
    ];

    public function comment()
    {
        return $this->belongsTo('App\Comment');
    }

    public function topTypes()
    {
        // Need to return an array of the top 3 types here
    }
}

And my Vote.php class looks like:

class Vote extends Model
{
    public function comment()
    {
        return $this->belongsTo('App\Comment');
    }
}

I'd like to retrieve the top 3 types for each comment. So for comment_id = 1, the output would be [0, 1, 3] (as an array), in that order. 0 appears 3 times, 1 appears 3 times, and 3 appears twice. If there is a tie, it should get the lower integer type.

I'm trying to get the JSON to end up looking something like this, so that the top_types is part of stats:

{
    "id": 1,
    "message": "Hi",
    "stats": {
        "id": 1,
        "comment_id": 1,
        "votes": 10,
        "top_types": [0, 1, 3]
    }
}

How could I achieve this? All of these relationships are driving me insane.



via Chebli Mohamed

i need pagination with sortBy in laravel

I have 3 tables products, prices, cats.

I need to filter product by cats and sort by price but I have a problem:

this code work very well but needs pagination.

$products = Product::with('photo', 'price', 'brand')
    ->whereHas('cats', function ($q) use ($cat) {
        $q->where('cat_id', $cat->id);
    })
    ->get()
    ->sortByDesc(function($query) {
        return $query->price->price;
    });

at first I did it like this:

$products = Product::with('photo', 'price', 'brand')
    ->whereHas('cats', function ($q) use ($cat) {
        $q->where('cat_id', $cat->id);
    })
    ->paginate($page)
    ->sortByDesc(function ($query) {
        return $query->price->price;
    });

but links() did not work.

After i did it like this:

$products = Product::with('photo', 'price', 'brand')
    ->whereHas('cats', function ($q) use ($cat){
        $q->where('cat_id', $cat->id);
    })
    ->paginate($page);

$products->setCollection(
    $products->sortBy(function ($query) {
        return $query->price->id;
    })
);

but sortBy does not work.

so I can't use orderBy() by join prices table

because when I do it I can show all products and I can't filter product by categories

my mind does not work, if someone can to help me, I will be very grateful



via Chebli Mohamed

I always get this error Trying to get property 'nama_lengkap' of non-object

index.blade.php

                <td class="sorting_1" style=""></td>
                <td></td>

TicketController

 public function index(Request $request)
    {
        $data = Ticket::with('User','Kategori','Prioritas','Status')->when($request->keyword, function ($query) use ($request) 
        {
            $query->where('judul', 'like', "%{$request->keyword}%");
            })->paginate(5); 
            $data->appends($request->only('keyword'));

            
            return view('admin.crud_ticket.index', compact('data'));         
        }

model Ticket

public function user()
    {
        return $this->belongsTo(User::class);
    }

model User

public function ticket()
    {
        return $this->hasMany(Ticket::class);
    }

if you have a solution to the problem that i am experiencing please help me



via Chebli Mohamed

PHP small api based task

I want to perform small task like when you search for a vendor and in your area within the range of 1km it will show 10 vendors and if 2 of these will change a place then it will show only 8 vendors and while other 2 added another place so whole these things I want to perform in PHP and used API for tracking purpose and I want to use tower tracker for tracking so how I can I do this so anyone can suggest me for this



via Chebli Mohamed

How to send array variable in laravel mail template?

$carts= Cart::leftjoin('products', 'products.id', '=', 'carts.productid')
    ->leftjoin('sellers', 'sellers.id', '=', 'products.seller')
    ->select('products.*','carts.productid as productid','carts.userid as userid','carts.quantity as cartquantity','carts.subtotal as subtotal','carts.id as cartid','sellers.id as sellerid')->where('carts.userid',$_SESSION['salmonlightsuserid'])->get();
$data1 = array('carts'=>"$carts",'subtotal'=>"$subtotal",'totalquantity'=>"$totalquantity",'primaryaddress'=>"$primaryaddress");
    $useremail=$_SESSION['salmonlightsuseremail'];

     Mail::send('order-email-template',$data1, function($message) use($useremail){
     $message->to($useremail)->subject
         ('Order');
     $message->from('noreply@gamil.com');
     });

It gives error in order-email-template.blade.php Error is:- Invalid argument supplied for foreach() @foreach($carts as $cartsnew)



via Chebli Mohamed

How do I convert my submitted form uploads as one pdf and send that as an attachment to receiver in laravel?

A Laravel 5.7 project

I have a form where I need to upload 3 images and 2 pdfs in single form.

What I am going for:

  1. Submit the form and save data.
  2. Convert the files uploaded via the user form as a single pdf.
  3. Sending the converted pdf as a mail attachment using code.

Tried like this

public function sendmail(Request $request){
        $data["email"]=$request->get("email");
        $data["client_name"]=$request->get("client_name");
        $data["subject"]=$request->get("subject");

        $pdf = PDF::loadView('mails.mail', $data);

        try{
            Mail::send('mails.mail', $data, function($message)use($data,$pdf) {
            $message->to($data["email"], $data["client_name"])
            ->subject($data["subject"])
            ->attachData($pdf->output(), "invoice.pdf");
            });
        }catch(JWTException $exception){
            $this->serverstatuscode = "0";
            $this->serverstatusdes = $exception->getMessage();
        }
        if (Mail::failures()) {
             $this->statusdesc  =   "Error sending mail";
             $this->statuscode  =   "0";

        }else{

           $this->statusdesc  =   "Message sent Succesfully";
           $this->statuscode  =   "1";
        }
        return response()->json(compact('this'));
 }


via Chebli Mohamed

Cannot upload project in public_html directory

I have a shared hosting i have created test_project folder inside public_html directory, when i access it through url i'm getting

enter image description here

myurl is like :

https://maindomain.com/testproject/,

Any help is highly appreciated.



via Chebli Mohamed