Deekshith

Deekshith

Member Since 1 Year Ago

Experience Points
7,520
Total
Experience

2,480 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
27
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
7,520 XP
Nov
27
1 day ago
Activity icon

Started a new Conversation Open Quiz Based On Scheduled Date And Time In Laravel

Hi, I have a quiz listing with scheduled date and time like below,

Quiz 1 will open on 28-11-2020 11:00:00 Quiz 2 will open on 29-11-2020 15:00:00

So once scheduled date crosses users will be able to open the quiz at any time.

But the main problem is i have default time zone (date_default_timezone_set("Asia/Kolkata")) in construct function because most of the users are from India.

But if users from other countries tries to access this quiz does he get early or late access , if i set default timezone to INDIA?

Activity icon

Started a new Conversation Reset Password Should Not Same As Old Password Condition

I am trying to implement a condition in reset password page where new password should not be the same as old password. how to check this without providing the old password textbox.

i tired below code but i think hash make changes for every request,

$userDet = User::where('email',$getemail)->where('user_group',2)->first();

if ((Hash::check($userDet->password, $request->password))) {
          return json_encode(array('status'=>600,'info'=>'New password should be different from your old password'));
        }

How can i implement this? any help?

Nov
26
2 days ago
Nov
19
1 week ago
Activity icon

Started a new Conversation Integrating AWS S3 And Cloudfront With Existing Laravel Application

Hello All, I have Laravel application where we have courses in application. users purchase these courses and they can view live classes and recorded classes in their user dashboard. i am using Vimeo for this.

I am planning to change all VOD classes stream from vimeo to AWS.

my requirements are,

1.Store videos in s3 and make it secured. 2. distribute that video only for paid users and i should disable download option even paid users should not get option to download.

any websites/link to check and get some idea to implement?(I am new to aws)

Nov
18
1 week ago
Activity icon

Replied to Mail Not Working In Laravel Console Command Handle Function

i checked config both are displaying same data. i am using sendmail to send emails as of now.

php artisan demo:cron returns like below,

array:9 [
  "driver" => "mail"
  "host" => null
  "port" => null
  "from" => array:2 [
    "address" => "[email protected]"
    "name" => "Example"
  ]
  "encryption" => null
  "username" => null
  "password" => null
  "sendmail" => "/usr/sbin/sendmail -bs"
  "markdown" => array:2 [
    "theme" => "default"
    "paths" => array:1 [
      0 => "/home1/username/public_html/pathname/resources/views/vendor/mail"
    ]
  ]
]

And route returns like below in browser

array:9 [▼
  "driver" => "mail"
  "host" => null
  "port" => null
  "from" => array:2 [▼
    "address" => "[email protected]"
    "name" => "Example"
  ]
  "encryption" => null
  "username" => null
  "password" => null
  "sendmail" => "/usr/sbin/sendmail -bs"
  "markdown" => array:2 [▼
    "theme" => "default"
    "paths" => array:1 [▼
      0 => "/home1/username/public_html/pathname/resources/views/vendor/mail"
    ]
  ]
]
Activity icon

Replied to Mail Not Working In Laravel Console Command Handle Function

No i am not using any other settings and email settings are in .env file and i am using the same settings to all email in this application. i just created the console using artisan and changed the code.

Activity icon

Replied to Mail Not Working In Laravel Console Command Handle Function

no use. it will just display success message Demo:Cron Cummand Run successfully!. i have not received the mail.

Activity icon

Replied to Mail Not Working In Laravel Console Command Handle Function

@sinnbeck i tried like below,

At first i have added only log to test

public function handle()
    {

         \Log::info("Cron is working fine!");
    }

and tried below command,

php artisan demo:cron 

it worked fine and log stored in storage folder

Now i tried to replace log with mail and again ran artisan command but mail is not working.

    public function handle()
    {
        
        // \Log::info("Cron is working fine!");

        $data['messageval'] = "Task reminder";
        $data['name'] = "Deekshith";
        $email = "[email protected]";
        $subject = "Task reminder subject";

         Mail::send('emails.sendemail', $data, function ($message) use ($email,$subject) {
                  $message->from('[email protected]', 'Nervi - Nurturing Event Services');
                  $message->subject($subject);
                  $message->to($email);
                });

        // $this->info('Demo:Cron Cummand Run successfully!');
    }

The same i tried in controller and run as web request and it is working fine in controller as web request.

Activity icon

Replied to Mail Not Working In Laravel Console Command Handle Function

@sinnbeck i tired this method as well but mail is not working.

i have replaced code like below,

