mehrdad70

Member Since 2 Years Ago

Experience Points
6,010
Total
Experience

3,990 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
2
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

  • Community Pillar

    Earned once your experience points ranks in the top 10 of all Laracasts users.

Level 2
6,010 XP
Apr
19
3 weeks ago
Activity icon

Replied to Invalid Argument Supplied For Foreach()

[{"value":"test"},{"value":"test2"}]
Activity icon

Started a new Conversation Invalid Argument Supplied For Foreach()

hi , how i can fix this error ?

An error occurs when I want to display article tags The tag is stored in the database as Jason

                <ul class="list-unstyled">
                    @foreach ($article->tags as $tag)
                        @foreach(json_decode($tag->tag_name) as $value)
                        {{dd($value)}}
                            <li>
                                <a href="">
                                    {{$value->value}}
                                </a>
                            </li> 
                        @endforeach
                    @endforeach
                </ul>
        Schema::create('tags', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained('users')->onDelete('CASCADE');
            $table->string('name')->nullable();
            $table->timestamps();
        });
        Schema::create('article_tag', function (Blueprint $table) {
            $table->foreignId('article_id')->constrained('articles')->onDelete('CASCADE');
            $table->foreignId('tag_id')->constrained('tags')->onDelete('CASCADE');
        });
class Article extends Model
{
    use HasFactory;

    protected $guarded = [];

    public function tags()
    {
        return $this->belongsToMany(Tag::class);
    }

}
Activity icon

Started a new Conversation Information Filter In Laravel

Hi, I want to filter the inbox information, but I can't think of a query Based on the maximum amount deposited Based on payment time

class WalletChange extends Model
{
    use HasFactory;

    protected $table= 'wallet_changes';
    protected $guarded =[];
    
}
class FactorPayment extends Model
{
    use HasFactory;

    protected $guarded = [];

    static $types =[
        'naghdi' => 'نقدی',
        'check' => 'چک',
        'aghsat' => 'اقساط'
    ];

    public function getPrice()
    {
        return $this->price ? number_format($this->price) . 'تومان' : '---';
    }

    public function getTypeTitle()
    {
        try
        {
            return Self::$types[$this->type];
        }
        catch(Exception $e)
        {
            return 'نامشخص';
        }
    }

    public function isDoneTitle()
    {
        if($this->is_done == true)
        {
            return "<span class='badge badge-success'>تایید شده</span>";
        }else if($this->is_done == false)
        {
            return "<span class='badge badge-danger'>تایید نشده</span>";
        }
    }

    
}
class Factor extends Model
{
    use HasFactory;

    protected $guarded = [];


   
    public function wallets()
    {
        return $this->belongsTo(Wallet::class , 'wallet_id');
    }

    public function customers()
    {
        return $this->belongsTo(Customer::class , 'customer_id');
    }

    public function items()
    {
        return $this->hasMany(FactorItem::class , 'factor_id');
    }


    public function payments()
    {
        return $this->hasMany(FactorPayment::class , 'factor_id');
    }



}
class Wallet extends Model
{
    use HasFactory;
    protected $table = 'wallets';
    protected $guarded = [];

    public function factors()
    {
        return $this->belongsTo(Factor::class);
    }
    
    public function walletChanges()
    {
        return $this->hasMany(walletChange::class , 'wallet_id');
    }

}
Apr
07
1 month ago
Activity icon

Started a new Conversation Non-static Method App\User::hasPermissionTo() Should Not Be Called Statically

how i can fix this error

    public function teacherList()
    {
        $teachers = User::hasPermissionTo('teacher')->latest()->paginate(9);
        return view('front.users.teacher-list', compact('teachers'));
    }
Apr
04
1 month ago
Activity icon

Replied to Add New Column To Table Database

I have two tables that have the same rows: i want through the second table (using the form) Add a field to the first table

Activity icon

Started a new Conversation Add New Column To Table Database

hello how i can add new column to table users Without using migration and using form in laravel

Mar
16
1 month ago
Activity icon

Replied to Store Final Price Product In Cart

The price of three products in my cart is 742 without discount Two of the products have a discount and the price after the discount should be 524 and the final price field should be saved in the card, ie the new prices of the products should be added together in the basket

    public function getPriceAfterApplyCoupon()
    {
        foreach ($this->categories as $category) {
            $coupons = $category->validCoupons();
            if ($coupons->isNotEmpty()) {
                $amount = $this->price;
                $discount = ($amount * $coupons[0]->percent) / 100;
                $total = $amount - $discount;
                foreach ($this->carts as  $cart) {
                    $cart->coupon_id = $coupons[0]->id;
                    // $discountP = ($this->price * $cart->coupon->percent) / 100;
                    $final = $cart->total_price - $total;
                    $cart->final_price  = $final;
                    $cart->save();
                }

                return number_format($total);
            }

        }

        return $this->price;

    }````
