MahmoudMonem

Member Since 7 Months Ago

Experience Points
5,920
Total
Experience

4,080 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
33
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,920 XP
Mar
03
2 months ago
Activity icon

Started a new Conversation How To Update Orders Table After Payment Being Approved [ PAYPAL ] Express Checkout

Hello Guys, I'm trying to update order status after it is paid on paypal .. my checkout process goes as follow

1- User Add product to cart 2- Go to check out page 3- Create an order > Gets directed to paymentpage 4- in payment page he clicks on buttons to choose his preferred payment option [ 2 gateways ] and both fires up a javascript

5- after completing purchase on the gateway I am expecting a callback response which I use it's details to update the order status and attach the user to this product [ since it's a digital product ]

My Code goes like that

paymentpage.php

<script
src="https://www.paypal.com/sdk/js?client-id={{env('PAYPAL_SANDBOX_CLIENT_ID')}}"> 
</script>
<script>
     paypal.Buttons({
            createOrder: function(data, actions) {
                var payableAmount = $("#finalAmountTotalOrders").attr("amountData");  
                return actions.order.create({
                    purchase_units: [{
                        amount: {
                            value: '{{$order->usd_price}}'
                        }
                    }]
                });
            },
            onApprove: function(data, actions) {
                return actions.order.capture().then(function(details) {
                    window.location.href = 'complete?&orderID='+data.orderID;                
                });
                }
        }).render('#paypal-button-container');
</script>


<div class="mt-3" id="paypal-button-container"></div>

I know this is not right but here is what I'm trying to achieve

PaypalController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Order;
use App\Mail\NewPurchaseMail;
use App\Services\PaypalService;
use Illuminate\Support\Facades\Mail;


class PaypalController extends Controller
{

    public function index()
    {
        return View('payment/complete');      
    }


    public function paymentfailed()
    {
        return View('payment/paymentfailed');      
    }

    public function UpdateOrder(Request $request, $orderId){

        $order = Order::find($orderId);
        $response = $this->paypalService->captureOrder($order->paypal_orderid);

        if($response->result->status == 'COMPLETED'){
            $orderId = $request->orderId;     
            $status = $request->status; 
                // Update order status
                $order->update([
                    'status' => 'PAID',
                    'paymentMethod' => 'PayPal',
                ]);

                // Get order items
            $items = $order->items()->get()->pluck('item_id')->toArray();
    
            // Inseet user items to user course
            $order->user->products()->attach($items);
            return redirect()->route('paymentSuccess');
           //Mail::to($order->user)->send(new NewPurchaseMail($order));
            
        }
            
        return redirect()->route('paymentFailed');
        
       
   }
}

route

Route::get('/payment/complete',['uses'=>'[email protected]']);

I can direct to page success or page fail .. but just can't understand how to update the orders table .. also got so confused with what is available in the internet.. since this is new and old SDKs are depricated and even the official doc of paypal is so confusing for me ..

Feb
25
2 months ago
Activity icon

Replied to Best Way To Remove Columns From Table [ Live Project ]

@guybrush_threepwood this with @samross comment helped me have better understanding thanks a lot :)

Activity icon

Replied to Best Way To Remove Columns From Table [ Live Project ]

Thanks @snapey , I already do that <3

Feb
24
2 months ago
Activity icon

Started a new Conversation Best Way To Remove Columns From Table [ Live Project ]

Hello guys, I'm a little bit worried. what is the best way to remove two foreign keys columns from a table on a live project. [ My project is hosted on an Ubuntu Linux server by Digitalocean. and I use SSH to run migrations on live.

I know how to add tables and add columns to tables but I never removed / dropped before and I'm kinda worried to screw things up.

I have two tables units and tests

tests had unit_id and course_id foreing keys columns. now I decided to make the relationship many to many and have a new test_unit table.

which is already done & also updated the relationships to many to many.

Thanks for your time.

Feb
16
2 months ago
Activity icon

