MahmoudMonem

MahmoudMonem

Member Since 1 Month Ago

Experience Points
4,440
Total
Experience

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
32
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.

Level 1
4,440 XP
Oct
31
7 hours ago
Activity icon

Awarded Best Reply on Problem Sending Email To User When Purchase A Product

Solved by changing this line

Mail::to($order->user->email)->send(new NewPurchaseMail($order));

and I also forgot to add the facade

use App\Mail\NewPurchaseMail;
use Illuminate\Support\Facades\Mail;
Activity icon

Replied to Problem Sending Email To User When Purchase A Product

Solved by changing this line

Mail::to($order->user->email)->send(new NewPurchaseMail($order));

and I also forgot to add the facade

use App\Mail\NewPurchaseMail;
use Illuminate\Support\Facades\Mail;
Oct
30
1 day ago
Activity icon

Started a new Conversation Problem Sending Email To User When Purchase A Product

I have three tables users | products | product_user

What I have is a call back from payment service provider .. in this call back , I attach the order user to the product

Now everything is working fine, I attach the user to product and also I update Order status .. What I'm trying to do is to send an Email to the user with the details of his purchase or at least just an email that he purchased a new product and he can check it out through the link I give in the mail. something like [website/myproducts]

so In my trial to do that, I tried the following :

I created a NewPurchaseMail.php

 public function build()
    {
        return $this->markdown('emails.new_purchase')
        ->subject('You have purchased new Course 🥳');
    }
}

With a markdown called new_purchase.blade.php

@component('mail::message')

# Hi! You have a new purchase 

@component('mail::button', ['url' => 'https://website/myproducts'])
Checkout your Products
@endcomponent

Team {{ config('app.name') }}

@endcomponent

and in my callback function I tried to do so

if($order = \App\Order::find($orderId)) {
		
        // Update order status
        $order->update([
            'status' => $status
        ]);

        // Get order items
        $items = $order->items()->get()->pluck('item_id')->toArray();

        // Insert user items to product_user table
        $order->user->products()->attach($items);

        Mail::to($order->user->email)->send(new NewPurchaseMail($order));
    } // I am sure this is wrong 

Would appreciate your inputs

Activity icon

Replied to My .htaccess Keep Changing On Server Even Though I Added It To Gitignore File

Hello @sinnbeck thanks for replying ..

just to confirm I understood right .. My flow is usually [ changes on local > GIT push > pull to server ] and not reversed I always reset hard any changes on server before pulling.

now I should

1- remove /public/.htaccess from the gitignore file

2- will backup my .htaccess in my local ..

3- run git rm --cached .htaccess

4- committ the changes and push

then

1- put the "server" version .htaccess

2- commit and push it

3- pull it on server

4- add .htaccess to git ignore again.

5- do the little changes needed for my localhost environment and save

Activity icon

Started a new Conversation My .htaccess Keep Changing On Server Even Though I Added It To Gitignore File

I have little differences between my .htaccess in localhost and the one on server. Every time I make new git pull. the .htaccess keep changing. despite the fact that I added and that the gitignore files are similar on both localhost and server.

I have this :

/public/.htaccess

in the gitignore file .. what do I need to do to prevent the .htaccess on server from being updated on pull commands ?

Activity icon

Awarded Best Reply on Problem With Updating Images On A Linked Storage Directory On Server

Alright Solved it .. I had public folder in git ignore, hence my public folder and storage folder on server were a miss with so many old files and other useless folders .. also in the update function had to change this

$request->crs_img->storeAs("courses/",$course->crs_img);

to

$request->crs_img->storeAs("public/courses/",$course->crs_img);

because it was actually updloading the new picture, but outside the public folder in storage. hence, I didn't see it.

Now all is fine :)

Activity icon

Replied to Problem With Updating Images On A Linked Storage Directory On Server

Alright Solved it .. I had public folder in git ignore, hence my public folder and storage folder on server were a miss with so many old files and other useless folders .. also in the update function had to change this

$request->crs_img->storeAs("courses/",$course->crs_img);

to

$request->crs_img->storeAs("public/courses/",$course->crs_img);

because it was actually updloading the new picture, but outside the public folder in storage. hence, I didn't see it.