What is your solution?
Activity icon

Replied to Store Final Price Product In Cart

It didn't work with the accessor I just want one thing to be done The new prices are added together after the discount in foreachand stored in the final price field on the card. The question is very simple.

Activity icon

Replied to Store Final Price Product In Cart

No, your solution did not work

Activity icon

Replied to Store Final Price Product In Cart

I do not have a field in the course table called the final price, I only have a price field and I have a final price in the field card table

Activity icon

Started a new Conversation Store Final Price Product In Cart

Hello I have three products in the cart with prices 260, 170 and 312 which add up to 742 And the amount of 742 is stored in the price field in the shopping cart

Of these three products, two products have discounts for categoy and their prices are 260, 93 and 171 and has changed and I want the final price to be stored in the shopping cart with the discount amounting to 524 in the final price field. What is the solution?

Course.php

    public function getPriceAfterApplyCoupon()
    {
        foreach ($this->categories as $category) {
            $coupons = $category->validCoupons();
            if ($coupons->isNotEmpty()) {
                $amount = $this->price;
                $discount = ($amount * $coupons[0]->percent) / 100;
                $total = $amount - $discount;
                foreach ($this->carts as  $cart) {
                    $cart->coupon_id = $coupons[0]->id;

                    //----------this line code not working-------------
                    $final = $cart->total_price - $total;
                    $cart->final_price  =  $total;
                    //---------------
                    
                    $cart->save();
                }

                return number_format($total);
            }

        }

        return $this->price;

    }

   public function coupons()
    {
        return $this->morphToMany(Coupon::class, 'couponable');
    }

    public function carts()
    {
        return $this->belongsToMany(Cart::class, 'cart_course', 'course_id', 'cart_id');
    }

Coupon.php

    public function carts()
    {
        return $this->hasMany(Cart::class);
    }

    public function categories()
    {
        return $this->morphedByMany(Category::class , 'couponable');
    }

    public function courses()
    {
        return $this->morphedByMany(Course::class , 'couponable');
    }

Cart.php

    public function coupon()
    {
        return $this->belongsTo(Coupon::class, 'coupon_id');
    }
    public function courses()
    {
        return $this->belongsToMany(Course::class);
    }
Mar
14
1 month ago
Activity icon

Replied to Sum Of Product Prices In The Shopping Cart

I have a collection of courses on my card Some of these courses are discounted Some others do not have a discount Now I want to add the prices of these courses together and save them in the final price field on the card

Activity icon

Replied to Sum Of Product Prices In The Shopping Cart

This is how my card table is structured

        Schema::create('carts', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained('users')->cascadeOnDelete();
            $table->foreignId('coupon_id')->nullable()->constrained('coupons')->cascadeOnDelete();
            $table->string('status');
            $table->integer('price')->default(0);
            $table->integer('final_price')->default(0);
            $table->dateTime('expired_at');
            $table->timestamps();
        });

        Schema::create('cart_course', function (Blueprint $table) {

            $table->foreignId('cart_id')->constrained('carts')->cascadeOnDelete();
            $table->foreignId('course_id')->constrained('courses')->cascadeOnDelete();
        });
Activity icon

Replied to Sum Of Product Prices In The Shopping Cart

    public function getPriceAfterApplyCoupon()
    {
        foreach ($this->categories as $category) {
            $coupons = $category->validCoupons();
            if ($coupons->isNotEmpty()) {
                $amount = $this->price;
                $discount = ($amount * $coupons[0]->percent) / 100;
                $total = $amount - $discount;
                foreach ($this->carts as  $cart) {
                    $cart->coupon_id = $coupons[0]->id;
                    //this code should working
                    $cart->final_price = $total;
                    $cart->save();
                }
                return number_format($cart->final_price);
            }
        }

        return $this->price;
    }
Activity icon

Replied to Sum Of Product Prices In The Shopping Cart

I refracted your code but it does not give the desired result This is my shopping cart collection

