Our Black Friday sale is now live! All individual subscriptions are 50% OFF. This week only!

MahmoudMonem

MahmoudMonem

Member Since 1 Month Ago

Experience Points
5,120
Total
Experience

4,880 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.

Level 2
5,120 XP
Nov
23
13 hours 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
1 day 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
2 days 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
1 week 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
1 week 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
1 week 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
3 weeks 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

Nov
01
3 weeks ago
Activity icon

Replied to Problem With Ajax [ Trying To Update Add To Cart Without Refreshing The Page ]

Alright will try to do that.. any idea why it's giving my unidentified in the response, even though I hade

return response()->json(['totalQuantity',$cart->totalQuantity]);

in my function ?

Activity icon

Replied to Problem With Ajax [ Trying To Update Add To Cart Without Refreshing The Page ]

Hello @jlrdw yess .. but only on page refresh .. both item counts and total price get calculated fine. so the button does actually add the item to cart on click.

Activity icon

Started a new Conversation Problem With Ajax [ Trying To Update Add To Cart Without Refreshing The Page ]

Hey, I am trying to use ajax to handle the Add to cart functionality and show total quantity without [return back()] which is the current stat .. or the need to refresh the page

I tried the following ;

in all_courses.blade.php

<script type="text/javascript">
    
     $(document).ready(function() {

             $('.ajaxPOST').click(function(e){

                    e.preventDefault();

                   var url = $(this).find('#url').text();
                   var courseId = $(this).find('#courseId').text();

                    var _token = $("input[name='_token']").val();


                    $.ajax({
                            
                            method:"POST",
                            url:url,

                            data:{_token: _token, id: courseId},

                            success:function(data,status,XHR){

                                 alert(data.totalQuantity);

                                 var totalQuantity = data.totalQuantity;

                                 $('#totalQuantity').text(totalQuantity);
                            },
                            error:function(xhr,status,error){
                                alert(error);

                            }

                    });

             });

     });
</script>
@foreach ($courses as $course)
<div>
<h5 class="card-title">{{ $course->crs_title}}</h5>

<a href="#" class="ajaxPOST btn btn-default add-to-cart">
<div id="url" style="display:none">
{{ route('AddToCartAjaxPost') }}
</div>
<div style="display:none" id="courseId"> {{$course->id}} </div>
<i class="fa fa-shopping-cart"></i>Add to cart</a>

</div>

@endforeach

In my CoursesController.php

   public function addToCartAjaxPost(Request $request){


     $id = $request->input('id');

     $prevCart = $request->session()->get('cart');
      $cart = new Cart($prevCart);

      $course = Course::find($id);
      $cart->addItem($id,$course);
      $request->session()->put('cart', $cart);

       return response()->json(['totalQuantity',$cart->totalQuantity]);

  }

in my Web.php

//Add to cart using ajax post request
Route::post('courses/addToCartAjaxPost', ["uses"=>"[email protected]", "as"=> "AddToCartAjaxPost"]);

in my app.blade

<li class="nav-item">
<a href="{{route('cart')}}">
<button type="button" class="btn btn-primary">CART
@if(Session::has('cart'))
<h2><span id="totalQuantity" class="badge badge-light">
QTY {{ Session::get('cart')->totalQuantity }} | Total {{ Session::get('cart')->totalPrice }} EGP
</span></h2>
<span class="sr-only">Items</span>
@endif
</button>
</a>
</li>

Now what happens is, first I get response, Unidentified .. and the items actually gets added to cart, but only appear on page refresh ..

what is missing here ?

Oct
31
3 weeks 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
3 weeks 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
4 weeks 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 month 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 month 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
1 month 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
1 month 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
1 month 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