Now all is fine :)

Activity icon

Started a new Conversation Problem With Updating Images On A Linked Storage Directory On Server

I have a an update function for my courses that looks like this [code below] .. It is supposed to check if an old picture exists and if it does, it overwrites it with a new one. the function works perfectly fine on localhost but on server, it just deletes the old picture and does not update.

 //update course Image
    public function updateCourseCard(Request $request,$id){


        Validator::make($request->all(),['crs_img'=>"required|file|image|mimes:jpg,png,jpeg|max:5000"])->validate();


        if($request->hasFile("crs_img")){

            $course = Course::find($id);
          $exists = Storage::disk('local')->exists("public/courses/".$course->crs_img);

          //delete old image
          if($exists){
             Storage::disk("local")->delete('public/courses/'.$course->crs_img);

          }

          //upload new image
            $ext = $request->file('crs_img')->getClientOriginalExtension(); //jpg

            $request->crs_img->storeAs("courses/",$course->crs_img);

            $arrayToUpdate = array('crs_img'=>$course->crs_img,
                                   'updated_at' => \Carbon::now());


            DB::table('courses')->where('id',$id)->update($arrayToUpdate);


            return redirect()->route("adminAllCourses")->withSuccess('Course Image Updated!');

        }else{

           $error = "NO Image was Selected";
           return $error;

        }


    }

I made sure that I ran php artisan storage link on my SSH server. I am using Digital ocean .. what is the issue here ? is it a permission issue or what ?

When I ran storage link again i got

The [/public/storage] link already exists.
The links have been created.
Oct
24
1 week ago
Activity icon

Replied to Trying To Validate / Prevent User From Submitting Multiple Reviews For The Same Product

Very interesting .. thanks @michaloravec for sharing .. I was wondering if there are any pros or cons for one approach over the other

    public function store(Request $request)
    {
$findReview = Review::where(['user_id' => Auth::user()->id, 'product_id' => $request->product_id])->first();
        if($findReview) {return back()->with('error', 'You already reviewed this product');}
        else{Review::create($request->all());
        return redirect()->back()->with('success', 'Review Submitted Successfuly');}
       
    }
Activity icon

Started a new Conversation Trying To Validate / Prevent User From Submitting Multiple Reviews For The Same Product

I have 3 tables Users | Products | Reviews

in my reviews table I have user_id and product_id

Once a user purchase specific product, he/she can submit review .. I am trying to prevent duplicated reviews for the same user. and I did the following to achieve that ..

1- in my "make_reviews_table.php"

            $table->unsignedBigInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->unsignedBigInteger('product_id');
            $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');

            $table->unique(['product_id', 'user_id']);

This actually prevents users from submitting a second review for the same product, but it throws a Database Error in the view and I don't want customers to see that .. so I tried to add this line in the controller [ even though I was so sure it's missing something

2- added conditional if before processing the review submission

    public function store(Request $request)
    {
   
        $findReview = Review::where('user_id', Auth::user()->id)->first();
        if($findReview) {
            return back()->with('error', 'You already reviewed this product');
        }else{

            Review::create($request->all());
        
            return redirect()->back()->with('success', 'Review Submitted Successfuly');

        }
       
    }

The problem here, which I knew, is that it prevents users from adding any other reviews on any other product. so I need to define "the current specific product" in the function. Or maybe there is something else better than this approach .. would appreciate your input.

Ps: my view url looks like .. website.com/{product-slug}

Activity icon

Replied to Unable To Unlink/delete Product Image After Destroying The Product Itself

@talinon This is exactly what was missing :D Thank you so much <3

Activity icon

Replied to Unable To Unlink/delete Product Image After Destroying The Product Itself

hey @talinon sorry I didn't get what you mean by specifying disk local .

Activity icon

Started a new Conversation Unable To Unlink/delete Product Image After Destroying The Product Itself