Illuminate\Support\Collection {#1829 ▼
  #items: array:3 [▼
    0 => App\Course {#1853 ▶}
    1 => App\Course {#1852 ▶}
    2 => App\Course {#1851 ▶}
  ]
}
Activity icon

Replied to Sum Of Product Prices In The Shopping Cart

Sorry, this did not work😢

Activity icon

Replied to Sum Of Product Prices In The Shopping Cart

one cart with multiple products

Activity icon

Replied to Sum Of Product Prices In The Shopping Cart

this not work I want to add prices together by deducting the discount price

Activity icon

Started a new Conversation Sum Of Product Prices In The Shopping Cart

Hi, I have some products in my cart I want the prices of all products together with the deduction of the discount amount together Sum and save in the final price field in the card table. How can this be done?

    public function getPriceAfterApplyCoupon()
    {
        foreach ($this->categories as $category) {
            $coupons = $category->validCoupons();
            if ($coupons->isNotEmpty()) {
                $amount = $this->price;
                $discount = ($amount * $coupons[0]->percent) / 100;
                $total = $amount - $discount;
                foreach ($this->carts as  $cart) {
                    $cart->coupon_id = $coupons[0]->id;
                    //this code not working
                    $cart->final_price  + $total;
                    $cart->save();
                }
                
                return number_format($total);
            }

        }

        return $this->price;

    }
Mar
10
2 months ago
Activity icon

Replied to Show Discounted Products

Do not have a solution?

Activity icon

Started a new Conversation Show Discounted Products

Hi, when a course related to a discount category has, I want it to be on the original strike price and show the discounted price, but this code puts it on the discounted courses and the non-discounted courses.

{{--The problem is from here--}}
                            <tr>
                                <td>total</td>
                                <td class="text-right font-weight-700">{{$cart->getPrice()}}  </td>
                            </tr>
                            <tr>
                                <td>discount percent</td>
                                <td class="text-right font-weight-700"><span class="text-danger mr-15">{{$cart->getDiscountPercent()}}%</span></td>
                            </tr>
                            <tr>
                                <td>discount amount</td>
                                <td class="text-right font-weight-700">{{number_format($cart->getDiscountAmount())}}  </td>
                            </tr>

                            <tr>
                                <th class="bt-1">final amount</th>
                                <th class="bt-1 text-right font-weight-900 font-size-18">{{number_format($cart->final_price)}} تومان</th>
                            </tr>
                        </tbody>

Course.php

public function getPriceAfterApplyCoupon()
    {
        foreach ($this->categories as $category) {
            $coupons = $category->validCoupons();
            if ($coupons->isNotEmpty()) {
                $amount = $this->price;
                $discount = ($amount * $coupons[0]->percent) / 100;
                $total = $amount - $discount;
                foreach ($this->carts as  $cart) {
                    $cart->coupon_id = $coupons[0]->id;
                    $discountP = ($this->price * $cart->coupon->percent) / 100; 
                    $final = $cart->total_price - $discountP;
                    $cart->final_price  = $final;
                    $cart->save();
                }
                
                return number_format($total);
            }

        }

        return $this->price;

}

 public function coupons()
    {
        return $this->morphToMany(Coupon::class, 'couponable');
    }

    public function carts()
    {
        return $this->belongsToMany(Cart::class, 'cart_course', 'course_id', 'cart_id');
    }

Cart.php

    public function coupon()
    {
        return $this->belongsTo(Coupon::class, 'coupon_id');
    }


    public function courses()
    {
        return $this->belongsToMany(Course::class);
    }

Coupon.php

    public function categories()
    {
        return $this->morphedByMany(Category::class , 'couponable');
    }

    public function courses()
    {
        return $this->morphedByMany(Course::class , 'couponable');
    }

    public function carts()
    {
        return $this->hasMany(Cart::class);
    }

cart table

        Schema::create('carts', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained('users')->cascadeOnDelete();
            $table->foreignId('coupon_id')->nullable()->constrained('coupons')->cascadeOnDelete();
            $table->string('status');
            $table->integer('total_price')->default(0);
            $table->integer('final_price')->default(0);
            $table->dateTime('expired_at');
            $table->timestamps();
        });

        Schema::create('cart_course', function (Blueprint $table) {

            $table->foreignId('cart_id')->constrained('carts')->cascadeOnDelete();
            $table->foreignId('course_id')->constrained('courses')->cascadeOnDelete();
        });
Mar
01
2 months ago
Activity icon

Replied to Discount For One Category

// This function is related to the discount to the category and the bug may be here
    public function getPriceAfterApplyCoupon()
    {
        foreach ($this->categories as $category) {
            $coupons = $category->validCoupons();
            if ($coupons->isNotEmpty()) {
                $amount = $this->price;
                $discount = ($amount * $coupons[0]->percent) / 100;
                $total = $amount - $discount;
                foreach ($this->carts as  $cart) {
                    $cart->coupon_id = $coupons[0]->id;
                    $cart->final_price  = $total;
                    $cart->save();
                    
                    if ($cart->coupon->expired_at < now()) {
                        $cart->coupon_id  = null;
                        $cart->final_price  = $cart->total_price;
                        $cart->save();
                        
                    }
                }


                return number_format($total);
            }
        }


        return $this->price;
    }
Activity icon

Replied to Discount For One Category

The problem is that when I add a product from a discounted category to the cart, the discounted price of the product is stored as a discount in the database and card table, and when the discount expires I want the price in the cart It will return to the previous price, but this will not happen

Activity icon

Started a new Conversation Discount For One Category

Hi, I want to give a discount to one category, and when the discount code expires, the price will return to normal on all site, but the price in the shopping cart will not return to normal and will remain discounted. What is the problem?

Coupon.php

class Coupon extends Model
{

    public function users()
    {
        return $this->morphedByMany(User::class , 'couponable');
    }

    public function categories()
    {
        return $this->morphedByMany(Category::class , 'couponable');
    }

    public function courses()
    {
        return $this->morphedByMany(Course::class , 'couponable');
    }



    public function userUsedCoupons()
    {
        return $this->belongsToMany(User::class , 'coupon_used');
    }

    public function carts()
    {
        return $this->hasMany(Cart::class);
    }
}

Course.php

class Course extends Model
{

    public function categories()
    {
        return $this->belongsToMany(Category::class);
    }

    public function coupons()
    {
        return $this->morphToMany(Coupon::class, 'couponable');
    }


    public function carts()
    {
        return $this->belongsToMany(Cart::class, 'cart_course', 'course_id', 'cart_id');
    }

// This function is related to the discount to the category and the bug may be here
    public function getPriceAfterApplyCoupon()
    {
        foreach ($this->categories as $category) {
            $coupons = $category->validCoupons();
            if ($coupons->isNotEmpty()) {
                $amount = $this->price;
                $discount = ($amount * $coupons[0]->percent) / 100;
                $total = $amount - $discount;
                foreach ($this->carts as  $cart) {
                    $cart->coupon_id = $coupons[0]->id;
                    $cart->final_price  = $total;
                    $cart->save();
                    
                    if ($cart->coupon->expired_at < now()) {
                        $cart->coupon_id  = null;
                        $cart->final_price  = $cart->total_price;
                        $cart->save();
                        
                    }
                }


                return number_format($total);
            }
        }


        return $this->price;
    }
}

Category.php

class Category extends Model
{

    public function courses()
    {
        return $this->belongsToMany(Course::class);
    }

    public function coupons()
    {
        return $this->morphToMany(Coupon::class , 'couponable');
    }


    public function validCoupons()
    {
        return $this->coupons->where('expired_at' , '>' , Carbon::now());
    }

}

Cart.php

class Cart extends Model
{
    protected $guarded = [];

    const Active = 'Active';

    public function courses()
    {
        return $this->belongsToMany(Course::class);
    }

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

    public function getPrice()
    {
        return number_format($this->total_price);
    }

    public function coupon()
    {
        return $this->belongsTo(Coupon::class, 'coupon_id');
    }

    public function getDiscountPercent()
    {
        return optional($this->coupon)->percent;
    }

    public function getDiscountAmount()
    {
        return ($this->coupon) ? ($this->total_price * $this->coupon->percent) / 100 : 0;
    
    }
    public function getFinalPrice()
    {
        return number_format($this->total_price - $this->getDiscountAmount());    
    }

 
}

Cart table

        Schema::create('carts', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained('users')->cascadeOnDelete();
            $table->foreignId('coupon_id')->nullable()->constrained('coupons')->cascadeOnDelete();
            $table->string('status');
            $table->integer('total_price')->default(0);
            $table->integer('final_price')->default(0);
            $table->dateTime('expired_at');
            $table->timestamps();
        });

        Schema::create('cart_course', function (Blueprint $table) {

            $table->foreignId('cart_id')->constrained('carts')->cascadeOnDelete();
            $table->foreignId('course_id')->constrained('courses')->cascadeOnDelete();
        });