Replied to How Can I Track URL Referral And Store Its Content

Hello @martinbean .. I have pixel already installed .. but this is something different .. for example let's say you and one of your friends are running two different fb campaigns for the same product .. and a customer purchased this product .. how would u know which campaign this customer clicked on to complete the purchase ?

Feb
15
2 months ago
Activity icon

Started a new Conversation How Can I Track URL Referral And Store Its Content

Hello Guys, Now I have customers coming to the registration page coming from promotional campaigns made by different affiliates using different platforms like [ facebook - google ads - instagram ] .

What I want to do is [ to store the campaign data ex; ID ] when the customer sign up. so that I know that this customer did sign up through this specific campaign. and send my incentives to the right affiliate.

I can get/store the source using {{$_SERVER['HTTP_REFERER']}} .. which will return something like https://l.facebook.com/

but that's not enough .. if the URL for example looks like this

fbclid=IwAR3wN4y_nqWyWzDiwynjcvr4reA1sUJSQ4OY3h_6QAtteC-9xnRhdr-mJNw

How can I get store or strip or echo this fbclid ??

Would really appreciate your inputs

Jan
16
3 months ago
Activity icon

Replied to How To Add Processing Icon To Submit Button [ On Registration ]

Thank you @paulmaxos for your time. Actually I'm using Laravel 7 ... I am actually using queues and I pretty much did everything to try to reduce the time .. delayed email .. used queues .. even removed the mails and verifications all together :D nothing did affectthe processing time.. it's always 5 to 6 sec. but that's another topic for now I would stick with the spinner option , It was annoying that shen user click submit nothing happens for 5 seconds, so they might keep clicking on the submit button.. but now there is an indicator for him to wait .. I followed yours and snapys inputs and now it's working. that will do .. later on will think on how to improve things. Have a great day ahead.

Activity icon

Replied to How To Add Processing Icon To Submit Button [ On Registration ]

That worked just fine thank you so much @snapey <3

Activity icon

Replied to How To Add Processing Icon To Submit Button [ On Registration ]

Yes without the script it works fine :)

Activity icon

Replied to How To Add Processing Icon To Submit Button [ On Registration ]

Hello @snapey

I tried without the timeout but it didn't work as well. the button shows the spinner and text, but the registration doesn't go through.

          <form method="POST" action="{{ route('register') }}" class="registerform">

            <div class="text-right">
             
              <button class="submit btn btn-block btn-primary" type="submit">
              <i class="loading-icon fa-lg fas fa-spinner fa-spin hide"></i> &nbsp; 
              <i class="czi-user mr-2 ml-n1"></i>
              <span class="btn-txt">{{ __('Register') }}</span></button>
            </div>


<script>
$(document).ready(function() {
$(".submit").on("click", function() {
$(".result").text("");
$(".loading-icon").removeClass("hide");
$(".submit").attr("disabled", true);
$(".btn-txt").text("Processing ...");
});
});
</script>
Activity icon

Replied to How To Add Processing Icon To Submit Button [ On Registration ]

Hello again @paulmaxos .. thank you so much for your time.. I will try what you told me and will update my answer here, but for the time being.. this is actually the Registration form to register new users. I am using the default Laravel Auth and I have validations for all the inputs. Supposedly yes this will go live .. It's not just for fun project. I just hate the fact that when users click submit .. nothing happens till the registeration is processed which takes like 5 seconds. since I am also sending verification mail and welcome mail.

that was the reason why I wanted to do this.

In my registercontroller. php

   // protected $redirectTo = RouteServiceProvider::HOME;
     protected $redirectTo = '/verifyemail';

I just redirect users to static page [ Verify Email ] to just let them know that they have received a verification mail.

That's it.. again thank you so much and I will try and update again <3

Jan
15
3 months ago
Activity icon

Replied to How To Add Processing Icon To Submit Button [ On Registration ]

Hello @paulmaxos thanks for your input, appreciated .. can you please tell me how can I add my request to the script. my form looks like this ..