I have products that has one product image .. I add this image while creating the product like that .. also I have the storage folder linked to public folder

 // CREATE NEW PRODUCT

        public function adminCreateProduct(Request $request){

            $prod_name =  $request->input('prod_name');
            $slug =  Str::slug($prod_name);

            Validator::make($request->all(),
            ['prod_img'=>"required|file|image|mimes:jpg,png,jpeg|max:5000"])->validate();
            $ext =  $request->file("prod_img")->getClientOriginalExtension();
            $stringImageReFormat = time();
    
            $imageName = $stringImageReFormat.".".$ext; 
            $imageEncoded = File::get($request->prod_img);
            Storage::disk('local')->put('public/products/'.$imageName, $imageEncoded);
            $newProductArray = array(
                                
                                "prod_name"=>$prod_name, 
                                 "slug"=>$slug,
                                 "prod_img"=> $imageName);
    
            $created = DB::table("products")->insert($newProductArray);
    
    
            if($created){
                return redirect()->route("adminAllProducts");
            }else{
               return "Product was not Created";
            }
    }

All works fine I also have a destroy product function in ProductsController

    public function destroy($id)
    {
        $product = Product::find($id);

        $exists =  Storage::disk("local")->exists("public/products/".$product->prod_img);
      
       //if old image exists
        if($exists){
       //delete it
            Storage::delete('public/products/'.$product->prod_img);
        }
        
        //dd($exists);
      
        Product::destroy($id);
      
        return redirect()->route("adminAllProducts")->withSuccess('Product Deleted successfully!');
        
    }

Now in my View

 <td>
<a onclick="return confirm('Delete {{$product['prod_name']}} from Database ?')" href="{{ route('adminDestroyProduct',['id' => $product['id']])}}"  class="btn btn-sm btn-danger">Remove</a>
</td>

Now when I delete the product , it gets deleted but the image stays in the folder .. when I tried to dd($exists) in the destroy function it actually returned TRUE .. but still the image doesn't get removed .. What am I missing here ?

Activity icon

Replied to How Can I Get The Percentage Of Discount Between 2 Prices In Controller

this is exactly what I was looking for .. Thank you guys @sinnbeck @jlrdw and @siangboon <3

Oct
23
1 week ago
Activity icon

Replied to How Can I Get The Percentage Of Discount Between 2 Prices In Controller

@siangboon and @jlrdw .. Hello guys thank you so much for the head up .. actually I dove into the php manual and it's soo interesting .. so many things to learn :D so thanks..

{{(ceil(($product->price_before - $product->price_after)/$product->price_before*100))}}

Now I did that in the blade view and it gave me the expected result I'm looking for .. actually this percentage thing is jut serving informing purpose .. nothing more.

I really think there is a better way I can get this into the controller and just call something like "$discount" in the blade view .. @siangboon can you please give me more input on how can I improve this by moving it to a dedicated class .. or even in the Product Model :)

Activity icon

Started a new Conversation How Can I Get The Percentage Of Discount Between 2 Prices In Controller

I have products table that has 2 columns price_before | price_after

In the view I loop through all products

@foreach($products as $product)

{{$product->price_before}}
{{$product->price_after}}

@endforeach

I would like to get the percentage and achieve an equation like

(1 - New Price / Old Price)*100)

so that it looks 50% or at least 50 .. not like 50.1234223

my ProductsController.php

public function index(){
$products = Product::orderBy('created_at','desc')->paginate(39);
return view('products', ['products' => $products]);
}

How can I achieve that in the productscontroller ?

Oct
18
1 week ago
Activity icon

Replied to Laravel Deployment - Production Workflow And Good Case Practices

Alright @sinnbeck understood .. will get familiar with envoy and start using it, then show you the results .. thanks, appreciated <3

Activity icon

Replied to Laravel Deployment - Production Workflow And Good Case Practices

Hello @sinnbeck .. yes by SSH and I have php myadmin for DB .. regarding what i meant by editing manually for example I have added .env to the gitignore list and if I need to do any changes on remote .env .. I open the file using cmd vi .env and do the changes .. Is this ok or bad practice ? Then Do confing cache clear.

I should run composer install everytime I do new pull on remote ? And alright will read more about compiling assets thank you :)

Activity icon

Started a new Conversation Laravel Deployment - Production Workflow And Good Case Practices

Hello guys .. I managed to deploy my very first laravel app on Digital Ocean ubuntu 20.04 server with apache2 and it is up and running and everything seems to be ok .. I am kind of very worried to mess things up and would love to hear from you how do you manage your apps once it's live.