Coupon table

    public function up()
    {
        Schema::create('coupons', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('code')->unique();
            $table->integer('percent');
            $table->bigInteger('limit')->nullable();
            $table->boolean('is_general')->default(0)->nullable();
            $table->unsignedInteger('quantity')->nullable();
            $table->enum('type'  , ['fixed' , 'percent'])->nullable();
            $table->enum('status'  , ['enable' , 'disable'])->default('disable');
            $table->text('description')->nullable();
            $table->dateTime('start_at');
            $table->dateTime('expired_at');
            $table->timestamps();
        });

        Schema::create('couponables', function (Blueprint $table) {
            $table->foreignId('coupon_id')->constrained('coupons')->cascadeOnDelete();
            $table->integer('couponable_id');
            $table->string('couponable_type');
        });
        
        Schema::create('coupon_used', function (Blueprint $table) {
            $table->foreignId('coupon_id')->constrained('coupons')->cascadeOnDelete();
            $table->foreignId('user_id')->constrained('users')->cascadeOnDelete();
        });
    }

Category table

        Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('parent_id')->nullable();
            $table->string('name');
            $table->string('slug');
            $table->longText('body')->nullable();
            $table->enum('status' , ['accept' , 'reject' , 'pending'])->default('pending');
            $table->foreign('parent_id')->references('id')->on('categories')->onDelete('SET NULL');
            $table->timestamps();
        });