<form method="POST" action="{{ route('register') }}">

I really have never done something like that before. Also, tried to check online but all the tutorials highlights just how to add the animation to the button, but never tackles how to separate the form submission action from the btn click. thanks again

Activity icon

Started a new Conversation How To Add Processing Icon To Submit Button [ On Registration ]

I am trying to show users that registration is being processing .. I thought of using jquery and following some tutorials this did pretty much look fine, but the problem is that the function is overlapping the submit action and the form is not being processed. but the icon spinner appears as I would like it to look like.

<div class="text-right">
             
              <button class="btn btn-block btn-primary" type="submit">
              <i class="loading-icon fa-lg fas fa-spinner fa-spin hide"></i> &nbsp; 
              <i class="czi-user mr-2 ml-n1"></i>
              <span class="btn-txt">{{ __('Register') }}</span></button>
            </div>

    <script>
      $(document).ready(function() {
        $(".btn").on("click", function() {
          $(".result").text("");
          $(".loading-icon").removeClass("hide");
          $(".btn").attr("disabled", true);
          $(".btn-txt").text("Processing ...");
 
setTimeout(function(){

            $(".loading-icon").addClass("hide");
          $(".button").attr("disabled", false);
          $(".btn-txt").text("Registered");
          }, 5000);
          });
        });
    </script>

how should I tackle this or maybe even if you have a better approach altogether would appreciate your input.

Activity icon

Started a new Conversation My Form Submits Data Automatically To Fields Even Though No Edits Were Made [ UPDATING Data ]

Hello Guys,

Now I have courses table where I update some fields like ; available [enum 0,1 ] available_at [ date ] category_id [ foreign key ]

my update function works fine .. but for example if I just edited the "available" field .. the form submit current date for the "available_at " [ which is different than the existent date I put before ] and in crs_ctg field it choose the first category automatically .. Even though I didn't edit these fields at all.

<div class="col-sm-6">
<div class="form-group">
<label for="available_at">Available Date</label>
<input type="date" class="form-control" name="available_at" id="available_at" placeholder="Course Available date">
</div>
</div>

for example to avoid this problem in normal inputs I just pass the Value like that, so I don't have problem the same problem with title field

<div class="col-sm">
<div class="form-group">
<label for="crs_title">Course Title</label>
<input type="text" class="form-control" name="crs_title" id="crs_title" placeholder="{{$course->crs_title}}" value="{{$course->crs_title}}">
</div>
</div>

but since I pick the category id from a list of categories like in here ;

@foreach ($categories as $category)
<option value="{{ $category->id}}"> 
{{ $category->ctg_name}}
</option>
@endforeach

The form submits default data in inputs like lists and dates , even though I didn't change them

Here is my update function :

public function updateCourse(Request $request,$id){

    $crs_ctg =  $request->input('crs_ctg');
    $crs_title =  $request->input('crs_title');
    $available =  $request->input('available');
    $available_at =  $request->input('available_at');
    $crs_price =  $request->input('crs_price');
    $slug =  $request->input('slug');

$updateArray = array(
                        
"crs_ctg"=>$crs_ctg,
"crs_ctg"=>$crs_ctg,
"available"=>$available,
"available_at"=>$available_at,
"crs_price"=>$crs_price,
'updated_at' => \Carbon::now(),
"slug"=>$slug);

DB::table('courses')->where('id',$id)->update($updateArray);
return redirect()->route("adminAllCourses")->withSuccess('Course Updated Successfully!');


}

would appreciate your input

Dec
20
4 months ago
Activity icon

Replied to [Discussion] How Do You Track Customers Purchase Channel After Adding To Cart

Will definitely explore more about php referrer .. thanks @jlrdw for the input <3

Activity icon

Started a new Conversation [Discussion] How Do You Track Customers Purchase Channel After Adding To Cart

