mehrdad70

Member Since 1 Year Ago

Experience Points
5,440
Total
Experience

4,560 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
5,440 XP
Feb
25
14 hours 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
4 days 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
5 days 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
1 week 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
1 week 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
1 week 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
1 week 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
1 week 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
1 week 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
2 weeks 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
2 weeks 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.

Activity icon

Replied to Add Product To Favorites

Yes, I also want the user to have a set of favorite courses, but I do not want the user to add the same course to his favorites list many times and enter a duplicate record in the database.

Activity icon

Started a new Conversation Add Product To Favorites

Hi everyone I want to add my desired product to my favorites list And the second time, if I want to add the same product to my favorites list, it will show me a message stating that the product is already in the list. But this condition does not work for me

        Schema::create('favorites', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained('users')->cascadeOnDelete();
            $table->foreignId('course_id')->constrained('courses')->cascadeOnDelete();
            $table->timestamps();
        });
class Favorite extends Model
{
    protected $fillable = ['user_id' , 'course_id'];

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

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

Course Model

    public function favorites()
    {
        return $this->belongsToMany(Favorite::class);
    }

User Model

  public function favorites()
    {
        return $this->hasMany(Favorite::class);
    }

favorite controller

    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();
    }
Feb
07
2 weeks ago
Activity icon

Replied to Many To Many Relationship

thanks martinbean

Activity icon

Started a new Conversation Many To Many Relationship

Hi everyone I have a table called the course and I also have a user table Now users who buy the course user_id and course_id are stored in the course_user table The relationship between the course and the user is many to many Now what query can I make so that the user's purchased courses are logged in and visible in the user panel?

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

            $table->foreignId('user_id');
            $table->foreignId('course_id');

            $table->timestamps();
            $table->primary(['user_id' , 'course_id']);

            $table->foreign('user_id')->references('id')->on('users')->onDelete('CASCADE');
            $table->foreign('course_id')->references('id')->on('courses')->onDelete('CASCADE');

        });

Course.php

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

User.php

    public function purchases()
    {
        return $this->belongsToMany(Course::class , 'course_user' , 'user_id' , 'course_id');
    }
    public function myCourses()
    {
        $courses = Course::with('students')->get();
        $courses->students->contains(auth()->id());

        return view('front.users.my-courses', ['courses' => $courses]);
    }
                            @foreach ($courses as $course)
                            <tr>										
                                <td>
                                    <div class="d-flex align-items-center">
                                        <div class="flex-shrink-0 mr-20">
                                            <div class="bg-img h-50 w-50" style="background-image: url(../images/front-end-img/courses/1.jpg)"></div>
                                        </div>

                                        <div>
                                            <a href="#" class="text-dark font-weight-600 hover-primary mb-1 font-size-16">{{$course->title}}</a>
                                            <span class="text-fade d-block">{{$course->price}}</span>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    Programming
                                </td>
                                <td>
                                    k
                                </td>
                                <td>
                                    Sophia Pharetra
                                </td>
                                <td>
                                    <span class="badge badge-success badge-lg">Approved</span>
                                </td>
                                <td>
                                    <div class="d-flex justify-content-end gap-items-1">
                                        <a href="#" class="waves-effect waves-light btn btn-primary btn-xs btn-circle"><span class="icon-Bookmark"></span></a>
                                        <a href="#" class="waves-effect waves-light btn btn-primary btn-xs btn-circle"><span class="icon-Arrow-right"><span class="path1"></span><span class="path2"></span></span></a>
                                    </div>
                                </td>
                            </tr>
                            @endforeach
Activity icon

Replied to Using Event And Listener In Laravel

After successful payment, the user should have access to the courses he has purchased, but this does not happen

Activity icon

Started a new Conversation Using Event And Listener In Laravel

Hello everyone, I want the user to have access to the purchased courses after the order was successful This will be done using event and listenter, but this code that I wrote does not work.

orders table

        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();

        });

payments table

        Schema::create('payments', function (Blueprint $table) {
            $table->id();
            $table->foreignId('order_id')->constrained('orders')->cascadeOnDelete();
            $table->string('ref_num')->nullable();
            $table->string('gateway')->nullable();
            $table->enum('status' , Payment::$statuses)->default(Payment::STATUS_PENDING);
            $table->integer('amount');
            $table->timestamps();
        });