Feb
25
2 months ago
Activity icon

Replied to Display The Number Of Orders For Each Product

hey no , In one order from a product has ordered a few

Activity icon

Replied to Display The Number Of Orders For Each Product

I made a typo in this question

This relationship is related to order table

    public function orders()
    {
        return $this->belongsToMany(Order::class);
    }

This relationship is related to order_items table

    public function orderProducts()
    {
        return $this->belongsToMany(Order::class ,'order_items');
    }
Activity icon

Started a new Conversation Display The Number Of Orders For Each Product

Hi, I want to display the product that the user has ordered in any number on the orders page. What is your solution?

Order.php

class Order extends Model
{


    public function products()
    {
        return $this->belongsToMany(Product::class, "order_items");
    }
    public function cart()
    {
        return $this->belongsTo(Cart::class);
    }
    public function orderItems()
    {
        return $this->belongsToMany(Product::class, 'order_items');
    }

}

Cart.php

class Cart extends Model
{
    public function payment()
    {
        return $this->belongsTo(Payment::class);
    }
    public function order()
    {
        return $this->belongsTo(Order::class);
    }
}

Product.php

class Product extends Model
{
    public function carts()
    {
        return $this->belongsToMany(Cart::class ,'cart_products');
    }
    public function cartProducts()
    {
        return $this->belongsTomany(Cart::class , 'cart_products');
    }

    public function orders()
    {
        return $this->belongsToMany(Order::class ,'order_items');
    }

    public function orderProducts()
    {
        return $this->belongsToMany(Order::class ,'order_items');
    }

}

order_items table

        Schema::create('order_items', function (Blueprint $table) {
            $table->foreignId('product_id')->constrained()->cascadeOnDelete();
            $table->foreignId('order_id')->constrained()->cascadeOnDelete();

        });

cart_product table

Schema::create('cart_products', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('product_id');
            $table->unsignedBigInteger('cart_id');
            $table->integer('count')->default('0');
            $table->integer('price');
            $table->integer('total_price');
            $table->timestamps();
            $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
            $table->foreign('cart_id')->references('id')->on('carts')->onDelete('cascade');
        });

index.blade

    @foreach($order->products as $product)
        <tr role="row" class="">
            <td>{{$product->title}}</td>
            <td>{{$product->price}}</td>
            <td>0</td> // this td 
            <td>{{ number_format($order->total_price) }}</td>
        </tr>
    @endforeach
Feb
21
2 months ago
Activity icon

Started a new Conversation The Best Course To Learn JavaScript

Hi everyone Please provide me with a complete tutorial for learning JavaScript from basic to advanced level

Feb
20
2 months ago
Activity icon

Replied to The Best-selling Products In Laravel

Can anyone give me a good solution?

Activity icon

Replied to The Best-selling Products In Laravel

This solution did not solve the problem):

Activity icon

Replied to The Best-selling Products In Laravel

yes Training courses

Activity icon

Started a new Conversation The Best-selling Products In Laravel

Hello friends I want to show the best selling products How can I implement this?

order model

class Order extends Model
{

    public function courses()
    {
        return $this->belongsToMany(Course::class, 'order_course', 'order_id', 'course_id');
    }

    public function payments()
    {
        return $this->hasMany(Payment::class);
    }

}

course model

class Course extends Model
{

    public function students()
    {
        return $this->belongsToMany(User::class , 'course_user' , 'course_id' , 'user_id');
    }

    public function orders()
    {
        return $this->belongsToMany(Order::class);
    }


    public function addStudentToCourses($courses , $userId)
    {
        foreach($courses as $course) {
            if(! $this->getCourseUser($course , $userId)){
                $course->students()->attach($userId);
            }
        }
    }

    public function getCourseUser(Course $course , $userId)
    {
        return $course->students()->where('id' , $userId)->first();
    }


}

order table

    public function up()
    {
        Schema::create('orders', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained('users')->cascadeOnDelete();
            $table->string('code')->nullable()->unique();
            $table->bigInteger('price');
            $table->enum('status' , ['fail'  ,'success' , 'pending' , 'canseled']);
            $table->timestamps();
        });

        Schema::create('order_course', function (Blueprint $table) {
            $table->foreignId('order_id')->constrained('orders')->cascadeOnDelete();
            $table->foreignId('course_id')->constrained('courses')->cascadeOnDelete();

        });
    }
Feb
18
2 months ago
Activity icon

Started a new Conversation Like And Dislike Using Ajax In Laravel