Hello guys, I would like to know from you, your good case practices about handling the purchase channel. Here is what I mean. for example when a customer click on your facebook ad and go to your product page. if he clicked on add to cart and made an order, I would like for example to capture, the campaign id or for example insert into my orders table's "channel" column [1] or whatever any type of indicator that highlights that this customer is coming from this source/channel or campaign

How do you manage something like that in your applications?

Dec
03
5 months ago
Activity icon

Replied to [Discussion] Best Approach To Handle Bundle Products/packages

Hey @bugsysha .. thanks for your input but i am kinda confused .. can u plz elaborate more .. so you would have 1- product table .. 2- bundle table .. 3 - bundle-product table ?? .. what would be stored in the bundle table and the pivot one

Activity icon

Started a new Conversation [Discussion] Best Approach To Handle Bundle Products/packages

Hello Guys, I was wondering what is the best way to create bundle of existing products. what approach do you follow. do you create a separate bundles table or you just handle everything in blade view or you just add new columns to the existing product table.

now for example we have :

Product 1 : price : 50 USD Product 2 : price : 100 USD

If I would like to create something like

Buy Product 1 + Product 2 for 120 USD, what is the best way to achieve that.

Dec
01
5 months ago
Activity icon

Replied to File Upload Issue With Jpg Files Only

Hello @michaloravec .. thank you for ur input, appreciated .. actually this solved it , but what do you think could be the reason why it was working normally and then stopped out of no where .. thanks again <3

Activity icon

Started a new Conversation File Upload Issue With Jpg Files Only

My file images uploader was working perfectly fine and out of no where it started to give me error only for the JPG files. I didn't do any changes on the code in controller or form submission .. all i did was composer upgrade to version 2 . not sure if that is even what's causing the problem.

in my controller I have

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

my form

<div class="form-group">
<label for="image">Upload Course Card Image </label>
<input type="file" class=""  name="crs_img" id="crs_img" required>
</div>

I get an error [ file must be an image] .. though if i tried png , it goes through ! the weird thing is that the very same picture was uploaded successfully a few hours ago.

The problem also same in the "picture edit " form. only accepts whatever is not jpg.

any hints what might be the cause of this

Activity icon

Replied to Question About Updating Composer On Production Environment

Hello Sinnbeck , can you please elaborate more what do i need to check exactly .. how can i chevk if its in version control and how can i update it in production .. because actually composer stuff gets me very confused sorry.

Nov
30
5 months ago
Activity icon

Started a new Conversation Question About Updating Composer On Production Environment

Hello guys, I did upgrade my composer locally using simple

composer self-update 
composer self-update --2 

and now it's version two. now on production .. I just run composer install and it did some updates .. is that all it takes to get things updated or do I need to do something else ?

Do I need to upgrade composer on live as well or now it is updated as part of the new updates after I pulled the latest composer.lock ?

Nov
25
5 months ago
Activity icon

Replied to How To Eager Load The Queries Inside The "show" Page

I just loaded

$course->load(['units.lessons','reviews.user','users' ]);

and that pretty much cleaned the queries from 31 to 15 .. and for some reason the repeated code above is gone and now everything should be ok. I updated my answer for that reason. Thank you @rodrigo.pedra so much for your time <3

Activity icon

Replied to How To Eager Load The Queries Inside The "show" Page

@rodrigo.pedra Thank you so much , I did explore a bit, but this helped me a lot .. now is fine :)

Nov
24
5 months ago
Activity icon

Started a new Conversation How To Eager Load The Queries Inside The "show" Page

Hello Guys, I'm very new to optimization and I'm trying to improve my code efficiency a bit. Now I actually improved the index pages for so many modules like for example here in courses controller index function

changed this