First is there any files or things need to change because I went live ? Something in config or .env or any other files?

My current flow goes as follows; Locally:

1- develop new features locally 2- commit & push updates to Git repo

On remote: 1- Git reset hard (not always) 2- Git pull 3- run migrations 4- edit changes manuly for files in Gitignore

That's it .. what else do I need to do or stop doing .. also if you have any articles or terms or services to check , read about and learn would be of great help.

Oct
17
2 weeks ago
Activity icon

Replied to How To Send Mail Using Zoho Laravel Mailable

Hello Guys this is a late reply, but if you still have issues with that [ especially Authentication Errors like 530-535 etc ] try the following :

1- Generate a security password instead of your email password

to do that log in to your email at zoho and from the security tab on the left go to > App Passwords and check for > Application-Specific Passwords .. Generate a new password and copy it and place this in the MAIL_PASSWORD field on your .env file.

MAIL_USERNAME= 
MAIL_PASSWORD= // 

2- Make sure you changed these 2 lines in the config > mail.php file instead of example bla bla

   'from' => [
        'address' => env('MAIL_FROM_ADDRESS', 'YOUR EMAIL'),
        'name' => env('MAIL_FROM_NAME', 'YOUR APP NAME'), // instead of Example 
    ],

Clear your cache ~~~ php artisan cache:clear


and you should be good to go.
Oct
16
2 weeks ago
Activity icon

Replied to How To Prevent Sending Notification If User Is Replying On His Own Comments

Hello @loyd

I did this and it worked as I want .. thank you so much :)

 public function store(Request $request)
    {
        $reply = Reply::create($request->all());

        $comment = $reply->comment;
	
	if ($comment->user_id === Auth::user()->id) {
		return back()->with('success', 'Reply Submitted Successfully');
	}
    
        if ($reply && $reply->comment && $reply->comment->user ) {
            
            $reply->comment->user->notify(new RepliedToComment($reply));
            
            return redirect()->back()->with('success', 'Reply Submitted Successfuly');
        }
        return redirect()->back()->with(['error', 'Something wrong while creating reply!']);
    }
Oct
15
2 weeks ago
Activity icon

Started a new Conversation How To Prevent Sending Notification If User Is Replying On His Own Comments

I have 3 tables .. users | comments | replies

and I have a notification called RepliedToComment.php

 public function toDatabase($notifiable)
    {
        return [
            'repliedTime'=>Carbon::now(),
            'reply'=>$this->reply, 
            'user'=>$notifiable
        ];
    }

My RepliesController.php looks like that

  public function store(Request $request)
    {
        $reply = Reply::create($request->all());
    
        if ($reply && $reply->comment && $reply->comment->user ) {
            
            $reply->comment->user->notify(new RepliedToComment($reply));
            
            return back()->with('success', 'Reply Submitted Successfully');
        }
        return back()->with('error', 'Something wrong while submitting this reply!');
    }

Now the notification is working fine when someone reply on a comment, but I would like to "not" send the notification if the reply is made by the comment owner himself.

I tried to add .. if reply->comment->user == Auth::user() in the store function, but it didn't work.

Activity icon

Replied to How To Insert Multiple Data With One Form Submission [ LARAVEL - Eloquent ]

@michaloravec will definitely go through them to learn more .. thanks for sharing

Activity icon

Replied to How To Insert Multiple Data With One Form Submission [ LARAVEL - Eloquent ]

Changed this and also changed the name="course_id" in the input field to avoid array conversion errors and now all works great .. Thank you so much .. you're awesome :D @sinnbeck and @michaloravec .. thank you guys for your contribution .. appreciated

Activity icon

Replied to How To Insert Multiple Data With One Form Submission [ LARAVEL - Eloquent ]

did exactly try this before your reply and it threw

ErrorException
Undefined offset: 1

This is my function in case I am doing something wrong