Hi, I want the color of the icon to change when I like or dislike and add a number to the number of likes or dislikes. What is your solution?

  $("#disliked").click(function (event) {
    event.preventDefault();
    let article_id = $(this).data("articleId");
    let user_id = $(this).data("userId");
    $.ajax({
      method: "get",
      url : "{{route('courses.likes.destroy' , $course->id)}}",
      data:{
        'user_id': user_id,
        'article_id': article_id,
      },  

      success : function(response) {
        if (response.status == 'success') {
          Swal.fire({
              toast: true,
              position: 'bottom-end',
              showConfirmButton: false,
              timer: 5000,
              animation:true,
              showCloseButton: true,
              icon: 'success',
              title: response.message
          });
        }
      },

      fail: function(response) {
        Swal.fire({
              toast: true,
              position: 'bottom-end',
              showConfirmButton: false,
              timer: 5000,
              animation:true,
              showCloseButton: true,
              icon: 'error',
              title: response.message
          });
      }       
    })
  })
    $("#liked").click(function (event) {
    event.preventDefault();
    let article_id = $(this).data("articleId");
    let user_id = $(this).data("userId");
    $.ajax({
      method: "get",
      url : "{{route('courses.likes.store' , $course->id)}}",
      data:{
        'user_id': user_id,
        'article_id': article_id,
      },  

      success : function(response) {
        if (response.status == 'success') {
          Swal.fire({
              toast: true,
              position: 'bottom-end',
              showConfirmButton: false,
              timer: 5000,
              animation:true,
              showCloseButton: true,
              icon: 'success',
              title: response.message
          });
        }
      },

      fail: function(response) {
        Swal.fire({
              toast: true,
              position: 'bottom-end',
              showConfirmButton: false,
              timer: 5000,
              animation:true,
              showCloseButton: true,
              icon: 'error',
              title: response.message
          });
      }       
    })
  })
              <div class="d-flex align-items-center ml-12">
                <a href="#" id="liked">
                    <i class="fa fa-thumbs-up {{auth()->check() && $course->isLikedBy(auth()->user()) ? 'text-blue' : 'text-gray'}}">
                    </i>
                  </a>
                  <span class="ml-2" >{{$course->likes()->where('liked' , 1)->count() ?: '0'}}</span>
              </div>


              <div class="d-flex align-items-center ml-12" data-userId="{{auth()->id()}}" data-articleId="{{$course->id}}">
                <a href="#" id="disliked" data-userId="{{auth()->id()}}" data-articleId="{{$course->id}}">
                    <i class="fa fa-thumbs-down {{auth()->check() && $course->isDisLikedBy(auth()->user()) ? 'text-blue' : 'text-gray'}}"></i>
                  </a>
                  <span class="ml-2">{{$course->likes()->where('liked' , 0)->count() ?: '0'}}</span>
              </div>
    public function courseStoreLike(Course $course)
    {
        try {
            $course->like(auth()->user());
            return response()->json(['status' => 'success', 'message' => 'پسندیده شد']);
        } catch (\Exception $e) {
            return $this->getMessage();
        }
    }

    public function courseDestroyLike(Course $course)
    {
        try {
            $course->dislike(auth()->user());
            return response()->json(['status' => 'success', 'message' => 'پسندیده نشد']);
        } catch (\Exception $e) {
            return $this->getMessage();
        }
    }
Feb
17
2 months ago
Activity icon

Replied to Add Courses To Favorites In Laravel

You have no solution?

Activity icon

Replied to Add Courses To Favorites In Laravel

The goal is if the user clicks on a course interest If the course was already on his favorites: receive a message stating that this course is already in your favorites If the course was not on his list of favorites: the course was successfully added to his favorites

Activity icon

Started a new Conversation Add Courses To Favorites In Laravel

Hi, I would like to add one or more courses to my favorites list Ajax method But this code does not work and I do not know how to send user_id and course_id to script code via tag a Does anyone have a solution?

        Schema::create('favorites', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained('users')->cascadeOnDelete();
            $table->foreignId('course_id')->constrained('courses')->cascadeOnDelete();
            $table->timestamps();
        });