$courses = Course::orderBy('created_at','desc')->paginate(39);
        return view('courses', ['courses' => $courses]

to this and with this logic I managed to reduce the number of queries a lot for so many other things related to the course.

$courses = Course::with('category')
 ->orderBy('created_at','desc')->paginate(39);
        return view('courses', ['courses' => $courses])

Now I have show page which is [ courses/show ] and simply it has this

public function show(Course $course)
    {
$instructorname = $course->instructor->user->name;
return view('courses.show', ['course' => $course])
}

However in the show view, I am calling " list of students who are enrolled " [ which led me to have many duplicates for select * from users .. ] I am also having course units and units lessons. so I also have many duplicates for select*from units and select * lessons.

How can I eager load these queries in this show page. will appreciate ur inputs :)

Nov
23
5 months ago
Activity icon

Replied to My Registration Process Is So Slow [ 5 : 9 Seconds ]

Alright will install and check it out .. Thank you @automica for the help and time, really appreciated :)

Activity icon

Replied to My Registration Process Is So Slow [ 5 : 9 Seconds ]

@automica The ip address 127.0. etc db port 3306 in both local and server

Activity icon

Replied to My Registration Process Is So Slow [ 5 : 9 Seconds ]

I removed all the validations except for name didn't improve anything..

Removed the Phone number field entirely and it's validation .. same 9.4 s :D

The phone Rule is there to make sure that the phone input customers put is valid phone number in Egypt and not any gibberish

return preg_match('/^[0-9]{3}[0-9]{8}$/', $value) && strlen($value) >= 10;

and this is my Email input

<div class="col-sm-12">
                <div class="form-group">
                  <!-- <label for="email">E-mail Address</label> -->
                 
                  <input id="email" class="form-control" type="email" placeholder="Email - البريد الإلكتروني" name="email" value="{{ old('email') }}" required autocomplete="email">
                  <p class="font-size-sm text-muted mb-4 text-left">A verification message will be sent to this Email</p>

                    @error('email')
                    <span class="invalid-feedback" role="alert">
                    <strong>Your Email is Wrong or Taken</strong>
                    </span>
                    @enderror
                </div>
              </div>

Btw I don't have any users in the database as I didn't launch the website .. so like 4 5 users ..

Activity icon

Replied to My Registration Process Is So Slow [ 5 : 9 Seconds ]

@automica on remote as well .. only Register takes that long .. even asked a friend to try ... to make sure that it's not related to cache or anything on my machine or browser. same thing

Activity icon

Replied to My Registration Process Is So Slow [ 5 : 9 Seconds ]

@automica .. Contact and wallet creates new entries for the new user in these two tables. so that later on for example he can edit his social contacts [contacts] and I can give him points in the [ wallet ]. deleting these two insertion did not make any improvements. otherwise, I would have removed them entirely.

1-almost all app pages load time is between 250 to 500 ms .. not bad for me.

2- the welcome page loading time is 261 ms / which is pretty ok for me as well.

3- Sometimes Inserting a new comment also took long. that's why I even added the loader gif, to give the customers any hints that something is loading .. this does not even happen on registration. as the loading gif only appears after the registration is done.

4- I didn't quite understand the question, sorry. but I have a database on localhost and i manage it through php my admin on local machine.

4- my web hosting is Digital ocean Lamp Ubuntu on Ubuntu 20 with apache2 .. php my admin for database management and I use visual studio as SSH and sometimes WinSCP.

Activity icon

Replied to My Registration Process Is So Slow [ 5 : 9 Seconds ]

Hello @automica .. not at all .. i even removed the mail entirely .. and removed the insertions .. didn't even improve anything .. the delay was also experienced by my friend on live so it's not related to my machine or work environment.

Activity icon

Replied to Job Queue Failure

The behavior is same on localhost and on live server .. using digital ocean .. no only this registeration form takes that long :) also it's very weird that the loading gif doesn't appear except after registration is processed ! Don't know what is the point of it then if customers dont see it after clicking register. thats why it is driving me crazy haha thanks @tisuchi don't want to bother u with the issue more, will keep trying stuff and see if anything helped improving it. And will update the discussion if managed to solve it

Activity icon

Replied to My Registration Process Is So Slow [ 5 : 9 Seconds ]

