dimanche 1 août 2021

Count data slow use relationship in laravel?

$user = User::select(['id', 'name'])
            ->withCount([
                'posts as success' => function ($query) {
                    $query->where('status', 0);
                },
                'posts as error' => function ($query) {
                    $query->whereIn('status', [1, 2, 3]);
                },
            ])                
            ->where('order', 3)
            ->get();

Model Post.php :

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

Model User.php :

public function posts()
    {
        return $this->hasMany(Post::class);
    }

I want to count status in post table through relationship. Like the above code, I got the result I wanted. But it is very slow, about 10 seconds or more. Is there any way to fix it. My post table has 400,000 data



via Chebli Mohamed

@csrf not working on cpanel in laravel 7.x

Hi all developers I have some problem with @csrf in laravel 7.x , Every thing in my local I can submit data from form normally buy when I upload my project to cpanel sometime @csrf work and sometime it is not work and show error message page expired 419 , If you all know about this error please help to share me.

Thank you

Lab



via Chebli Mohamed

How to redirect // in Laravel 5.7?

Older version of laravel here, 5.7. I have a situation where I have a url like this http://127.0.0.1:8000//

I have a catch all of this

Route::get('{uri}', ['uses'=>'PageController@render'])->where('uri', '(.*)');

The URL that comes into the render method is ''. I'm not quite sure the best way to take http://127.0.0.1:8000// and redirect that to http://127.0.0.1:8000.

.htaccess doesn't seem to let me redirect that either with Redirect 301 // / or RewriteRule ^$ /? [L,R=301]

Is there any way to get around this?

thanks!



via Chebli Mohamed

Relationship laravel : count data

Model Category:

    public function product()
    {
        return $this->hasMany(products::class);
    }

Model product:

    public function category()
    {
        return $this->belongsTo(Category::class);
    }

I handle in controller:

$result = Category::select(['id', 'name'])
            ->with(['product:category_id, status'])
            ->where('order', 1)
            ->get();

Result when I print out raw data :

[
  'id' => 1,
  'name' => 'Hot'
  'product' => [
     'status' => 1,
     'category_id' => 1
   ]
]
[
   'id' => 2,
   'name' => 'New'
   'product' => [
      'status' => 2,
      'category_id' => 2
   ]
]
..........

I got the list of category id and name, and got the product data array based on relationship. In my product table, There is a status column with values ​​equal to 1,2,3.

Now I want to count how many status = 1 and how many status = [2, 3] through the product array I get using that relationship?



via Chebli Mohamed

file_get_contents($url): failed to open stream: HTTP request failed! HTTP/1.1 401

Trying something like

$url = $this->getValue($item, ['manufacturingReadyDataUrl'], null);
$file = file_get_contents($url);
Storage::put('file.pdf', $file);

In Laravel. But failed to get and download the file.

The URL require GET method.

Encounter message:

file_get_contents($url): failed to open stream: HTTP request failed! HTTP/1.1 401 Unauthorized

The reason for this is because it require Bearer token.

Trying to find similar implementation on Laravel, but always found how to implement passport, create a download function, but not how to download file from link that require bearer token.

Any idea how?



via Chebli Mohamed

How to count data use relationship in laravel?

Table user example :

id | name | status | first_name | last_name | create_at

Table post example :

id | title | name | description | user_id | create_at

In model user:

public function posts()
{
    return $this->hasMany(Post::class);
}

In model post:

public function users()
{
    return $this->belongsTo(Users::class);
}

In the post table database, there is a status column with three values ​​of 1, 2, 3, now I want to count how many status = 1, and how many status = 2, 3

I have two ways to handle that is to use a relationship or call the post model to handle it In UserController.php:

// The best way to try is relationship
    $user = User::select(['id', 'name'])
              ->with(['posts:user_id'])
              ->where('type', 2)
              ->get();

Or:

$user = User::select(['id', 'name'])
          ->where('type', 2)
          ->get();
    foreach ($user as $val) {
      $statusPublic[] = Posts::where('user_id', $val['id'])->where('status', '=', 1)->count();
      $statusPrivate[] = Posts::where('user_id', $val['id'])->whereIn('status', [2, 3])->count();
    }

My problem is that in the posts table it has 300,000 items . If you handle the status count like that, it's very slow. Sometimes up to 20s. Is there any way to improve? Thanks



via Chebli Mohamed

check if record exist through relation in laravel

I have Product table:

id | title | price | user_id

Menu Planner Table:

id | day | category_id | product_id | user_id

Product Model:

class Product extends Model
{
    public function menuplanner()
    {
        return $this->belongsTo(MenuPlanner::class);
    }
    public function check($Catid,$productID,$userID,$day)
    {
        return $this->menuplanner()->select('product_id')->where('product_id', '=', $productID)->where('user_id', '=', $userID)->where('day', '=', $day)->first();
    }
}

MenuPlanner Model:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class MenuPlanner extends Model
{
    public function products()
    {
        return $this->hasMany('App\Models\Product');
    }
}

In Controller

$product = Product::where(['user_id'=>$ID])->get();
$menuPlanner=MenuPlanner::where(['user_id'=>auth()->user()->id,'category_id'=>$categoryID])->get(); 
$html =  view('frontend.available_items', ['products'=>$product,'day'=>$day,'partnerID'=>$partnerID,'categoryID'=>$categoryID,'menu_planner'=>$menuPlanner,'user_id'=>auth()->user()->id)->render();
echo json_encode(array('products' => $html)); 

Issue is in my view

i want to show all products that are returned from controller but want to replace button if product already exist in menuPlanner for that specific user, for that i'm using if($rowProducts->check($categoryID,$rowProducts->id,$user_id,$day)) condition

@foreach($products as $key=>$rowProducts)
if($rowProducts->check($categoryID,$rowProducts->id,$user_id,$day))

but this condition always return NULL.



via Chebli Mohamed