public function adminSendCreateUnit(Request $request){


        $course_id =  $request->input('course_id');
        $unit_number =  $request->input('unit_number', []);
        $unit_title =  $request->input('unit_title', []);
        
        
        $units = [];

        foreach ($unit_number as $index => $unit) {
            $units[] = [
                "course_id" => $course_id[$index],
                "unit_number" => $unit_number[$index],
                'created_at' => \Carbon::now(),
                "unit_title" => $unit_title[$index]
            ];
        }

        $created = Unit::insert($units);

        if($created){
            return redirect()->route("adminAllUnits")->withSuccess('Unit Created successfully!');
        }else{
           return "Unit was not Created";
        }
}

Activity icon

Replied to How To Insert Multiple Data With One Form Submission [ LARAVEL - Eloquent ]

Tried again and I got this error .. for your method and also @sinnbeck same result

ErrorException
Uninitialized string offset: 2

highlighting this line

"course_id" => $course_id[$index],
Activity icon

Replied to How To Insert Multiple Data With One Form Submission [ LARAVEL - Eloquent ]

Hello @automica .. thanks .. here is the full form code .. I want multiple for both [ unit_title and unit_number ] so the data will look something like that on the database

course_id :1 unit_number:1 unit_title: intro -------------------- course_id :1 unit_number:2 unit_title: Two -------------------- course_id :1 unit_number:3 unit_title: three


<form action="{{ route('adminSendCreateUnits')}}" method="post" enctype="multipart/form-data">
{{csrf_field()}}
<div  class="row col-12">
<div class="col-sm">
<div class="form-group">

<label style="width:100%; background-color:grey; color:white; padding:15px;" for="course_id">Course</label>
<select name="course_id" class="form-control">
<option>Select Course</option><!--selected by default-->
@foreach ($courses as $course)
<option value="{{$course->id}}"> 
{{ $course->id}}-{{ $course->crs_title}}
</option>
@endforeach
</select>

</div>
</div>
</div><br>

<div class="row col-12">

<table class="table table-bordered table-hover" id="tab_logic">
        <thead style="background-color:grey; color:white">
          <tr>
            <th style="width:5%;"> rows </th>
            <th class="text-center">Unit Number </th>
            <th class="text-center">Unit Title</th>
          </tr>
        </thead>
        <tbody style="background-color:#dce8dc;">
          <tr id='addr0'>
            <td  style="width:5%;">1</td>
            <td>
                <div class="col-sm">
                <div class="form-group">
                <label for="unit_number">Unit Number</label>
                <select name="unit_number[]" class="form-control">

                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
                <option value="4">4</option>

                </select>
                </div>
                </div>
            </td>
            <td>
                <div class="col-sm">
                <div class="form-group">
                <label for="unit_title">Unit Title</label>
                <input type="text" class="form-control" name="unit_title[]" id="unit_title" placeholder="Unit Title" required>
                </div>
                </div>
            </td>
          </tr>
          <tr id='addr1'></tr>
        </tbody>
      </table>

</div>
<br><br><div class="row col-12">
    <div style="text-align: center;" class="col-md-12">
      <button id="add_row" class="btn btn-success float-left">+ Unit</button>
      <button type="submit" name="submit" class="btn btn-lg btn-success">Submit</button>
      <button id='delete_row' class="btn btn-danger float-right">x Unit</button>
    </div>
  </div>
Activity icon

Started a new Conversation How To Insert Multiple Data With One Form Submission [ LARAVEL - Eloquent ]

I have form where I am planning to insert data into units table .. it has fields course_id | unit_number | unit_title

the form is working fine, in case I'm inserting only one unit. but when I insert multiple rows it only stores the last row.

@include('admin.messages')
<form action="{{ route('adminSendCreateUnits')}}" method="post" enctype="multipart/form-data">
{{csrf_field()}}
<div  class="row col-12">
<div class="col-sm">
<div class="form-group">

<label style="width:100%; background-color:grey; color:white; padding:15px;" for="course_id">Course</label>
<select name="course_id" class="form-control">
<option>Select Course</option><!--selected by default-->
@foreach ($courses as $course)
<option value="{{$course->id}}"> 
{{ $course->id}}-{{ $course->crs_title}}
</option>
@endforeach
</select>

</div>
</div>
</div><br>

<label for="unit_number">Unit Number</label>
 <select name="unit_number[]" class="form-control">
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
                <option value="4">4</option>
                <option value="10">10</option>