Hello @gitwithravish .. here you are the full code .. just for you to know, I removed the google recaptcha, facebook pixels , google analytics and even the payment gateway script from my header. but none of these helped fasten the process, or even show any signs of improvement. in the network console, when I looked at the initiators, there are a bunch of css and js being called, but none of them exceeds a few ms. or has a significant waterfall. only Register.

I even removed the whole controller and replaced it with the original default register controller of laravel. but still same results. Actually my Register process was fast before, but I remember as I'm adding features, I was like okk fine will get back to this later on. and noww I have no idea what is causing all this delay.

<?php

namespace App\Http\Controllers\Auth;
use Request;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\User;
use App\Contact;
use App\Wallet;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Mail;


use App\Rules\PhoneNumber;
use App\Rules\FullName;

use App\Mail\WelcomeMail;

use GuzzleHttp\Client;
use Session;

class RegisterController extends Controller
{


    use RegistersUsers;


     protected $redirectTo = '/verifyemail';


    public function __construct()
    {
        $this->middleware('guest');
    }


    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:30', new FullName],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
            'phone' => ['required', new PhoneNumber],
            'birthdate' => ['required'],
          
            
        ]);
    }


    protected function create(array $data)
    {
        $user = User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
            'phone' => $data['phone'],
            "birthdate"=>$data['birthdate'],       

            'ip' =>  request()->ip(),   
        ]);

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

        Contact::create([
            'user_id' => $user->id,      
        ]);

        Wallet::create([
            'user_id' => $user->id,
            
        ]);
        
        return $user;
        
        $captchatoken = $request->input('g-recaptcha-response');

        if ($captchatoken) {
            $client = new Client();
            $response = $client->post('https://www.google.com/recaptcha/api/siteverify', [
                'form_params' => array(
                    'secret'    => '6Ldo-uEZAAAAAMFKTnYpJAbazolD3n0JPFQJrXsf',
                    'response'  => $captchatoken
                    )
                ]);
            $results = json_decode($response->getBody()->getContents());
                }
            if ($results->success) {
            } else {
                Session::flash('error', 'You are probably a robot!');
                return redirect('/');
            }


    }
}



Activity icon

Replied to Job Queue Failure

I did remove almost everything and I ended up having the same result. even sometimes worse :) like I removed facebook pixel - google analytics - the table insertions - the welcome mail .. the verification .. even removed the payment gateway script from the header. all didn't change anything. In the Netowork tab for example, it shows me the water fall is 9 seconds .. but when i look at the initiators, there are a bunch of css and js being called, but none of them are taking more than a few ms.. I will keep trying though thanks @tisuchi for your time :)

Activity icon

Started a new Conversation My Registration Process Is So Slow [ 5 : 9 Seconds ]

I have a registration form where I collect register information, then

1- Send Welcome mail 2- Verify Mail 3- Insert a value into another table 4- insert another value into another table

Then redirect the customer to welcome page.

in the Network Console "Register" has a very big waterfall and it takes from 5 to 9 seconds to process. when I clicked on it, like css and js files in addition to connection to facebook fbevent and google recaptcha.

I even have a loader GIF, which doesn't even appear to the customers on registration.. it only appear after the registration is processed just before going to welcome page. So when the customer click on Register.. nothing happen for like 9 seconds, then the loading gif just appear and redirection happen and all is good to go.

I tried to remove the " Emails " and the data insertions from the RegisterController, but that didn't change anything, the speed was same. so apparently it's not the mail and insertions that are causing the delays. any tips on how to speed this generally or at least figure out exactly what is causing all this delay :) ?? would appreciate your help.

Nov
22
5 months ago
Activity icon

Replied to Job Queue Failure

Here you are .. I also have Email verification active. this is the one I have before I think of queue jobs .. the time on network is like from 5.99 seconds to even sometimes 9 seconds.

<?php

namespace App\Http\Controllers\Auth;
use Request;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\User;
use App\Contact;
use App\Wallet;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Mail;