Favorite Controller

    public function addFavoriteCourse(Course $course)
    {
        if (auth()->check()) {
            if (!$this->isValidFavoriteCourse($course)) {
                auth()->user()->favoriteCourses()->attach($course);

                return response()->json(['status' => 'success', 'message' => 'The course was successfully added to your favorites']);

            } else {
                return response()->json(['status' => 'error', 'message' => 'The desired period is already in the favorites list']);
            }
        }

        toast('To add a course to your favorites list, you must first login', 'error');
        return back();
    }

    public function isValidFavoriteCourse($course)
    {
        return auth()->user()->favoriteCourses()
                ->where('course_id' , $course->id)
                ->where('user_id' , auth()->id())
                ->exists();
    }
            <div class="d-flex align-items-center ml-12">
                <a href="#" id="favorite"><i class="fa fa-heart text-danger mr-5" title="" data-toggle="tooltip" data-original-title="add to favorites list"></i></a>
            </div>
  @section('js')
      <script>
        $("#favorite").click(function (event , userId , courseId) {
          event.preventDefault();
          let use_id = userId;
          let course_id = courseId;

          $.ajax({
            method: "get",
            url : "{{route('favorites.courses' , $course->id)}}",
            data:{
              'user_id': userId,
              'course_id': course_id
            },  

            success : function(response) {
              if (response.error == 'success') {
                Swal.fire({
                    toast: true,
                    position: 'bottom-end',
                    showConfirmButton: false,
                    timer: 5000,
                    animation:true,
                    showCloseButton: true,
                    icon: 'success',
                    title: 'The course was successfully added to your favorites'
                });
              }
            },

            fail: function(response) {
              if (response.error == 'error') {
                Swal.fire({
                    toast: true,
                    position: 'bottom-end',
                    showConfirmButton: false,
                    timer: 5000,
                    animation:true,
                    showCloseButton: true,
                    icon: 'error',
                    title: 'The desired period is already in the favorites list '
                });
              }
            }       
          })
        })
      </script>
  @endsection
Feb
16
2 months ago
Activity icon

Replied to Argument 1 Passed To App\Jobs\SendEmail::__construct() Must Be An Instance Of App\User, String Given,

I am a beginner programmer. What do you think can be done to fix this error?

Activity icon

Replied to Argument 1 Passed To App\Jobs\SendEmail::__construct() Must Be An Instance Of App\User, String Given,

I got another error

Argument 2 passed to App\Jobs\SendEmail::__construct() must be an instance of Illuminate\Mail\Mailable, instance of App\Ticket given, called in G:\learning\vendor\laravel\framework\src\Illuminate\Foundation\Bus\Dispatchable.php on line 17 
class EmailProvider implements providerContract
{
    private $user;
    private $mailable;

    public function __construct(User $user , Mailable $mailable)
    {
        $this->user = $user;
        $this->mailable = $mailable;
    }

    public function send()
    {
        return Mail::to($this->user->email)->send($this->mailable); // add ->email
    }
}
    public function reply(Ticket $ticket,  ReplyRequest $request)
    {
        $this->authorize('replyTicket' , $ticket);

        $reply = auth()->user()->replies()->create([
            'message' => $request->message,
            'ticket_id' => $ticket->id,
        ]);
        
        SendEmail::dispatch($ticket->user , $reply->ticket);
        
        event(new ReplyTicket($reply , auth()->user()));
        Alert::success('موفقیت آمیز', 'پاسخ با موفقیت ارسال شد', 'success')
            ->showConfirmButton($btnText = 'بسیار خوب', $btnColor = '#3085d6')
            ->autoClose($milliseconds = 4000);

        return back();
    }
class SendEmail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private $user;
    private $mailable;

    public function __construct(User $user , Mailable $mailable)
    {
        $this->user = $user;
        $this->mailable = $mailable;
    }

    public function handle(Notification $notification)
    {

        return $notification->sendEmail($this->user , $this->mailable);
    }
}
Activity icon

Started a new Conversation Argument 1 Passed To App\Jobs\SendEmail::__construct() Must Be An Instance Of App\User, String Given,

Hi, I want to send a notification email to the user when I reply to the ticket, but I get the following error

Argument 1 passed to App\Jobs\SendEmail::__construct() must be an instance of App\User, string given, called in G:\learning\vendor\laravel\framework\src\Illuminate\Foundation\Bus\Dispatchable.php on line 17 

TicketController

    public function reply(Ticket $ticket,  ReplyRequest $request)
    {
        $this->authorize('replyTicket' , $ticket);

        $reply = auth()->user()->replies()->create([
            'message' => $request->message,
            'ticket_id' => $ticket->id,
        ]);
        
	//this line has error
        SendEmail::dispatch($ticket->user->email , $reply->ticket);
        
        event(new ReplyTicket($reply , auth()->user()));
        Alert::success('موفقیت آمیز', 'پاسخ با موفقیت ارسال شد', 'success')
            ->showConfirmButton($btnText = 'بسیار خوب', $btnColor = '#3085d6')
            ->autoClose($milliseconds = 4000);

        return back();
    }

SendEmail Job

class SendEmail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private $user;
    private $mailable;

    public function __construct(User $user , Mailable $mailable)
    {
        $this->user = $user;
        $this->mailable = $mailable;
    }

    public function handle(Notification $notification)
    {
        return $notification->sendEmail($this->user , $this->mailable);
    }
}