/**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //
        // \Log::info("Cron is working fine!");

        $data['messageval'] = "Your OTP to reset password is 456456";
        $data['name'] = "Deekshith";
        $email = "[email protected]";
        $subject = "Password Reset Email";

         Mail::send('emails.sendemail', $data, function ($message) use ($email,$subject) {
                  $message->from('[email protected]', 'Nervi - Nurturing Event Services');
                  $message->subject($subject);
                  $message->to($email);
                });

        // $mail = new WebsiteController();
        // $mail->testemail();
        // $this->info('Demo:Cron Cummand Run successfully!');
    }

But no use. But the same is working fine if i run as web request.

Activity icon

Replied to Mail Not Working In Laravel Console Command Handle Function

@automica This is my controller code,

public function testemail() {
        // return \Log::info("Cron is working fine from controller!");
        $data['messageval'] = "Message goes here";
        $data['name'] = "Deekshith";
        $email = "[email protected]";
        $subject = "Task reminder";

          Mail::send('emails.sendemail', $data, function ($message) use ($email,$subject) {
                  $message->from('[email protected]', 'Nervi - Nurturing Event Services');
                  $message->subject($subject);
                  $message->to($email);
                });

      // return 'success';
      }

Above code is working fine if i run in browser as route.

Activity icon

Started a new Conversation Mail Not Working In Laravel Console Command Handle Function

I have create a new command file for task scheduling using cron job,

DemoCron.php

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Http\Controllers\WebsiteController;

class DemoCron extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'demo:cron';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {

        // \Log::info("Cron is working fine!");

        $mail = new WebsiteController();
        $mail->testemail();
        // $this->info('Demo:Cron Cummand Run successfully!');
    }
}

kernel.php

<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
     /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        Commands\DemoCron::class,
    ];
     
    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('demo:cron')
                 ->everyMinute();
    }
     
    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');
     
        require base_path('routes/console.php');
    }
}

I tired to run below command,

php artisan demo:cron

But mail is not sending but if i run in browser using the route then it is working fine i tried to replace mail with logging for testing prupose using below code in handle function.

public function handle()
    {

         \Log::info("Cron is working fine!");
    }

I can see log generated inside storage and it is working fine but the mail is not working. Please help me.

Nov
13
2 weeks ago
Activity icon

Started a new Conversation Get Sum Of Columns In Nested Relationship.

i want to fetch sum of each columns in relationship andi have a code like below,

$userlist = LearnerCenterMap::with('learnerdetails.assignmentscores')->where('center_id',$center_id)->where('client_id',$client_id)->get();

LearnerCenterMap.php

public function learnerdetails()
    {
      return $this->hasOne('App\User','id','learner_id');
    }

User.php

public function assignmentscores()
    {
      return $this->hasMany('App\TopicAssignmentMark','learner_id','id');
    }

above code results like below,

[
  {
    "id": 1,
    "learner_id": 2,
    "center_id": 2,
    "client_id": 2,
    "active_status": 1,
    "created_at": "2020-07-28T10:34:46.000000Z",
    "updated_at": "2020-10-27T07:35:19.000000Z",
    "learnerdetails": {
      "id": 2,
      "name": "Deekshith Prakash",
      "username": "UN0009206",
      "email": "[email protected]",
      "token": "5Fh7x7LVlMjetMtZpna40zX0Iix0FOufhCia9sEjI8ux3ap0X6HB2sW2j",
      "email_verified_at": null,
      "raw_password": "[email protected]",
      "mobile": "",
      "city": null,
      "state": null,
      "address": null,
      "role": null,
      "profile_picture": "profile6.png",
      "gender": null,
      "designation": null,
      "user_role_id": 1,
      "professional_bio": "I will wear white belt",
      "active_status": 1,
      "created_at": "2020-07-06T14:12:28.000000Z",
      "updated_at": "2020-09-30T08:59:21.000000Z",
      "assignmentscores": [
        {
          "id": 1,
          "exp_center_id": 2,
          "topic_id": 47,
          "module_id": 1,
          "learner_id": 2,
          "marks_scored": 100,
          "punctuality_score": 30,
          "clarity_score": 30,
          "presentation_score": 30,
          "submission_date": "2020-11-13 17:49:01",
          "status": "graded",
          "created_at": "2020-11-13T12:19:12.000000Z",
          "updated_at": "2020-11-13T12:19:12.000000Z",
          "deleted_at": null
        },
        {
          "id": 2,
          "exp_center_id": 2,
          "topic_id": 48,
          "module_id": 1,
          "learner_id": 2,
          "marks_scored": 100,
          "punctuality_score": 20,
          "clarity_score": 20,
          "presentation_score": 20,
          "submission_date": "2020-11-13 17:56:00",
          "status": "graded",
          "created_at": "2020-11-13T12:26:05.000000Z",
          "updated_at": "2020-11-13T12:26:05.000000Z",
          "deleted_at": null
        }
      ]
    }
  }

I want to display sum of total_marks, presentation_score and punctuality_score for every learner detail. how to alter above code?

Nov
11
2 weeks ago
Activity icon

Started a new Conversation Integrating AWS S3 And Cloudfront With Existing Laravael Application

Hello All, I have laravel application where we have courses in application. users purchase these courses and they can view live classes and recorded classes in their user dashboard. i am using Vimeo for this.

I am planning to change all VOD classes stream from vimeo to AWS.

my requirements are,

  1. Store videos in s3 and make it secured.
  2. distribute that video only for paid users and i should disable download option even paid users should not get option to download. any websites/link to check and get some idea to implement?(I am new to aws)

any websites/link to check and get some idea to implement?(I am new to aws)

Nov
09
2 weeks ago
Activity icon

Started a new Conversation If Condition Inside The Query,

Hi, I have below query to get total no of questions,

Tables structre,

tests => 'test_id','test_name','test_type';
user_tests =>user_test_id,marks_scored,time_taken,user_id
questions => question_id, question_text, a,b,c,d,correct_option,question_level,language
user_answer => user_answer_id,user_test_id,question_id,user_answer,

So here i am fetching total number of easy questions user attended.

public function getQuestionLevelcorrectincorrectCount($level,$user_testids,$testids,$languages,$action)
  {

  $correctattempt = UserAnswer::leftjoin('questions','user_answers.question_id','=','questions.question_id')
                                        ->leftjoin('user_tests','user_answers.user_test_id','=','user_tests.user_test_id')
                                        ->where('user_tests.user_id',uid())
                                        ->whereIn('user_tests.user_test_id',$user_testids)
                                        ->whereIn('questions.language',$languages)
                                        ->where('questions.question_level',$level);
  /* All different scenarios */
  switch ($action) {
      case ('correct'):
          $correctattempt->whereColumn('user_answers.user_answer','questions.correct_option');
          break;
      case ('incorrect'):
          $correctattempt->whereColumn('user_answers.user_answer','!=','questions.correct_option');
          break;
  }

    return $correctattempt->count();
  }

it will return the number like 30,

So every question will have 2 marks for test_type 1 and 2.5 marks for test_type 2,

i am using below approach to calculate the marks,