use App\Rules\PhoneNumber;
use App\Rules\FullName;

use App\Mail\WelcomeMail;

use GuzzleHttp\Client;
use Session;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */

     
    
     // protected $redirectTo = RouteServiceProvider::HOME;
     protected $redirectTo = '/verifyemail';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:30', new FullName],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
            'phone' => ['required', new PhoneNumber],
            'birthdate' => ['required'],
          
            
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    {
        $user = User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
            'phone' => $data['phone'],
            "birthdate"=>$data['birthdate'],       

            'ip' =>  request()->ip(),   
        ]);

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

        Contact::create([
            'user_id' => $user->id,      
        ]);

        Wallet::create([
            'user_id' => $user->id,
            
        ]);
        
        return $user;
        
        $captchatoken = $request->input('g-recaptcha-response');

        if ($captchatoken) {
            $client = new Client();
            $response = $client->post('https://www.google.com/recaptcha/api/siteverify', [
                'form_params' => array(
                    'secret'    => '6Ldo-uEZAAAAAMFKTnYpJAbazolD3n0JPFQJrXsf',
                    'response'  => $captchatoken
                    )
                ]);
            $results = json_decode($response->getBody()->getContents());
                }
            if ($results->success) {
            } else {
                Session::flash('error', 'You are probably a robot!');
                return redirect('/');
            }


    }
}



Activity icon

Replied to Job Queue Failure

This gave me undefined user error .. I think apparently this mail is not what is making my process slow. because even with the job, the registration still takes 7-8 sec. I do have a couple of other table inserts

    Contact::create([
            'user_id' => $user->id,
            
        ]);

        Wallet::create([
            'user_id' => $user->id,
            
        ]);

and I think these are what is causing the problem of delay..

Activity icon

Replied to Job Queue Failure