</select>

 <label for="unit_title">Unit Title</label>
<input type="text" class="form-control" name="unit_title[]" id="unit_title" placeholder="Unit Title" required>
	

my unitscontroller.php [ I'm sure this is wrong .. since I was trying stuff and i lack the knowledge]

 public function adminSendCreateUnit(Request $request){


        $course_id =  $request->input('course_id');
        $unit_number =  $request->input('unit_number', []);
        $unit_title =  $request->input('unit_title', []);
        
       
        $newCategoryArray = array(
                            
                            "course_id"=>$course_id, 
                             "unit_number"=>$unit_number,
                             'created_at' => \Carbon::now(),
                             "unit_title"=> $unit_title);

        $created = DB::table("units")->insert($newCategoryArray);


        if($created){
            return redirect()->route("adminAllUnits")->withSuccess('Unit Created successfully!');
        }else{
           return "Unit was not Created";
        }
}

I would like to have the course ID same in all rows .. only Unit number and titles change. would appreciate any input :)

Oct
14
2 weeks ago
Activity icon

Replied to Merchant Call Back POST Is Getting 405 Error - Payment Integration [ Laravel ]

Hello @snapey .. thanks for replying .. Actually when I first gave the Callback url to them

https:://website/merchantCallbackPage .. I clearly mentioned to him that it's a POST request. .. actually they do both and I said POST and he carried on forward with that .. will doublr check with them again and see .. I am very new to these stuff :)

Activity icon

Started a new Conversation Merchant Call Back POST Is Getting 405 Error - Payment Integration [ Laravel ]

Hello ..

I am working with a payment gateway service provider. and now I'm testing everything. I have 3 routes .. 1 for payment success [ New & Paid Orders ] & One for payment failed

these 2 are working fine.

The third one is a POST route where I am planning to capture the data sent back from service provider. and then since user purchased the course, I'm planning to attach the user to his course in a Course_user table

Route::post('merchantCallbackPage', function (Request $request) {
													 
    $orderId = $request->get('MerchantRefNo');
    $farwyRef = $request->get('FawryRefNo');
    $status = $request->get('OrderStatus'); // NEW, PAID, CANCELED, DELIVERED, REFUNDED, EXPIRED
    $amount = $request->get('Amount');


    if($order = \App\Order::find($orderId)) {

        // Update order status
        $order->update([
            'status' => $status
        ]);

        // Get order items
        $items = $order->items()->get()->pluck('item_id')->toArray();

        // Inset user items to user course
        $order->user->courses()->attach($items);
    }
});

Now when I am completing an order I received this log from the service provider .. which clearly shows that there is an error preventing the POST request.

0000031e MerchantInteg I MerchantIntegrationService sendHTTPRequest merchantCode = 9910url=https://website/merchantCallbackPage?MerchantRefNo=65&FawryRefNo=958034105&OrderStatus=PAID&Amount=179.9&MessageSignature=16385A
[10/14/20 17:44:31:613 EET] 0000031e MerchantInteg I MerchantIntegrationService sendHTTPRequest Http respons code = 405 for merchant = 9910

I thought maybe the Csrf Middleware is blocking it .. so I tried to exclude the route by writing this [ not even sure if this is right ] . but anyway it didn't work ..

class VerifyCsrfToken extends Middleware
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'merchantCallbackPage/*'
    ];
}

Do you have any inputs ? and how can I test this again using the URL i got from them

Oct
12
2 weeks ago
Activity icon

Awarded Best Reply on How To Notify Comment Owner And Not Auth User

@michaloravec @bestmomo @saeed410

Someone recommended me to remove the $reply parameter and change the function code to following :

public function store(Request $request)
{
    $reply = Reply::create($request->all());

    if ($reply && $reply->comment && $reply->comment->user) {
        $reply->comment->user->notify(new RepliedToComment($reply));
        
        return redirect()->back()->with('success', 'Reply Submitted Successfuly');
    }
    return redirect()->back()->withErrors(['error' => 'Something wrong while creating reply!']);
}

and Now it's working fine .. Thank you guys for your effort.

Activity icon

Replied to How To Notify Comment Owner And Not Auth User

@michaloravec @bestmomo @saeed410