Notification Service

class Notification
{
    public function sendEmail(User  $user , Mailable $mailable)
    {
        $emailPrivider = new EmailProvider($user , $mailable);
        return $emailPrivider->send($user , $mailable);
    }
}


class EmailProvider implements providerContract
{
    private $user;
    private $mailable;

    public function __construct(User $user , Mailable $mailable)
    {
        $this->user = $user;
        $this->mailable = $mailable;
    }

    public function send()
    {
        return Mail::to($this->user)->send($this->mailable);
    }
}
Feb
14
2 months ago
Activity icon

Started a new Conversation Send Email To Laravel

Hi, I want to send a notification email to the user when I reply to the user ticket. What is the solution?

Feb
13
2 months ago
Activity icon

Replied to Implement A Star Rating System In Laravel

Is this using a package? I want to implement this without using the package, do you suggest another way?

Activity icon

Started a new Conversation Implement A Star Rating System In Laravel

Hi everyone I want to implement a star rating system for my products, but I do not have the experience to do so. Training for this topic, if any, please give me the link. Thank you.

Feb
12
2 months ago
Activity icon

Started a new Conversation SQLSTATE[42S22]: Column Not Found: 1054 Unknown Column 'available' In 'order Clause' (SQL: Select * From Products Order By Available Desc)

Hi, I want to filter my products based on the available and unavailable fields, but it gives me an error

public function scopeFilter($query)
    {
        if(request('status') ==  'available'){
            $query->orderBy('available' , 'DESC')->get();
        }

    }
Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('seller_id')->unsigned();
            $table->unsignedBigInteger('category_id')->unsigned()->nullable();

            $table->string('image')->nullable();
            $table->string('title')->unique();
            $table->string('meta_description');
            $table->string('slug');
            $table->float('priority')->unique();
            $table->string('price',10);
            $table->string('seller_share', 5);
            $table->integer('stock');
            $table->string('code_product')->unique();
            $table->enum('status', ['available' , 'unavailable']);
            $table->longText('body')->nullable();
            $table->timestamps();

            $table->foreign('category_id')->references('id')->on('categories')->onDelete('SET NULL');
            $table->foreign('seller_id')->references('id')->on('users')->onDelete('CASCADE');


        });
<select name="status" id="" class="box__title">
            <option value="">filter by available</option>
                <option value="available">available</option>
               <option value="unavailable">unavailable</option>
        </select>
Feb
11
3 months ago
Activity icon

Started a new Conversation Trying To Get Property 'firstBackground' Of Non-object

Hello everyone, when I have no record in the settings table, I want to set a default image as a background, but when the record is saved in the settings table, I want that data to be called. But I get the following error

<section class="bg-img pt-150 pb-20" data-overlay="7" @if(\App\Setting::first()->firstBackground) style="background-image: url({{'/storage/' . \App\Setting::first()->firstBackground}});"@else style="background-image: url(/images/alexandru-acea-XEB8y0nRRP4-unsplash);" @endif>

</section>
Feb
10
3 months ago
Activity icon

Replied to Add Product To Favorites

Can you explain more? Please

Activity icon

Replied to Add Product To Favorites

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'course_id' in 'field list' (SQL: insert into `courses` (`course_id`, `updated_at`, `created_at`) values (2, 2021-02-10 13:28:34, 2021-02-10 13:28:34))

                auth()->user()->favoriteCourses()->create([
                    'course_id' => $course->id
                ]);
    public function usersThatFavored()
    {
        return $this->belongsToMany(User::class , 'favorites');
    }
    public function favoriteCourses()
    {
        return $this->belongsToMany(Course::class , 'favorites');
    }
Activity icon

Replied to Add Product To Favorites

I want it to not be possible for the course to be added to the favorites list twice by the user

user_id        course_id
2              1 
2              1 
2              3
Activity icon

Replied to Add Product To Favorites

Well, now I have changed the relationship. The problem still persists. My problem is in this section. How can I fix this?

    public function addFavoriteCourse(Course $course)
    {
        if (auth()->check()) {

				//This condition does not apply
            if (in_array(auth()->user()->favorites ,$course->favorites)) {
                auth()->user()->favorites()->create([
                    'course_id' => $course->id
                ]);
                toast('The course was successfully added to your list of favorite courses', 'success');
                return back();
            } else {
                toast('There are already courses in your favorites', 'error');
            }
        }
        toast('To add to your favorites list, you must first login', 'error');
        return back();
    }
Activity icon

Replied to Add Product To Favorites

Each user can have multiple courses and each course belongs to one user I already have this relationship in user and course models My problem now is that the user will not be able to add a course to their favorites twice and save a duplicate record in the database.