@tisuchi I did actually have the mail imported .. I think as @snapey said, I needed to refresh the queue and actually the mail error is gone, now I have problem defining $user in the SendEmailJob.php :(

Activity icon

Replied to Job Queue Failure

@tisuchi @parasume @snapey .. Hello Guys thanks for your feedback. I didn't notice the failed jobs table ! my bad sorry ..

so the error written in exception is

Error: Class 'App\Jobs\Mail' not found

and I have use Illuminate\Support\Facades\Mail; .. what is this I didn't even write this class anywhere

This is what I have in the SendEmailJob.php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Mail;

use App\Mail\WelcomeMail;
Activity icon

Started a new Conversation Job Queue Failure

Hello guys, so I had a welcome mail in my registration In addition to verify mail active as well. so the registration is taking so long on the network console [ like 9 seconds ]. I thought it would be a good idea to make queue for the welcome mail. and I did the following, but unfortunately now I get failed

[2020-11-22 08:52:06][2] Failed:     App\Jobs\SendEmailJob

So in my RegisterController I added the following


use App\Jobs\SendEmailJob;
use Carbon\Carbon;


$job= (new SendEmailJob())
                ->delay(Carbon::now()->addSeconds(5));
                dispatch($job);

in my SendEmailJob


use App\Mail\WelcomeMail;


   public function handle()
    {
        Mail::to($user->email)->send(new WelcomeMail());
    }

I also made sure that in my .env

QUEUE_CONNECTION=database

and I have the jobs table migrated and cleared my config & restarted my server .. what am I missing here please ? plus how can I fasten the registration more ..

Nov
21
5 months ago
Activity icon

Started a new Conversation Registration Button Does Not Work Only On Mobile View [ Google Recaptcha]

Hello Guys, I recently added google Recaptcha to my Registration form and I have noticed that the registration button, does not fire up ONLY on mobile view , because of the recaptcha. but everything works completely fine on desktop. why is this happening ? when I removed the recaptcha div below from the registration form, the button worked fine.

<div class="g-recaptcha" data-sitekey="6Ldo-uEZAAAAABeEalDYQc4V9"></div><br>

Also do you have any recommendation on how to add conditionals to the recaptcha. I mean, I don't want it to be there upfront like that. I want it to appear only if a suspicious form submission activity is detected

Nov
15
5 months ago
Activity icon

Replied to Getting The Count Of All Users In All Views

This is definitely what I was looking for .. thank you guys so much <3 @talinon @tisuchi

Nov
14
5 months ago
Activity icon

Started a new Conversation Getting The Count Of All Users In All Views

Hello guys, I currently have something like this

in my footer.blade.php

{{ \App\Product::all()->count() }}

to showcase the number of all products. It's working fine and displayed in all pages as I want.

I was wondering if this is an OK practice or bad. is there a better way to do something like that.

Like I was thinking to a query for example

$productcount = Product::count();

In a controller and simply return {{$roductcount}} in the view, but couldn't really think of how to get it in all views, since it will be in the footer and it would throw an error if $productcount not defined in that specific view.

Nov
11
5 months ago
Activity icon

Replied to How To Validate URL Input

This did solve it .. thank you so much @tykus <3 .. Now all is good.

I also changed the regex into a more simple one [ If anyone else in the future would like to use the code ]

    public function passes($attribute, $value)
    {
        $regex = '/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/';
        return preg_match($regex, $value);
    }
Activity icon

Replied to How To Validate URL Input

Hello @tykus thanks for replying .. can you please elaborate how can I do that, as I'm still learning and I understand what you mean, but not really familiar with how to achieve it.

Activity icon

Started a new Conversation How To Validate URL Input

I have a form where users add new projects the form has title image and video URL.

I am trying to create a validation for the URL and to do that I created a new Rule called UrlValidity.php .. I copied the regex from an old thread here which seemed fine for me.

UrlValidity.php

    public function passes($attribute, $value)
    {
        $regex = '_^(?:(?:https?|ftp)://)(?:\S+(?::\S*)[email protected])?(?:(?!(?:10|127)(?:.\d{1,3}){3})(?!(?:169.254|192.168)(?:.\d{1,3}){2})(?!172.(?:1[6-9]|2\d|3[0-1])(?:.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\x{00a1}-\x{ffff}0-9]-)[a-z\x{00a1}-\x{ffff}0-9]+)(?:.(?:[a-z\x{00a1}-\x{ffff}0-9]-)[a-z\x{00a1}-\x{ffff}0-9]+)(?:.(?:[a-z\x{00a1}-\x{ffff}]{2,})).?)(?::\d{2,5})?(?:[/?#]\S)?$_iuS';
        return [
        'proj_video_url' => 'regex:' . $regex,
        ];
    }

In my Controller I added the following

use App\Rules\UrlValidity;

// CREATE NEW Project
    public function CreateProject(Request $request){

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

        Validator::make($request->all(),
        ['proj_video_url' => new UrlValidity,
        'proj_img'=>"required|file|image|mimes:jpg,png,jpeg|max:5000"])->validate();
        
// the rest of the code. 

My Create form looks like this

<div class="col-sm">
<div class="form-group">
<label for="proj_video_url">Project Video URL</label>
<input type="text" class="form-control" name="proj_video_url" id="proj_video_url" placeholder="Project Video URL">
@error('proj_video_url')
<span class="invalid-feedback" role="alert">
<strong>URL is invalid</strong>
</span>
@enderror
</div>
</div>

now If i just put sss or anything in the url field, it gets processed and the project gets created. How can I solve this and how can I test the validation rule ?

Nov
02
6 months ago
Activity icon

Started a new Conversation How To Calculate Total Time Duration Using Carbon

I have a courses that has many lessons .. The lessons table has duration timestamp field .. I would like to calculate the total number of hours for a specific course. I tried to check for this but mostly people are calculating differences between two times.

course id	lesson_title	lesson_duration
-------------------------------------------------------------------
1	                 Intro	        00:16:43
1	                 B	                00:14:47
1	                 C	                00:13:09