Someone recommended me to remove the $reply parameter and change the function code to following :

public function store(Request $request)
{
    $reply = Reply::create($request->all());

    if ($reply && $reply->comment && $reply->comment->user) {
        $reply->comment->user->notify(new RepliedToComment($reply));
        
        return redirect()->back()->with('success', 'Reply Submitted Successfuly');
    }
    return redirect()->back()->withErrors(['error' => 'Something wrong while creating reply!']);
}

and Now it's working fine .. Thank you guys for your effort.

Activity icon

Replied to How To Notify Comment Owner And Not Auth User

@saeed410 thanks for your comment .. Actually I have protected $guarded = ['id'] in both Reply.php and Comment.php

I have added now protected fillable for other columns .. but still the same error msg.

ErrorException
Trying to get property 'user' of non-object
Activity icon

Replied to How To Notify Comment Owner And Not Auth User

@bestmomo

Now I get error

ErrorException
Undefined variable: reply

from this line

$reply->comment->user->notify(new RepliedToComment($reply));
Activity icon

Replied to How To Notify Comment Owner And Not Auth User

@bestmomo thanks for the trial though :( will wait and see if someone might find the issue..

Activity icon

Replied to How To Notify Comment Owner And Not Auth User

@michaloravec .. I used to do that in my store methods .. without it the $reply variable becomes undefined.

$reply->comment->user->notify(new RepliedToComment($reply));
Activity icon

Replied to How To Notify Comment Owner And Not Auth User

@bestmomo Yess my reply form

<form class="media-body needs-validation ml-3" novalidate action="{{ route('ReplySubmit')}}" method="POST" enctype="multipart/form-data">
                      {{csrf_field()}}

                      <input type="hidden" name="course_id" value="{{$unit->course->id}}"/>
                      <input type="hidden" name="user_id" value="{{ Auth::user()->id }}"/>
                      <input type="hidden" name="unit_id" value="{{ $unit->id }}"/>
                      <input type="hidden" name="comment_id" value="{{ $comment->id }}"/>
                    <div class="form-group">
                        <textarea class="form-control" rows="1" required id="rep_text" name="rep_text"></textarea>
                      <div class="invalid-feedback">Write a reply</div>
                    </div>
                    <button class="btn btn-dark btn-sm float-right" type="submit" name="submit">Reply</button>
 </form>
Activity icon

Replied to How To Notify Comment Owner And Not Auth User

@michaloravec yes definitely all replies belong to a comment and even they appear in my views under their relative comments.

Activity icon

Replied to How To Notify Comment Owner And Not Auth User

Thanks Michal for the reply .. I tried this already .. i get Error

ErrorException
Trying to get property 'user' of non-object
Activity icon

Replied to How To Notify Comment Owner And Not Auth User

Yeah tried and it gave me : error

Call to undefined method Illuminate\Database\Eloquent\Relations\BelongsTo::user()

Activity icon

Replied to How To Notify Comment Owner And Not Auth User

Helllo BestMomo .. Thanks for your reply.. this will actually notify the "reply owner" which is same result as now.. I want to notify the comment owner instead .. something like $reply->comment->user .. but i tried that and didn't work.

Activity icon

Started a new Conversation How To Notify Comment Owner And Not Auth User

I have 2 tables comments and Replies related as follows :

Reply.php

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

Comment.php

 public function user(){return $this->belongsTo('App\User');}
 public function replies(){return $this->hasMany('App\Reply');}
  • replies Tables has : comment_id | user_id
  • comments Table has : user_id

I am trying to create a notification .. when a user replies on a specific comment .. the comment owner gets notified.

so I created a new notification called RepliedToComment.php

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

public function via($notifiable)
    {
        return ['mail','database'];
    }

public function toDatabase($notifiable)
    {
        return [
            'repliedTime'=>Carbon::now(),
            'reply'=>$this->reply, 
            'user'=>$notifiable
        ];
    }

and in my RepliesController.php :

  public function store(Request $request, Reply $reply)
    {
        Reply::create($request->all());

        auth()->user()->notify(new RepliedToComment($comment));
        
        return redirect()->back()->with('success', 'Reply Submitted Successfuly');
    }

Notifications now is working , but as you can see the "Reply Owner " is the one being notified as defined in the function.. I tried to change Auth:: user many times trying to change it to comment-> user, but failed ..

How to define the comment owner instead of auth user ?

Oct
03
4 weeks ago
Activity icon

Replied to How To Get ID From URL Slug

@automica

 public function show(Course $course, Unit $unit )
    {
        $courseID = $course->id;
        $previous_record = Unit::where('id', '<', $unit->id)->where('course_id', $courseID) ->orderBy('id','desc')->first();
        $next_record = Unit::where('id', '>', $unit->id)->where('course_id', $courseID)->orderBy('id')->first();

        return view('courses.units.show',  compact('course', 'unit', 'previous_record','next_record'));

    }

It just did the job and now everything is working just as I want :D Thank you so much <3 !

Activity icon

Replied to How To Get ID From URL Slug

@sergiu17 .. hello again.. actually I have watched this many times and watched now again and I'm implementing exactly what he is doing

  • I have defined {course} in route & function
  • I set getRouteKeyname to return slug instead if ID
  • I prevented Users from manually inputting Unit ID in the URL and is now returnig 403 through .htaccess, so this is not an issue

.. Jeffrey's example is tackling 1 table .. I don't have any problems with that and I can do it ... my problem now is that I have two params for 2 tables with relationship .2 Parameters passed in the URL . 1 is: course slug .. and one is : Unit id .. all i need is to get the course ID [ define it as a variable ] in the previous and next records queries. this will be enough to solve the passing through next units to even access other courses issue. by clicking next next next ...

the question is .. can I get the course ID variable with the current settings or no ? and if no where is exactly the problem ? should I change the slug parameters to be ID and if i did that, wouldn't this ID clash with Unit ID ? because when I tried something like that my loops got screwed. sorry for the long message.

Activity icon

Replied to How To Get ID From URL Slug

Hello Sergiu .. thanks for your reply .. I have read the docs and watched many videos, but unfortunately couldn't spot a situation like this .. maybe it's too easy actually and my brain just can't get it. can you please give me more hints on what exactly needs to be changed in the wild cards ? Do I have to pass the course Id as Param ? .. would really appreciate more inputs

Oct
02
4 weeks ago
Activity icon

Started a new Conversation How To Get ID From URL Slug

I have a url that looks like this

/courses/{slug}/units/{unit_id}

This page shows unit content of this specific course

What I am doing is : I added Next and Previous buttons for users to navigate between this specific course units.

The problem [ Users can keep clicking next next next going through al the Units to even other courses

in my Course.php


 public function getRouteKeyName(){
    return 'slug';
}

in my UnitsController :

public function show(Course $course, Unit $unit )
    {
        $course = Course::find($course);
        $previous_record = Unit::where('id', '<', $unit->id)->where('course_id', 1) ->orderBy('id','desc')->first();
        $next_record = Unit::where('id', '>', $unit->id)->where('course_id', 1)->orderBy('id')->first();

        dd($previous_record);
        return view('courses.units.show',  compact('course', 'unit', 'previous_record','next_record'));


    }

Notice Here : I was trying to just see if it will work by adding 1 for the course ID and it worked perfectly .. so what I need to do here is to replace this 1 with the a variable that gets course ID .. because when I use anything, I get error undefined variable.

$previous_record = Unit::where('id', '<', $unit->id)->where('course_id', 1) ->orderBy('id','desc')->first();
$next_record = Unit::where('id', '>', $unit->id)->where('course_id', 1)->orderBy('id')->first();

Course has many units Unit belongsTo course

Unit table has "course_id" column.

Would appreciate any input :)

Sep
30
1 month ago
Activity icon

Replied to Only Allow Course Owner To Access Course Route [LARAVEL MIDDLEWARE]

Out of trying out things ..

in my CoursePolicy.php

I changed this $course->user_id;

 public function show(User $user, Course $course)
    {
         return $user->id === $course->user_id;
    }

to something like this

  public function show(User $user, Course $course)
    {
         return $user->id === 1;
    }

Result :: course views were successfully blocked from all users except User with ID 1 .. so technically the Authorize function is working & the problem is how I'm retrieving the User ID from Pivot table. will keep trying