course_user table

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

            $table->foreignId('user_id');
            $table->foreignId('course_id');

            $table->timestamps();
            $table->primary(['user_id' , 'course_id']);

            $table->foreign('user_id')->references('id')->on('users')->onDelete('CASCADE');
            $table->foreign('course_id')->references('id')->on('courses')->onDelete('CASCADE');

        });

relation*

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

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

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

}


event

class SuccessOrder
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $order;

    public function __construct(Order $order)
    {
        $this->order = $order;
    }

    public function broadcastOn()
    {
        return new PrivateChannel('channel-name');
    }
}

listener

class RegisterUserToCourse
{
    public function __construct()
    {
        //
    }

    public function handle($event)
    {
        if($event->order->courses == Course::class){
            return resolve(Course::class)->addStudentsToCourse($event->order->courses , $event->order->user_id);
        };
    }
}

course model

    public function addStudentsToCourse(Course $course , $userId)
    {
        if(! $this->getCourseUser($course , $userId)){
            $course->users()->attach($userId);
        }
    }

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

payment controller

        try {
            //TODO $payment->amount
            if ($payping->verify($request->refid, 100)) {
                $payment->update([
                    'status' => 'success'
                ]);

                $payment->order()->update([
                    'status' => 'success'
                ]);

                
                event(new SuccessOrder($payment->order));

                Alert::success('successfull', 'success payment', 'success')
                    ->showConfirmButton($btnText = 'ok', $btnColor = '#3085d6')
                    ->autoClose($milliseconds = 4000);;
                return redirect(route('courses.list'));
                
            } else {
                $payment->update([
                    'status' => 'fail'
                ]);

                $payment->order()->update([
                    'status' => 'fail'
                ]);

                return redirect(route('courses.list'));
            }
        } catch (PayPingException $e) {

            foreach (json_decode($e->getMessage(), true) as $msg) {
                $payment->update([
                    'status' => 'canseled'
                ]);

                $payment->order()->update([
                    'status' => 'canseled'
                ]);

                Alert::error('wrong ', $msg, 'error')
                    ->showConfirmButton($btnText = 'ok', $btnColor = '#3085d6')
                    ->autoClose($milliseconds = 4000);;
                return redirect(route('courses.list'));
            }
        }
Feb
06
2 weeks ago
Activity icon

Started a new Conversation SQLSTATE[42S22]: Column Not Found: 1054 Unknown Column 'likes' In 'order Clause'

Hi everyone I want to display the most popular articles on the home page but I get an error

articles table

        Schema::create('articles', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id');
            $table->string('title');
            $table->string('slug');
            $table->longText('body');
            $table->string('image')->nullable();
            $table->enum('status' , ['accept' , 'reject' , 'pending'])->default('pending');
            $table->integer('viewCount')->default(0);
            $table->timestamps();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('CASCADE');
        });

likes table

        Schema::create('likes', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained('users')->cascadeOnDelete();
            $table->unsignedInteger('likeable_id');
            $table->string('likeable_type');
            $table->boolean('liked');
            $table->timestamps();
        });

relations

    public function likes()
    {
        return $this->morphMany(Like::class, 'likeable');
    }

    public function likeable()
    {
        return $this->morphTo();
    }
        view()->composer('front.articles.popular-articles', function ($view) {
            $popArticles = (new Article())->popArticles();
            $view->with(compact('popArticles'));
        });

    public function popArticles()
    {
        return $this->where('status' , self::STATUS_ACCEPT)
        ->orderBy('likes' , 'DESC')
        ->latest()
        ->take(3)
        ->get();
    }
Feb
05
2 weeks ago
Activity icon

Started a new Conversation Lock Cash Sessions For Users Who Have Not Purchased The Course