if($testdet->csat > 0) {

            $cat['easy_total_marks'] = $cat['easy_total_question'] * 2.5;
            $cat['easy_marks_scored'] = round(($cat['easy_correct_attempt'] * 2.5) - ($cat['easy_incorrect_attempt'] * (5/6)),2);


          } else {

            $cat['easy_total_marks'] = $cat['easy_total_question'] * 2;
            $cat['easy_marks_scored'] = round(($cat['easy_correct_attempt'] * 2) - ($cat['easy_incorrect_attempt'] * (2/3)),2);
          }

how to put this condition in first part of query only instead of repeating in foreach? i want to edit getQuestionLevelcorrectincorrectCount() function to calculate marks as well.

Activity icon

Replied to Laravel Get Count With Nested Where Condition

Now i am trying to get only correct answers using below query,

$cat['easy_correct_attempt'] = DB::table('user_answers')
        ->leftjoin('questions','user_answers.question_id','=','questions.question_id')->leftjoin('question_categories','questions.question_category','=','question_categories.question_category_id')->leftjoin('user_tests','user_answers.user_test_id','=','user_tests.user_test_id')
        ->whereRaw(" user_answers.user_answer = questions.correct_option"
                . " and questions.question_level = 'Easy' and user_tests.user_id=$ckeck_user_id and  user_tests.user_test_id in ('$ids') and questions.language in ('$languageids')")
        ->count();

is there any way i can replace this with relationship or Eloquent way?

Activity icon

Started a new Conversation Laravel Get Count With Nested Where Condition

I Have three tables,

user_tests => user_test_id, user_id, marks_scored,time_taken, language
user_answers => user_answer_id, user_test_id, user_answer, time_taken, question_id,
question_table => question_id, question_title,description,option_a, option_b,option_c, option_d,correct_option, language, question_level

My requirement is to display all easy , medium, hard question level questions count. (here we should consider user_tests table because this table holds user completed tests)

First i am fetching details like below,

$getusertests = UserTest::where('course_id',$course_id)->where('attempt',1)->where('user_test_status',4)->where('user_id','=',uid())->groupBy('test_id')->get(['test_id','user_test_id','test_language']);
     
      $usertestids = $getusertests->pluck('user_test_id');
      $testids = $getusertests->pluck('test_id');
      $languages = $getusertests->pluck('test_language');

Above query returns all tests user completed and using pluck i am getting test id and user_test_id and languages in array format.

Now i have created one trait function to retrieve easy level questions like below,

$easy_total_questions = $this->getQuestionLevelAnalysis('Easy',$usertestids,$testids,$languages);

In trait i have written code like below,

public function getQuestionLevelAnalysis($level,$user_testids,$testids,$languages)
  {
    $easy_total_questions = UserTest::withCount(['testdet.fetchquestions' => function($q) use($languages){
                                  $q->where('question_level','Easy')
                                  ->whereIn('language',$languages);
                              }])->whereIn('test_id',$testids)
                                ->whereIn('user_test_id',$user_testids)
                                ->where('attempt',1)
                                ->where('user_test_status',4)
                                ->where('user_id','=',uid())
                                ->groupBy('test_id')
                                ->get();

    return $easy_total_questions;
  }

UserTest.php

  public function testdet()
    {
      return $this->belongsTo('App\Test','test_id','test_id');
    }

Test.php

public function fetchquestions()
    {
      return $this->hasMany('App\Question','test_id','test_id');
    }

i am getting below error,

Call to undefined method Illuminate\Database\Query\Builder::testdet.fetchquestions()

if i remove withcount and change to with then it will return. please check and is this correct way? and any shortest method to achieve this?

Activity icon

Started a new Conversation Laravel Realtionsip With Where Condition Which Matches Base Table Column Value

I Have three tables,

user_tests => user_test_id, user_id, marks_scored,time_taken, language
user_answers => user_answer_id, user_test_id, user_answer, time_taken, question_id,
question_table => question_id, question_title,description,option_a, option_b,option_c, option_d,correct_option, language

I have relationsip like below,

UserTest.php

public function fetchanswerslist()
    {
        return $this->hasMany('App\UserAnswer','user_test_id','user_test_id');
    }

User Answer.php

    public function fetchquestion()
    {
      return $this->belongsTo('App\Question','question_id','question_id');
    }

So in controller i used below code,

$usertests = UserTest::with(['fetchanswerslist.fetchquestion'])->where('course_id',$course_id)->where('user_id','=',uid())->get();

Now i want to write the condition like user_tests.language = questions.language

i have writeen a query like below but i want to rewrite using relationsip,

$usertests = UserTest::where('course_id',$course_id)->where('user_id','=',uid())->get();
 $test_array =array();
        $language_array =array();

foreach($usertests as $get_user) {
          array_push($arr_ids,$get_user->user_test_id);
		array_push($test_array,$get_user->test_id);
          array_push($language_array,$get_user->test_language);
        }

        $ids = join("','",$arr_ids);

        $languageids = join("','",$language_array);

        //easy questions
        $cat['easy_correct_attempt'] = DB::table('user_answers')
        ->leftjoin('questions','user_answers.question_id','=','questions.question_id')->leftjoin('question_categories','questions.question_category','=','question_categories.question_category_id')->leftjoin('user_tests','user_answers.user_test_id','=','user_tests.user_test_id')
        ->whereRaw(" user_answers.user_answer = questions.correct_option"
                . " and questions.question_level = 'Easy' and user_tests.user_id=$ckeck_user_id and  user_tests.user_test_id in ('$ids') and questions.language in ('$languageids')")
        ->count();

How to write above query in relationship? as i want match the column value of base table with join/relationship table

Nov
03
3 weeks ago
Activity icon

Replied to Laravel Route Access Thorttling

@laracoft thank you for the clarification.

Activity icon