Hi everyone I want to lock cash sessions for users who have not purchased the course from the site And the user can not download by clicking on cash sessions How is this possible?

    public function up()
    {
        Schema::create('lessons', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id');
            $table->unsignedBigInteger('course_id');
            $table->unsignedBigInteger('season_id')->nullable();
            $table->unsignedBigInteger('media_id')->nullable();
            $table->string('title');
            $table->string('slug');
            $table->unsignedInteger('number');
            $table->boolean('is_free')->default(false);
            $table->unsignedTinyInteger('time')->nullable();
            $table->longText('body')->nullable();
            $table->enum('status' , ['accept' , 'reject' , 'pending'])->default('pending');
            $table->enum('confirm' , ['opened' , 'locked' ])->default('opened');
            $table->timestamps();

            $table->foreign('user_id')->references('id')->on('users')->onDelete('CASCADE');
            $table->foreign('course_id')->references('id')->on('courses')->onDelete('CASCADE');
            $table->foreign('season_id')->references('id')->on('seasons')->onDelete('SET NULL');
            $table->foreign('media_id')->references('id')->on('media')->onDelete('SET NULL');
        });
    }
      <ul class="course-curriculum">
          @foreach ($seasons as $season)
          <li>
              <h5 class="text-primary font-weight-500">{{$season->title}}</h5>
                @foreach ($lessons->where('season_id' , $season->id) as $lesson)
                <ul class="list-unstyled">
                   @auth
                   <li>
                    <div class="list-bx">
                        <span>{{$lesson->number}} - </span>
                        <a href="{{$lesson->downloadLink()}}">{{$lesson->title}}</a>
                    </div>
                    <span>
                        {{$lesson->TimeForHumans}}
                        <a href="{{$lesson->downloadLink()}}">
                          <i class="{{auth()->user()->hasAccessToCourse($lesson->course)|| 
                          $lesson->is_free ? 'fa fa-download' : 'fa fa-lock'}} ml-10">
                          </i>
                        </a>
                    </span>

                    </li>
                    @else
                    <li>
                      <div class="list-bx">
                          <span>{{$lesson->number}} - </span>
                          <a href="{{route('login')}}">{{$lesson->title}}</a>
                      </div>
                      <span>
                          {{$lesson->TimeForHumans}}
                          <a href="{{route('login')}}"><i class="{{auth()->check() &&  auth()->user()->hasAccessToCourse($lesson->course) || $lesson->is_free ? 'fa fa-download' : 'fa fa-lock'}} ml-10"></i></a>
                      </span>

                      </li>
                   @endauth
                </ul>
                @endforeach
            </li>
            @endforeach
      </ul>
class MediaController extends Controller
{
    public function download(Media $media , Request $request)
    {
        if(!$request->hasValidSignature()){
            abort(401);
        }

        return MediaFileService::stream($media);
    }
}


    public static function stream(Media $media)
    {
        try {
            foreach (config('mediaFile.MediaTypeServices') as $key => $service) {
                if ($media->type == $key) {
                    return $service["handler"]::stream($media);
                }
            }
        } catch (\Exception $e) {
            abort(404);
        }
    }
Feb
01
3 weeks ago
Activity icon

Replied to Argument 1 Passed To App\Course::isLikedBy() Must Be An Instance Of App\User, Null Given,

So I want both the login user and the guest user to be able to like the posts. What is the solution?

Activity icon

Replied to Argument 1 Passed To App\Course::isLikedBy() Must Be An Instance Of App\User, Null Given,

These are all relevant codes. See where the problem is that the error still persists

<?php

namespace App;

use App\Like;
use App\User;
use Illuminate\Database\Eloquent\Builder;

trait Likeable
{
    public function scopeWithLikes(Builder $query)
    {
        $query->leftJoinSub(
            'select likeable_id , sum(liked) likes , sum(!liked) dislikes  from likes group by likeable_id',
        );
    }

    public function likes()
    {
        return $this->morphMany(Like::class, 'likeable');
    }

    public function isDisLikedBy(User $user)
    {
        return (bool) $user->likes
            ->where('likeable_id',  $this->id)
            ->where('liked', false)
            ->count();
    }

    public function isLikedBy(User $user = null)
    {
        if (! $user) {
            return false;
        } 
        
        return (bool) $user->likes
            ->where('likeable_id', $this->id)
            ->where('liked', true)
            ->count();
    }

    public function like($user = null, $liked = true)
    {
        $this->likes()->updateOrCreate(
            [
                'user_id' => $user ? $user->id : auth()->id()
            ],
            [
                'liked' => $liked
            ]
        );
    }