Started a new Conversation Laravel Route Access Thorttling

I have the route like below,

Route::get('otp-verify','[email protected])->middleware('ThrottleRequestsWithCustomResponse:2,2,resendotp');

Middleware code,

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Routing\Middleware\ThrottleRequests as BaseThrottleRequests;

class ThrottleRequestsWithCustomResponse extends BaseThrottleRequests
{

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @param  int $maxAttempts
     * @param  int $decayMinutes
     * @return mixed
     */
    public function handle($request, Closure $next, $maxAttempts = 60, $decayMinutes = 1, $prefix = '')
    {
        $key = $prefix.$this->resolveRequestSignature($request);

        $maxAttempts = $this->resolveMaxAttempts($request, $maxAttempts);

        if ($this->limiter->tooManyAttempts($key, $maxAttempts)) {
            return $this->buildJsonResponse($key, $maxAttempts);
        }

        $this->limiter->hit($key, $decayMinutes);

        $response = $next($request);

        return $this->addHeaders(
            $response, $maxAttempts,
            $this->calculateRemainingAttempts($key, $maxAttempts)
        );
    }

    /**
     * Create a 'too many attempts' JSON response.
     *
     * @param  string  $key
     * @param  int  $maxAttempts
     * @return \Symfony\Component\HttpFoundation\Response
     */
    protected function buildJsonResponse($key, $maxAttempts)
    {


        $retryAfter = $this->limiter->availableIn($key);

        $response = response()->json(['message' => 'Too many attempts, Please try after '.$retryAfter .' seconds',
        ], 429);

        return $this->addHeaders(
            $response, $maxAttempts,
            $this->calculateRemainingAttempts($key, $maxAttempts, $retryAfter),
            $retryAfter
        );
    }
}

here when user access this route continuously two times then he will be blocked for 2 minutes. and if he enters any other mobile number and tried to verify OTP then it will not work until 2 minutes.

In another case, i have another option to change mobile number in user profile so here also they should confirm OTP before changing mobile number.

So once userccess this route continuously two times then he will be blocked for 2 minutes. consider i logged out from that account and logged in to different account and tried to access same route but it will allow and it will remain blocked only for that previous user,

But in first scenario it will block for all users.

What's the logic here? when logged in does user id linked with throttle?

Nov
02
3 weeks ago
Activity icon

Started a new Conversation Laravel Route Throttling When Logged In And Logged Out

I am using custom throttling for rate access limit , i am using this for resend OTP feature one use can resend OTP for 5 times after that he will be blocked for next 3 hours. i have observed below points,

without login when user try to resend OTP then i block user after 5 attempts. and if different mobile number entered and tried to resend OTP then it will show try after some time error as well as i assume it will block IP, => here enter any user mobile number and generate OTP once you blocked you will be able to access this route only after mentioned time for any mobile number.

but in second approach consider user logged in to the portal and in settings he tries to update mobile number and again i have given Confirm otp and resend otp option here if i cross the limit for resend otp which is 5 then i will get please try after some time as expected and if logged in as different user then i can able to resend OTP. => here if one logged in user gets blocked for a particular route then i will logout and try to login different account and access the same URL and it will allow.

is this because after login user id /email linked with the block?

Oct
31
4 weeks ago
Activity icon

Replied to Laravel Facebook And Google Signin With Javascript SDK

@tisuchi my code will go like this after socialite installation and no need to do that manual verification right ? socialite will take care of this?

$user = Socialite::driver('google')->user();

$check_for_email = User::where('email',$user->email)->where('user_group',2)->first();

if($check_for_email) {
if(Auth::loginUsingId($check_for_email->user_id, true))
            session()->put('social_login', 2);
            $check_for_email->update(['login_type'=>'FB']);
          return json_encode(array('status'=>200,'info'=>'Login Success'));
}

Activity icon

Replied to Laravel Facebook And Google Signin With Javascript SDK

Thank you so much. i will upgrade to socialite and will compare email fields to allow from both google and facebook who has same email linked with both .

Activity icon

Replied to Laravel Facebook And Google Signin With Javascript SDK

at first i am verifying the login using google/facebook API whether this is legitimate or not if it is success then checking that email already exists in db if it is exists letting him to the dashboard in controller using below code, if not exists i will create new account and redirects to OTP page where he should add mobile number and confirm OTP.

$check_for_email = User::where('email',$email)->where('user_group',2)->first();

if($check_for_email) {
if(Auth::loginUsingId($check_for_email->user_id, true))
            session()->put('social_login', 2);
            $check_for_email->update(['login_type'=>'FB']);
          return json_encode(array('status'=>200,'info'=>'Login Success'));
}

same happens with google too,

Activity icon

Replied to Laravel Facebook And Google Signin With Javascript SDK

@tisuchi 3 years back i did this. but now if i upgrade to socialite then i should match with google_id and facebook_id. if i want to match only email will it cause any security issue? Example:

User first registers using facebook with email : [email protected] and he has gmail account too with the same email And again if he tries to login using same email linked gmail account then i should allow him to login,

for this i should put socialite condition like below,

$check_for_email = User::where('email',$email)->first();

more than 20k users have already created using this method. does this cause any issue if i match only email in socialite on login instead of facebook_id or google_id.

Activity icon

Started a new Conversation Laravel Facebook And Google Signin With Javascript SDK

In one of the application i have used facebook JavaScript SDK for login purpose and also used google signin sdk too. i have used below approach when user first click Facebook login it will check for email exists or not if exists it will login if not then it will create new account and redirects.

If again user tries to login using google with same email address then i am allowing user to login to his previous account and i am just collecting the AUTH token and i am not comparing while logging in.

check the Facebook controller logic below,

///////////////////////////////////////
        // prep Facebook verification
        ///////////////////////////////////////

        // sanitize login data
        $facebook_access_token = filter_var($accesstoken, FILTER_SANITIZE_STRING);

        // set variables
        $facebook_user_access_token = $facebook_access_token;
        $my_facebook_app_id = config('constants.fb.facebook_app_id');
        $my_facebook_app_secret = config('constants.fb.facebook_secret_key');
        $facebook_application = 'My Portal'; // in my case 'domain.com', as set up in Facebook

        ///////////////////////////////////////
        // get facebook access token
        ///////////////////////////////////////
        $curl_facebook1 = curl_init(); // start curl
        $url = "https://graph.facebook.com/oauth/access_token?client_id=".$my_facebook_app_id."&client_secret=".$my_facebook_app_secret."&grant_type=client_credentials"; // set url and parameters
        curl_setopt($curl_facebook1, CURLOPT_URL, $url); // set the url variable to curl
        curl_setopt($curl_facebook1, CURLOPT_RETURNTRANSFER, true); // return output as string
        $output = curl_exec($curl_facebook1); // execute curl call
        curl_close($curl_facebook1); // close curl
        $decode_output = json_decode($output, true); // decode the response (without true this will crash)

        // store access_token
        $facebook_access_token = $decode_output['access_token'];

	///////////////////////////////////////
        // verify my access was legitimate
        ///////////////////////////////////////
        $curl_facebook2 = curl_init(); // start curl
        $url = "https://graph.facebook.com/debug_token?input_token=".$facebook_user_access_token."&access_token=".$facebook_access_token; // set url and parameters
        curl_setopt($curl_facebook2, CURLOPT_URL, $url); // set the url variable to curl
        curl_setopt($curl_facebook2, CURLOPT_RETURNTRANSFER, true); // return output as string
        $output2 = curl_exec($curl_facebook2); // execute curl call
        curl_close($curl_facebook2); // close curl
        $decode_output2 = json_decode($output2, true); // decode the response (without true this will crash)

 // test browser and Facebook variables match for security
        if ($my_facebook_app_id == $decode_output2['data']['app_id'] && $decode_output2['data']['application'] == $facebook_application && $decode_output2['data']['is_valid'] == true) {
	//success
	$check_for_email = User::where('email',$email)->first();

	//if email exists then login or create new account

} else {
	//show email not found and error message
}

is this okay if i match only email and allow both google and facebook signin if they have same email address linked? i am using below condition if facebook/google login is success

$check_for_email = User::where('email',$email)->first();
Activity icon

Replied to Suggestion For Facebook Login Security

Any suggestions?

Oct
30
4 weeks ago
Activity icon

Started a new Conversation Suggestion For Facebook Login Security

I am using javascipt facebook login SDK for facebook login in my laravel application 3 years back and i have not used socialite for this,

and in controller i have written a code like below,

///////////////////////////////////////
        // prep Facebook verification
        ///////////////////////////////////////

        // sanitize login data
        $facebook_access_token = filter_var($accesstoken, FILTER_SANITIZE_STRING);

        // set variables
        $facebook_user_access_token = $facebook_access_token;
        $my_facebook_app_id = config('constants.fb.facebook_app_id');
        $my_facebook_app_secret = config('constants.fb.facebook_secret_key');
        $facebook_application = 'My Portal'; // in my case 'domain.com', as set up in Facebook

        ///////////////////////////////////////
        // get facebook access token
        ///////////////////////////////////////
        $curl_facebook1 = curl_init(); // start curl
        $url = "https://graph.facebook.com/oauth/access_token?client_id=".$my_facebook_app_id."&client_secret=".$my_facebook_app_secret."&grant_type=client_credentials"; // set url and parameters
        curl_setopt($curl_facebook1, CURLOPT_URL, $url); // set the url variable to curl
        curl_setopt($curl_facebook1, CURLOPT_RETURNTRANSFER, true); // return output as string
        $output = curl_exec($curl_facebook1); // execute curl call
        curl_close($curl_facebook1); // close curl
        $decode_output = json_decode($output, true); // decode the response (without true this will crash)

        // store access_token
        $facebook_access_token = $decode_output['access_token'];

	///////////////////////////////////////
        // verify my access was legitimate
        ///////////////////////////////////////
        $curl_facebook2 = curl_init(); // start curl
        $url = "https://graph.facebook.com/debug_token?input_token=".$facebook_user_access_token."&access_token=".$facebook_access_token; // set url and parameters
        curl_setopt($curl_facebook2, CURLOPT_URL, $url); // set the url variable to curl
        curl_setopt($curl_facebook2, CURLOPT_RETURNTRANSFER, true); // return output as string
        $output2 = curl_exec($curl_facebook2); // execute curl call
        curl_close($curl_facebook2); // close curl
        $decode_output2 = json_decode($output2, true); // decode the response (without true this will crash)

 // test browser and Facebook variables match for security
        if ($my_facebook_app_id == $decode_output2['data']['app_id'] && $decode_output2['data']['application'] == $facebook_application && $decode_output2['data']['is_valid'] == true) {
	//success
	$check_for_email = User::where('email',$email)->first();

	//if email exists then login or create new account

} else {
	//show email not found and erro mesage
}

Here i am checking only email because i was not storing user id or auth id of facebook login instead i was just checking for email exists or not. is this correct way or do i need to rewrite this ?

and if user registered using facebook and if user uses google signin with same email then he is allowed to login by verifying gmail token. does this cause any security issue?

Activity icon

Replied to Add Extra Parameter Or Query String To Socialite Google Signin

@gitwithravish i have already implemented this. my question is i want to change call back URL in two cases if user directly goes to login page then he will redirects to his profile page if he comes to login page during checkout then i should redirect him to checkout page instead of profile page so i am trying to fetch by passing optional parameter which has suggested in documentation but it is not working.

Oct
29
4 weeks ago
Activity icon

Started a new Conversation Add Extra Parameter Or Query String To Socialite Google Signin

I am using laravel socialite


public function redirectToGoogle()
    {	
    	

       return Socialite::driver('google')->with(['redirect' => $redirect])->redirect();
    }


i tried to $request->all() for above response but not getting redirect value.

I want to add query string like redirectto?=http://localhost/project/checkout

so when user logs in with facebook based on redrect query string i should redirect the user.

Oct
28
1 month ago
Activity icon

Replied to Jsonserialize Error In Sendgrid And Laravel Batch Email

@rodrigo.pedra please ignore above request i solved it. i dont know why it is not taking from config file. if i put values directly then it is working. i have cleared cache everything.

Activity icon

Replied to Jsonserialize Error In Sendgrid And Laravel Batch Email

@rodrigo.pedra and i could see that from dashboard i have verified the domain to prevent via sendgrid.net but it is still showing via sendgrid.net i want to display my domain instead

Activity icon

Replied to Jsonserialize Error In Sendgrid And Laravel Batch Email

@rodrigo.pedra yes response status is helpful. thank you

Activity icon

Replied to Jsonserialize Error In Sendgrid And Laravel Batch Email

@rodrigo.pedra perfect you are a life saver. thank you so much

Activity icon

Replied to Jsonserialize Error In Sendgrid And Laravel Batch Email

@rodrigo.pedra {"status":200,"info":{"status":"400-{"errors":[{"message":"Invalid type. Expected: object, given: string.","field":"personalizations.0.to.0","help":"http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.personalizations.to"},{"message":"Invalid type. Expected: object, given: string.","field":"personalizations.1.to.0","help":"http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.personalizations.to"}]}"}}

Activity icon

Replied to Jsonserialize Error In Sendgrid And Laravel Batch Email

@rodrigo.pedra i have used your code and called below serives sendgrid function

 public static function sendBulkEmail($subject, $sendgridPersonalization, $content = '')
    {
        $chunkedUsers = array_chunk($sendgridPersonalization, 1000, true);
        $sendgridApiKey = \Config::get('services.sendgrid_key');
        $setupEmail = \Config::get('mail.from.address');
        $setupEmailName = \Config::get('mail.from.name');
        $sendgrid = new \SendGrid($sendgridApiKey);

        foreach ($chunkedUsers as $singleChunk) {
            $email = new SendgridMail();
            $email->setFrom($setupEmail, $setupEmailName);
            $email->setSubject($subject);
            // $email->addTo($setupEmail);
            $email->addContent("text/html", $content);
            foreach ($singleChunk as $personalization) {
                $email->addPersonalization($personalization);
            }
            try {
                // Send in batch of 1000 users
                $response = $sendgrid->send($email);
            } catch (Exception $e) {
                return array(
                    'status' => false,
                    'message' => 'Failed to send bulk email. Error message: ' . $e->getMessage()
                );
            }
        }
        return array('status' => true);
    }

it shows true but mails are not sending. i have commented addto in above function becuase in your code you are assigning add to to personlization.

Activity icon

Replied to Jsonserialize Error In Sendgrid And Laravel Batch Email

@rodrigo.pedra thank you i am using sendgrid 7.6 and i have written this in services sendgrid.php how to change that file?

Activity icon

Replied to Jsonserialize Error In Sendgrid And Laravel Batch Email

@laracoft

{
    "message": "Call to a member function jsonSerialize() on array",
    "exception": "Error",
    "file": "/home/customer/www//public_html/vendor/sendgrid/sendgrid/lib/mail/Mail.php",
    "line": 1764,
    "trace": [
        {
            "function": "SendGrid\Mail\{closure}",
            "class": "SendGrid\Mail\Mail",
            "type": "::"
        },
        {
            "file": "/home/customer/www//public_html/vendor/sendgrid/sendgrid/lib/mail/Mail.php",
            "line": 1765,
            "function": "array_filter"
        },
        {
            "function": "jsonSerialize",
            "class": "SendGrid\Mail\Mail",
            "type": "->"
        },
        {
            "file": "/home/customer/ww/public_html/vendor/sendgrid/php-http-client/lib/Client.php",
            "line": 362,
            "function": "json_encode"
        },
        {
            "file": "/home/customer/www/public_html/vendor/sendgrid/php-http-client/lib/Client.php",
            "line": 461,
            "function": "createCurlOptions",
            "class": "SendGrid\Client",
            "type": "->"
        },
        {
            "file": "/home/customer/www/public_html/vendor/sendgrid/php-http-client/lib/Client.php",
            "line": 596,
            "function": "makeRequest",
            "class": "SendGrid\Client",
            "type": "->"
        },
        {
            "file": "/home/customer/wwwpublic_html/vendor/sendgrid/sendgrid/lib/BaseSendGridClientInterface.php",
            "line": 65,
            "function": "__call",
            "class": "SendGrid\Client",
            "type": "->"
        },
        {
            "file": "/home/customer/www/public_html/app/Services/Sendgrid.php",
            "line": 36,
            "function": "send",
            "class": "BaseSendGridClientInterface",
            "type": "->"
        },
        {
            "file": "/home/customer/www/public_html/app/Http/Controllers/DashboardController.php",
            "line": 119,
            "function": "sendBulkEmail",
            "class": "App\Services\Sendgrid",
            "type": "::"
        },
        {
            "function": "postSendEmail",
            "class": "App\Http\Controllers\DashboardController",
            "type": "->"
        },

i am using sendgrid library and it is giving in this line,

in controller,

$resultBulkEmail = Sendgrid::sendBulkEmail(
            $subject_text,
            $sendgridPersonalization,
            view('emails.updateemail')->render()
        );

in sendgrid service file,


$response = $sendgrid->send($email);

Activity icon

Started a new Conversation Jsonserialize Error In Sendgrid And Laravel Batch Email

I am trying to send bulk email using sendgrid API and laravel,

controller code is,

$subject_text = $subjectval;

        $clickurl = "https://www.example.com";

        $sendgridPersonalization = [];
        

        foreach ($usersDet as $user) {
            array_push(
                $sendgridPersonalization,
                [
                    'to' => [[ 'email' => $user->email ]],
                    'substitutions' => [
                        '%first_name%' => $user->name,
                        '%subject_text%' => $subject_text,
                        '%message_body%' => $messagebody,
                        '%clikc_url%' => $clickurl,
                    ]
                ]
            );
        }

        // Send bulk emails through sendgrid API
        $resultBulkEmail = Sendgrid::sendBulkEmail(
            $subject_text,
            $sendgridPersonalization,
            view('emails.updateemail')->render()
        );

        // return $resultBulkEmail;
        if(!$resultBulkEmail['status']) {

        	return json_encode(array('status'=>500,'info'=>'Email sending failed!'));

            // return redirect()->back()->withErrors('Email sending failed!');
        }

        return json_encode(array('status'=>200,'info'=>'Successfully sent email'));

App\Services\Sendgrid.php

<?php
namespace App\Services;
use SendGrid\Mail\Mail as SendgridMail;
class Sendgrid
{
    /**
     * Send bulk email using sendgrid API key
     * Chunk the requests in with set of 1000 users
     *
     * @param string $subject
     * @param array $sendgridPersonalization
     * @param string $content
     * @return array
     * @throws Exception
     */
    public static function sendBulkEmail($subject, $sendgridPersonalization, $content = '')
    {
        $chunkedUsers = array_chunk($sendgridPersonalization, 1000, true);
        $sendgridApiKey = \Config::get('services.sendgrid_key');
        $setupEmail = \Config::get('mail.from.address');
        $setupEmailName = \Config::get('mail.from.name');
        $sendgrid = new \SendGrid($sendgridApiKey);

        foreach ($chunkedUsers as $singleChunk) {
            // return $singleChunk;
            $email = new SendgridMail();
            $email->setFrom($setupEmail, $setupEmailName);
            $email->setSubject($subject);
            $email->addTo($setupEmail);
            $email->addContent("text/html", $content);
            foreach ($singleChunk as $personalization) {
                $email->addPersonalization($personalization);
            }
            try {
                // Send in batch of 1000 users
                $response = $sendgrid->send($email);
            } catch (Exception $e) {
                return array(
                    'status' => false,
                    'message' => 'Failed to send bulk email. Error message: ' . $e->getMessage()
                );
            }
        }
        return array('status' => true);
    }
}

?>

But when i try to execute this i am getting below error,

 "message": "Call to a member function jsonSerialize() on array",
    "exception": "Error",
    "file": "/home/customer/www/ww.xample.com/public_html/vendor/sendgrid/sendgrid/lib/mail/Mail.php",
    "line": 1764,
Oct
27
1 month ago
Activity icon

Replied to Lravel Notiy Inside Foreach Is Very Slow

@snapey right now i am trying to send emails when we post new article in web application so we have users table and we fetch the user emails and write mail code to send email. this direct approach is very slow in this case because i have more than 5000+ emails. as my cloud server is siteground they dont allow me to install supervisor too. it would be really helpful if you can explain how can i sort this out with cron?

and where to use this command?

$schedule->command('queue:restart')
    ->everyFiveMinutes();

$schedule->command('queue:work --daemon')
    ->everyMinute()
    ->withoutOverlapping();


above code does cause any mysql connection issue?

I want to send bulk email when we post new update in the website. every day we will post at least 1 post.

Activity icon

Replied to Sort Data On Relationship With Hasmany

i have a username with below format , if username is : UN0001605

constant is: "UN000";

dynamic values will be displayed after constant so here 1605 is the dynamic value i am trying to sort this using below query,

$userlist = $userlist->orderByRaw('LENGTH(users.username)','desc')->orderBy('users.username','desc');


it is not working any wrong in this?

Activity icon

Replied to Sort Data On Relationship With Hasmany

@sinnbeck sorry edited the question

Activity icon

Started a new Conversation Sort Data On Relationship With Hasmany

i have two tables one is learner_map and another is users

learner_map contains below colums,

id, user_id, center_id, client_id

users table contants

id, name,email,mobile,gender,username,

Now to display all mapped users to a particular center i used below query,

$userlist = LearnerCenterMap::with('learnerdetails')->where('center_id',$center_id)->where('client_id',$client_id)->get();

LearnerCenterMap.php

public function learnerdetails()
    {
      return $this->hasOne('App\User','id','learner_id');
    }

Above query displays data like below,

[
  {
    "id": 1,
    "learner_id": 2,
    "center_id": 2,
    "client_id": 2,
    "active_status": 1,
    "created_at": "2020-07-28T10:34:46.000000Z",
    "updated_at": "2020-10-27T07:35:19.000000Z",
    "learnerdetails": {
      "id": 2,
      "name": "Deekshith Prakash",
      "username": "UN0009206",
      "email": "[email protected]",
      "token": "token",
      "email_verified_at": null,
      "raw_password": "[email protected]",
      "mobile": "",
      "city": null,
      "state": null,
      "address": null,
      "role": null,
      "profile_picture": "profile6.png",
      "gender": null,
      "designation": null,
      "user_role_id": 1,
      "professional_bio": "I will wear white belt",
      "active_status": 1,
      "created_at": "2020-07-06T14:12:28.000000Z",
      "updated_at": "2020-09-30T08:59:21.000000Z"
    }
  },
  {
    "id": 2,
    "learner_id": 55,
    "center_id": 2,
    "client_id": 2,
    "active_status": 1,
    "created_at": "2020-07-28T10:34:46.000000Z",
    "updated_at": "2020-10-27T07:35:19.000000Z",
    "learnerdetails": {
      "id": 55,
      "name": "Deekshith 2",
      "username": "UN0001605",
      "email": "",
      "token": "token",
      "email_verified_at": null,
      "raw_password": "QLvgywiw",
      "mobile": "",
      "city": null,
      "state": null,
      "address": null,
      "role": null,
      "profile_picture": null,
      "gender": "Male",
      "designation": "",
      "user_role_id": 1,
      "professional_bio": null,
      "active_status": 1,
      "created_at": "2020-07-28T10:34:46.000000Z",
      "updated_at": "2020-07-28T10:34:46.000000Z"
    }
  },
  {
    "id": 3,
    "learner_id": 56,
    "center_id": 2,
    "client_id": 2,
    "active_status": 1,
    "created_at": "2020-07-28T10:34:46.000000Z",
    "updated_at": "2020-10-27T07:35:19.000000Z",
    "learnerdetails": {
      "id": 56,
      "name": "Deekshith 3",
      "username": "UN0005017",
      "email": "",
      "token": "token",
      "email_verified_at": null,
      "raw_password": "ixGMJ06q",
      "mobile": "",
      "city": null,
      "state": null,
      "address": null,
      "role": null,
      "profile_picture": null,
      "gender": "",
      "designation": "",
      "user_role_id": 1,
      "professional_bio": null,
      "active_status": 1,
      "created_at": "2020-07-28T10:34:46.000000Z",
      "updated_at": "2020-07-28T10:34:46.000000Z"
    }
  },
  {
    "id": 4,
    "learner_id": 57,
    "center_id": 2,
    "client_id": 2,
    "active_status": 1,
    "created_at": "2020-07-28T10:34:46.000000Z",
    "updated_at": "2020-10-27T07:35:19.000000Z",
    "learnerdetails": null
  },
  {
    "id": 5,
    "learner_id": 58,
    "center_id": 2,
    "client_id": 2,
    "active_status": 1,
    "created_at": "2020-07-28T10:34:46.000000Z",
    "updated_at": "2020-10-27T07:35:19.000000Z",
    "learnerdetails": {
      "id": 58,
      "name": "Deekshith 5",
      "username": "UN0004658",
      "email": "",
      "token": "token",
      "email_verified_at": null,
      "raw_password": "l9QuVrnH",
      "mobile": "mobile number",
      "city": null,
      "state": null,
      "address": null,
      "role": null,
      "profile_picture": null,
      "gender": "",
      "designation": "",
      "user_role_id": 1,
      "professional_bio": null,
      "active_status": 1,
      "created_at": "2020-07-28T10:34:46.000000Z",
      "updated_at": "2020-07-28T10:34:46.000000Z"
    }
  },
  {
    "id": 6,
    "learner_id": 59,
    "center_id": 2,
    "client_id": 2,
    "active_status": 1,
    "created_at": "2020-07-28T10:34:46.000000Z",
    "updated_at": "2020-10-27T07:35:19.000000Z",
    "learnerdetails": {
      "id": 59,
      "name": "Deekshith 6",
      "username": "UN00023",
      "email": "email",
      "token": "token",
      "email_verified_at": null,
      "raw_password": "G5SkxtZ8",
      "mobile": "",
      "city": null,
      "state": null,
      "address": null,
      "role": null,
      "profile_picture": null,
      "gender": "Male ",
      "designation": "Tester",
      "user_role_id": 1,
      "professional_bio": null,
      "active_status": 1,
      "created_at": "2020-07-28T10:34:46.000000Z",
      "updated_at": "2020-07-28T10:34:46.000000Z"
    }
  },
  {
    "id": 7,
    "learner_id": 60,
    "center_id": 2,
    "client_id": 2,
    "active_status": 1,
    "created_at": "2020-07-28T10:34:46.000000Z",
    "updated_at": "2020-10-27T07:35:19.000000Z",
    "learnerdetails": {
      "id": 60,
      "name": "name",
      "username": "UN0006774",
      "email": "email",
      "token": "tokenval",
      "email_verified_at": null,
      "raw_password": "9OjYoJrm",
      "mobile": "mobile number",
      "city": null,
      "state": null,
      "address": null,
      "role": null,
      "profile_picture": null,
      "gender": "Male",
      "designation": "Designation",
      "user_role_id": 1,
      "professional_bio": null,
      "active_status": 1,
      "created_at": "2020-07-28T10:34:46.000000Z",
      "updated_at": "2020-07-28T10:34:46.000000Z"
    }
  },
  {
    "id": 40,
    "learner_id": 87,
    "center_id": 2,
    "client_id": 2,
    "active_status": 1,
    "created_at": "2020-10-23T10:12:59.000000Z",
    "updated_at": "2020-10-27T07:35:19.000000Z",
    "learnerdetails": null
  }
]

Now i am applying sort by username and alerted like below when users click sort by name,

$userlist = LearnerCenterMap::with(['learnerdetails' => function($q) {

							$q->orderBy('username','asc');

							}])->where('center_id',$center_id)->where('client_id',$client_id)->get();

but above query applies sort only for learnerdetails how can i apply sort for base table LearnerCenterMap also? once user clicks sort then learnercentermap data should be sorted along with learner details as well.

Activity icon

Replied to Read Bar Code And Return The Value Of Barcode

@tray2 this is for generator and thank you and also i need the reader to be implemented in browser itself just like this.

https://webqr.com/

and shall i store user roll number in qr code instead of bar code?

Activity icon

Started a new Conversation Read Bar Code And Return The Value Of Barcode

I am trying to create bar codes for each students and i want to give camera or video icon in browser where admin opens the website in browser and click on that icon and camera or video should open in browser itself and it returns the value. is there any way to achieve this? i found for qr code but not a barcode. any suggestions?

Oct
25
1 month ago
Activity icon

Replied to Lravel Notiy Inside Foreach Is Very Slow

@snapey Thank you i will try this.