    public function dislike($user = null)
    {
        return $this->like($user, false);
    }
}

                    <li>
                        <form action="{{route('articles.likes.store' , $article->id)}}" method="post">
                            @csrf 
                            <button type="submit" style="border: none; background-color:#fff">
                                <i class="fa fa-thumbs-up {{Auth::check() && $article->isLikedBy(auth()->user()) ? 'text-blue' : 'text-gray'}}">
                                </i>
                            </button>{{$article->likes()->where('liked', 1)->count()}}
                        </form>

                    </li>
                    <li>
                        <form action="{{route('articles.likes.destroy' , $article->id)}}" method="post">
                            @csrf 
                            @method('delete')
                            <button type="submit" style="border: none; background-color:#fff">
                                <i class="fa fa-thumbs-down {{$article->isDisLikedBy(auth()->user()) ? 'text-blue' : 'text-gray'}}"></i>
                            </button>
                                {{$article->likes()->where('liked', 0)->count()}}
                        </form>

                    </li>
Activity icon

Replied to Argument 1 Passed To App\Course::isLikedBy() Must Be An Instance Of App\User, Null Given,

I followed Jeffrey tutorial. He used the current user function instead of auth, but I use it. It does not recognize the function.

Activity icon

Replied to Argument 1 Passed To App\Course::isLikedBy() Must Be An Instance Of App\User, Null Given,

The third solution gives this error

Trying to get property 'likes' of non-object

        return (bool) $user->likes
            ->where('likeable_id', $this->id)
            ->where('liked', true)
            ->count();
Activity icon

Replied to Argument 1 Passed To App\Course::isLikedBy() Must Be An Instance Of App\User, Null Given,

Dear friend, I want both the user who is not logged in and the user who is logged in to have access to this section, but this value only works for the user who is logged in.

Activity icon

Replied to Argument 1 Passed To App\Course::isLikedBy() Must Be An Instance Of App\User, Null Given,

This error persists

Argument 1 passed to App\Course::isLikedBy() must be an instance of App\User, null given, called in 
                        @auth
                        <form action="{{route('articles.likes.store' , $article->id)}}" method="post">
                            @csrf 
                            <button type="submit" style="border: none; background-color:#fff">
                                <i class="fa fa-thumbs-up {{$article->isLikedBy(auth()->user()) ? 'text-blue' : 'text-gray'}}">
                                </i>
                            </button>{{$article->likes()->where('liked', 1)->count()}}
                        </form>
                        @endauth
    public function isLikedBy(?User $user)
    {
        if (! $user) {
            return false;
        } 
        
        return (bool) $user->likes
            ->where('likeable_id', $this->id)
            ->where('liked', true)
            ->count();
    }
Activity icon

Replied to Argument 1 Passed To App\Course::isLikedBy() Must Be An Instance Of App\User, Null Given,

I want logged in users and guests to be able to access this section This code does not apply to guest users

Activity icon

Started a new Conversation Argument 1 Passed To App\Course::isLikedBy() Must Be An Instance Of App\User, Null Given,

Hi, when the user is logged in or not logged in, I want him to be able to see the page, but this only works for the logged in user. What is the solution?

<i class="fa fa-thumbs-up {{$article->isLikedBy(auth()->user()) ? 'text-blue' : 'text-gray'}}">
</i>
    public function isLikedBy(User $user)
    {
        return (bool) $user->likes
            ->where('likeable_id', $this->id)
            ->where('liked', true)
            ->count();
    }
Jan
31
3 weeks ago
Activity icon

Replied to Implement Like Post System In Laravel

In this video, the methods mentioned are suitable for implementation with one to many relationships, but I want to implement them as one to many polymorphic.

Activity icon

Started a new Conversation Implement Like Post System In Laravel

Hello everyone, I want to implement a like system for products and blog site. Can you introduce me a tutorial on this topic?

Jan
30
3 weeks ago
Activity icon

Replied to Call To A Member Function GetLogo() On Null (

Yes, there is no record. I want a photo to be set by default if there is no record

Activity icon

Started a new Conversation Call To A Member Function GetLogo() On Null (

Hi, I expect the default image to be a logo when there is no record in the database, but I get an error

Setting Model

    public function getLogo()
    {
        if($this->logo){
            return '/storage/' . $this->logo;
        }else{
            return url('/images/logo-light-text2.png');
        }
    }

header.blade.php

<img src="{{\App\Setting::first()->getLogo()}}" alt=""/>

Jan
26
4 weeks ago
Activity icon

Replied to Display Products Of Each Category In Laravel

My problem is that by clicking on any category, I want to see the related products as described above

Activity icon

Replied to Display Products Of Each Category In Laravel

i use scopFilter in course model for filter but this code not working

Activity icon

Replied to Display Products Of Each Category In Laravel

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