Deekshith

Member Since 2 Years Ago

Experience Points
8,950
Total
Experience

1,050 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.

  • Community Pillar

    Earned once your experience points ranks in the top 10 of all Laracasts users.

Level 2
8,950 XP
Jan
25
3 days ago
Activity icon

Replied to Search User With Hasone Relationsip

Thank you will check this.

Activity icon

Started a new Conversation Search User With Hasone Relationsip

I have relationsip like below between user and store,

User.php

public function vendorstore()
    {
        return $this->hasOne('App\Store');
    }

Now i have a search button in user listing page and the format of user data and store is like below,


{
  "current_page": 1,
  "data": [
    {
      "id": 285,
      "role_id": "2",
      "name": "yyy",
      "email": "[email protected]",
      "mobile": "639639639",
      "city": "Mysore",
      "otp": null,
      "otp_status": "1",
      "added_by": "Admin",
      "added_by_id": "0",
      "status": "1",
      "package": "0",
      "created_at": "2021-01-19 11:24:37",
      "updated_at": "2021-01-19 11:24:37",
      "vendorstore": null
    },
    {
      "id": 280,
      "role_id": "2",
      "name": "xxy",
      "email": "[email protected]",
      "mobile": "8528528528",
      "city": "Mysore",
      "otp": "939419",
      "otp_status": "1",
      "added_by": "User",
      "added_by_id": "0",
      "status": "1",
      "package": "4",
      "created_at": "2021-01-07 13:17:09",
      "updated_at": "2021-01-07 13:18:16",
      "vendorstore": {
        "id": 168,
        "title": "Vendor Store",
        "store_slug": "vendor-store",
        "description": "<p>Store</p>",
        "user_id": "280",
        "city_id": "1",
        "area_id": "2",
        "state_id": "1",
        "address": "no 86",
        "cover_photo": "1610005856.jpg",
        "contact_numbers": "852852",
        "main_phone": "74123",
        "website": null,
        "year_established": null,
        "banner_image": "bannerimage_1610005855.jpg",
        "status": "1",
        "feature": "0",
        "created_at": "2021-01-07 13:20:56",
        "updated_at": "2021-01-07 13:21:02"
      }
    },
    
  ],
  "first_page_url": "https://localhost/admin/create-vendors?page=1",
  "from": 1,
  "last_page": 7,
  "last_page_url": "http://localhost/create-vendors?page=7",
  "next_page_url": "https://localhost/admin/create-vendors?page=2",
  "path": "https://localhost/demosite/admin/create-vendors",
  "per_page": 30,
  "prev_page_url": null,
  "to": 30,
  "total": 182
}

i should display user details if search matches user name, email,mobile and store name too. how to search and display relationship data too. i have code like below but not working,

$vendors = User::with('vendorstore')->where('role_id',2)->where(function($q) use($searchval) {
                                  $q->where('email', 'like', '%' . $searchval . '%')
                                  ->orWhere('mobile','like', '%' . $searchval . '%')
                                  ->orWhere('name','like', '%' . $searchval . '%');
                                })->whereHas('vendorstore', function($q) use($searchval){
                                  $q->where('title', 'like', '%' . $searchval . '%');
                                })->orderBy('created_at','DESC')
                                ->paginate(30);

Any help?

Jan
19
1 week ago
Activity icon

Started a new Conversation Nested Relationship Mapping

I have three models

Modules.php ModuleTopics.php TopicCompleted.php

Now every course will have modules and modules will have topics and user completes the topic and i should show which all the modules completed and which module is ongoing. i have a query like below,

$collectionarr = collect();

$coursemodules = Module::with(['topicsdet.learner_topic_status_detail' => function($q) use($userid) {
                                            $q->where('learner_id',$userid);
                                        }])
                                        ->has('topicsdet')
                                        ->where('course_id',1)
                                        ->where('active_status',1)
                                        ->orderBy('id','ASC')
                                        ->get();

$collectionarr->put('modules',$coursemodules);

response is,

{
  "modulename": [
    {
      "id": 32,
      "course_id": 7,
      "module_name": "Introduction",
      "module_icon": "module_icon1609911976.png",
      "slug": "introduction",
      "description": null,
      "active_status": 1,
      "priority": 26,
      "created_at": "2021-01-06T05:46:16.000000Z",
      "updated_at": "2021-01-06T05:46:16.000000Z",
      "topicsdet": [
        {
          "id": 176,
          "module_id": 32,
          "topic_type": "Topic",
          "topic_name": "Welcome",
          "slug": "welcome-2",
          "topic_date": null,
          "active_status": 1,
          "priority": 1,
          "no_of_min": null,
          "marks": null,
          "passing_marks": null,
          "pointtype": null,
          "challenge_instructions": null,
          "challenge_type": null,
          "bb_qsn_num": null,
          "level": null,
          "assignment_file1": null,
          "assignment_file2": null,
          "assignment_google_drive": null,
          "assignment_other_link": null,
          "assignment_total_marks": 0,
          "assignment_due_date": null,
          "assignment_submission_type": "individual",
          "created_at": "2021-01-06T05:46:36.000000Z",
          "updated_at": "2021-01-08T09:36:46.000000Z",
          "learner_topic_status_detail": {
            "id": 55,
            "learner_id": 208,
            "type": "Topic",
            "learner_content_topic_map_id": 88,
            "exp_center_id": 4,
            "course_id": 7,
            "module_id": 32,
            "topic_id": 176,
            "completed_date": "2021-01-18 00:00:00",
            "created_at": "2021-01-18T06:02:03.000000Z",
            "updated_at": "2021-01-18T06:02:03.000000Z"
          }
        },
        {
          "id": 177,
          "module_id": 32,
          "topic_type": "Topic",
          "topic_name": "Communication",
          "slug": "communcation",
          "topic_date": null,
          "active_status": 1,
          "priority": 2,
          "no_of_min": null,
          "marks": null,
          "passing_marks": null,
          "pointtype": null,
          "challenge_instructions": null,
          "challenge_type": null,
          "bb_qsn_num": null,
          "level": null,
          "assignment_file1": null,
          "assignment_file2": null,
          "assignment_google_drive": null,
          "assignment_other_link": null,
          "assignment_total_marks": 0,
          "assignment_due_date": null,
          "assignment_submission_type": "individual",
          "created_at": "2021-01-06T05:46:55.000000Z",
          "updated_at": "2021-01-08T09:36:46.000000Z",
          "learner_topic_status_detail": {
            "id": 56,
            "learner_id": 208,
            "type": "Topic",
            "learner_content_topic_map_id": 89,
            "exp_center_id": 4,
            "course_id": 7,
            "module_id": 32,
            "topic_id": 177,
            "completed_date": "2021-01-18 00:00:00",
            "created_at": "2021-01-18T06:02:11.000000Z",
            "updated_at": "2021-01-18T06:02:11.000000Z"
          }
        },
        {
          "id": 178,
          "module_id": 32,
          "topic_type": "Topic",
          "topic_name": "Problem Solving",
          "slug": "problem-solving",
          "topic_date": null,
          "active_status": 1,
          "priority": 3,
          "no_of_min": null,
          "marks": null,
          "passing_marks": null,
          "pointtype": null,
          "challenge_instructions": null,
          "challenge_type": null,
          "bb_qsn_num": null,
          "level": null,
          "assignment_file1": null,
          "assignment_file2": null,
          "assignment_google_drive": null,
          "assignment_other_link": null,
          "assignment_total_marks": 0,
          "assignment_due_date": null,
          "assignment_submission_type": "individual",
          "created_at": "2021-01-06T05:47:16.000000Z",
          "updated_at": "2021-01-08T09:36:46.000000Z",
          "learner_topic_status_detail": {
            "id": 57,
            "learner_id": 208,
            "type": "Topic",
            "learner_content_topic_map_id": 90,
            "exp_center_id": 4,
            "course_id": 7,
            "module_id": 32,
            "topic_id": 178,
            "completed_date": "2021-01-18 00:00:00",
            "created_at": "2021-01-18T06:02:17.000000Z",
            "updated_at": "2021-01-18T06:02:17.000000Z"
          }
        },
        {
          "id": 179,
          "module_id": 32,
          "topic_type": "Quick Challenge",
          "topic_name": "Assess 1",
          "slug": "assess-1",
          "topic_date": null,
          "active_status": 1,
          "priority": 4,
          "no_of_min": "2",
          "marks": 50,
          "passing_marks": 100,
          "pointtype": "Credits",
          "challenge_instructions": "<p><span style=\"font-size:26px\">Select the correct answer</span></p>",
          "challenge_type": "MCQ",
          "bb_qsn_num": null,
          "level": null,
          "assignment_file1": null,
          "assignment_file2": null,
          "assignment_google_drive": null,
          "assignment_other_link": null,
          "assignment_total_marks": 0,
          "assignment_due_date": null,
          "assignment_submission_type": "individual",
          "created_at": "2021-01-06T05:47:32.000000Z",
          "updated_at": "2021-01-08T09:36:46.000000Z",
          "learner_topic_status_detail": {
            "id": 58,
            "learner_id": 208,
            "type": "Quick Challenge",
            "learner_content_topic_map_id": 0,
            "exp_center_id": 4,
            "course_id": 7,
            "module_id": 32,
            "topic_id": 179,
            "completed_date": "2021-01-18 00:00:00",
            "created_at": "2021-01-18T06:02:43.000000Z",
            "updated_at": "2021-01-18T06:02:43.000000Z"
          }
        },
        {
          "id": 180,
          "module_id": 32,
          "topic_type": "Quick Challenge",
          "topic_name": "Assess 2",
          "slug": "assess-2",
          "topic_date": null,
          "active_status": 1,
          "priority": 5,
          "no_of_min": "2",
          "marks": 50,
          "passing_marks": 100,
          "pointtype": "Credits",
          "challenge_instructions": "<p><span style=\"font-size:26px\">Fill in the blanks with the appropriate answer</span></p>",
          "challenge_type": "FIB",
          "bb_qsn_num": null,
          "level": null,
          "assignment_file1": null,
          "assignment_file2": null,
          "assignment_google_drive": null,
          "assignment_other_link": null,
          "assignment_total_marks": 0,
          "assignment_due_date": null,
          "assignment_submission_type": "individual",
          "created_at": "2021-01-06T05:47:42.000000Z",
          "updated_at": "2021-01-08T09:36:46.000000Z",
          "learner_topic_status_detail": null
        },
        {
          "id": 181,
          "module_id": 32,
          "topic_type": "Quick Challenge",
          "topic_name": "Assess 3",
          "slug": "assess-3",
          "topic_date": null,
          "active_status": 1,
          "priority": 6,
          "no_of_min": "2",
          "marks": 60,
          "passing_marks": 300,
          "pointtype": "Credits",
          "challenge_instructions": null,
          "challenge_type": "MTF",
          "bb_qsn_num": null,
          "level": null,
          "assignment_file1": null,
          "assignment_file2": null,
          "assignment_google_drive": null,
          "assignment_other_link": null,
          "assignment_total_marks": 0,
          "assignment_due_date": null,
          "assignment_submission_type": "individual",
          "created_at": "2021-01-06T05:47:53.000000Z",
          "updated_at": "2021-01-08T09:36:46.000000Z",
          "learner_topic_status_detail": null
        },
        {
          "id": 183,
          "module_id": 32,
          "topic_type": "Quick Challenge",
          "topic_name": "Assess 4",
          "slug": "assess-4",
          "topic_date": null,
          "active_status": 1,
          "priority": 7,
          "no_of_min": "5",
          "marks": 20,
          "passing_marks": 100,
          "pointtype": "Credits",
          "challenge_instructions": null,
          "challenge_type": "BBGAME",
          "bb_qsn_num": 3,
          "level": "easy",
          "assignment_file1": null,
          "assignment_file2": null,
          "assignment_google_drive": null,
          "assignment_other_link": null,
          "assignment_total_marks": 0,
          "assignment_due_date": null,
          "assignment_submission_type": "individual",
          "created_at": "2021-01-06T05:56:31.000000Z",
          "updated_at": "2021-01-12T05:46:17.000000Z",
          "learner_topic_status_detail": null
        },
        {
          "id": 182,
          "module_id": 32,
          "topic_type": "Assignment",
          "topic_name": "Assignment 1",
          "slug": "assignment-1-1",
          "topic_date": null,
          "active_status": 1,
          "priority": 8,
          "no_of_min": null,
          "marks": null,
          "passing_marks": null,
          "pointtype": "Credits",
          "challenge_instructions": "<p>Download the attachment and fill it in.&nbsp;</p>\r\n\r\n<p>To submit, click on the &#39;Upload button&#39;. It will take you to an external drive. You may be asked to sign in here. Please upload your files here</p>\r\n\r\n<p>&nbsp;</p>",
          "challenge_type": null,
          "bb_qsn_num": 2,
          "level": null,
          "assignment_file1": "assignmentfiles1610430747.xlsx",
          "assignment_file2": null,
          "assignment_google_drive": "link",
          "assignment_other_link": null,
          "assignment_total_marks": 100,
          "assignment_due_date": "2021-01-15",
          "assignment_submission_type": "individual",
          "created_at": "2021-01-06T05:49:51.000000Z",
          "updated_at": "2021-01-12T05:54:02.000000Z",
          "learner_topic_status_detail": null
        },
        {
          "id": 184,
          "module_id": 32,
          "topic_type": "Assignment",
          "topic_name": "Assignment 2",
          "slug": "assignment-2",
          "topic_date": null,
          "active_status": 1,
          "priority": 9,
          "no_of_min": null,
          "marks": null,
          "passing_marks": null,
          "pointtype": "Credits",
          "challenge_instructions": null,
          "challenge_type": null,
          "bb_qsn_num": null,
          "level": null,
          "assignment_file1": null,
          "assignment_file2": null,
          "assignment_google_drive": "link",
          "assignment_other_link": null,
          "assignment_total_marks": 100,
          "assignment_due_date": "2021-01-18",
          "assignment_submission_type": "team",
          "created_at": "2021-01-18T05:52:04.000000Z",
          "updated_at": "2021-01-18T05:55:06.000000Z",
          "learner_topic_status_detail": null
        }
      ]
    }
  ]
}

Now i am trying to format the response like below which should return total topics for all modules and total completed topics here "learner_topic_status_detail" is the key to check this topic is completed or not if this key is not null then it is completed.

so if i get total topics count and total completed topics count then in blade i should compare if both count value is equal then that module is completed or it is ongoing. i have query like below,


$fullmodules = $collectionarr['modules'];

$sortcollection =  $fullmodules->map(function ($fullmodule) {
            return [
                'modulename' => $fullmodule->module_name,
                'topicscount' => $fullmodule->topicsdet->count(),
                'attendedcount' => $fullmodule->topicsdet
                    ? $fullmodule
                        ->topicsdet
                        ->map(function ($inner) {
                            return [
                                'attendedcountnumber' => $inner->learner_topic_status_detail ? $inner->learner_topic_status_detail : '',
                                // 'attendedcountnumber' => $inner->learner_topic_status_detail(),
                            ];
                        })
                    : 0,
            ];
        });

the response is,

[
  {
    "modulename": "Introduction",
    "topicscount": 9,
    "attendedcount": [
      {
        "attendedcountnumber": {
          "id": 55,
          "learner_id": 208,
          "type": "Topic",
          "learner_content_topic_map_id": 88,
          "exp_center_id": 4,
          "course_id": 7,
          "module_id": 32,
          "topic_id": 176,
          "completed_date": "2021-01-18 00:00:00",
          "created_at": "2021-01-18T06:02:03.000000Z",
          "updated_at": "2021-01-18T06:02:03.000000Z"
        }
      },
      {
        "attendedcountnumber": {
          "id": 56,
          "learner_id": 208,
          "type": "Topic",
          "learner_content_topic_map_id": 89,
          "exp_center_id": 4,
          "course_id": 7,
          "module_id": 32,
          "topic_id": 177,
          "completed_date": "2021-01-18 00:00:00",
          "created_at": "2021-01-18T06:02:11.000000Z",
          "updated_at": "2021-01-18T06:02:11.000000Z"
        }
      },
      {
        "attendedcountnumber": {
          "id": 57,
          "learner_id": 208,
          "type": "Topic",
          "learner_content_topic_map_id": 90,
          "exp_center_id": 4,
          "course_id": 7,
          "module_id": 32,
          "topic_id": 178,
          "completed_date": "2021-01-18 00:00:00",
          "created_at": "2021-01-18T06:02:17.000000Z",
          "updated_at": "2021-01-18T06:02:17.000000Z"
        }
      },
      {
        "attendedcountnumber": {
          "id": 58,
          "learner_id": 208,
          "type": "Quick Challenge",
          "learner_content_topic_map_id": 0,
          "exp_center_id": 4,
          "course_id": 7,
          "module_id": 32,
          "topic_id": 179,
          "completed_date": "2021-01-18 00:00:00",
          "created_at": "2021-01-18T06:02:43.000000Z",
          "updated_at": "2021-01-18T06:02:43.000000Z"
        }
      },
      {
        "attendedcountnumber": 0
      },
      {
        "attendedcountnumber": 0
      },
      {
        "attendedcountnumber": 0
      },
      {
        "attendedcountnumber": 0
      },
      {
        "attendedcountnumber": 0
      }
    ]
  }
]

Here attendedcountnumber which has zero is not attended yet. how to get proper format to check in view?

Jan
16
1 week ago
Activity icon

Replied to Prevent Php File Execution Inside Users Image Folder In Public

accessing public image file directly in browser can able to view.

Activity icon

Replied to Prevent Php File Execution Inside Users Image Folder In Public

I am using below code in public folder htaccess

<FilesMatch "\.php$">
    Order Allow,Deny
    Deny from all
</FilesMatch>
<FilesMatch "index[0-9]?\.php$">
    Order Allow,Deny
    Allow from all
</FilesMatch>
Activity icon

Started a new Conversation Prevent Php File Execution Inside Users Image Folder In Public

I found one php file inside public folder

Path is like below,

public/userprofilephoto/123123213.php

that code has image validation in laravel where only jpg or png file is allowed now if users trues to access this file directly in browser he will get a access to that file. how to prevent this?

Jan
15
1 week ago
Activity icon

Replied to Check Parameter Exists In All Url

i have pasted example code here,

public function getEventAdd($chapterid)
    {
      if($chapterid)
      {
          $chapterdetail = Chapter::where('id',$chapterid)->first();
          return view('adminfiles.events.addevent',compact('chapterdetail'));
      } else {

          return redirect('admindashboard')->withErrors('Select any one chapter');
      }
    }

if you can see here i am checking chapterid exists or not in every controller function so i am planning to create new middleware to check this route parameter exists or not.

Activity icon

Replied to Check Parameter Exists In All Url

I just want to check if that parameter exists in current url. if not present redirect to some other page.

Activity icon

Started a new Conversation Check Parameter Exists In All Url

I am passing one token to all URL like below,

http://localhost/project/events-manage/123123

here 123123 is the token of a particular branch so same thing s goes with news routes like below,

http://localhost/project/news-manage/123123

Here instead of checking this token exists in every controller function. i can create middle ware right? any suggestions?

Jan
12
2 weeks ago
Activity icon

Replied to Composer Error When I Try To Use Composer Commands

to avoid warning and error in sizeof() for query of single element i have used below code in web.php

if(version_compare(PHP_VERSION, '7.2.0', '>=')) {
    error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING);
}

any security issue? i am working on some changes in application and it will take some days to complete. for temporary i am using this.

Activity icon

Replied to Composer Error When I Try To Use Composer Commands

Ya I changed and is there any quick fix for sizeof problem for first ()?

Activity icon

Replied to Composer Error When I Try To Use Composer Commands

@tisuchi Fatal error: Composer detected issues in your platform: Your Composer dependencies require a PHP version ">= 7.2.5". You are running 7.1.33. in /projectpath/public_html/vendor/composer/platform_check.php on line 24

Now i am getting above error any suggestion?

Activity icon

Replied to Composer Error When I Try To Use Composer Commands

@tisuchi Thank you It worked. what exactly kylekatarnls does?

Activity icon

Started a new Conversation Composer Error When I Try To Use Composer Commands

i am trying to use compose update but getting below error,

Fatal error: Class UpdateHelper\ComposerPlugin contains 2 abstract methods and must therefore be declared abstract or implement the remaining methods (Composer\Plugin\PluginInterface::deactivate, Composer\Plugin\PluginInterface::uninstall) in /projectpath/public_html/vendor/kylekatarnls/update-helper/src/UpdateHelper/ComposerPlugin.php on line 11

I am using "laravel/framework": "5.5.*", Any suggestions/Fix? Shall i delete kylekatarnls folder inside vendor?

Jan
07
3 weeks ago
Activity icon

Replied to Map The User Into Groups From Id

@niush I want to display in select box like below,

2011001 - 2011100
2011101 - 2011200
2011201 - 2011300

for this i want modify the response.

Activity icon

Started a new Conversation Map The User Into Groups From Id

I have user details with orders and registration number for each users and i a getting this in list now i want to group this list based on reg number like below,


2011001 - 2011100
2011101 - 2011200
2011201 - 2011300

I am using the query like below right now

$users = Order::join('user_registerations','orders.course_id','=','user_registrations.course_id')->where('course_id',$course_id)->select('order_id','user_id','register_no')->get();

Now i want to group first register no and 100th registration number, 101th reg no and 200th reg no so on.

Jan
06
3 weeks ago
Activity icon

Started a new Conversation Map The User Into Groups From Id

i am using user details with orders for PDF export. now i want group result into different options in select box like if total user count is 200 then in select options i want to display like below,

1-100
101-200
201-300

the number mentioned above is column name i will replace 1 - 100 with registration numbers LIke this how to map the query to get in this format?

I am using the query like below right now

$users = Order::join('user_registerations','orders.course_id','=','user_registrations.course_id')->where('course_id',$course_id)->select('order_id','user_id','register_no')->get();

Now i want to group first register no and 100th registration number, 101th reg no and 200th reg no so on.

2011001 - 2011100
2011101 - 2011200
Dec
31
4 weeks ago
Activity icon

Replied to Best Way To Store Raw Password Along With Bcrypt Password For Guest Users Who Wants To Create Account

I have guest checkout option where if user enters details and select create account with these details then i am adding that user to db with auto created password like below,

at first user will be created like below,

if ($data['createaccount'] == 0) {
            $orderType = "Guest";
            $usercreate = User::create([
                             'user_type' => "G",
                             'name'      => $request->username,
                             'email'     => $request->useremail,
                             'mobile'    => $request->usermobile,
                             'active_status' => 1,
            ]);
        } else {
            $orderType = "Normal";
            $userPassword = generatePassword();
            $usercreate = User::create([
                              'role_id'  => 2,
                              'user_type' => "N",
                              'name'      => $request->username,
                              'email'     => $request->useremail,
                              'mobile'    => $request->usermobile,
                              'password' => bcrypt($userPassword),
                              'token'   => generateToken(),
                              'otp_status' => 1,
                              'active_status' => 1,
             ]);
            if ($usercreate) {
                Auth::loginUsingId($usercreate->id, TRUE);
                Mail::to($request->useremail)->send(new \App\Mail\RegisterEmail($usercreate, $userPassword, "Guest"));
            }
        }

and user should select mode of payment and in online payment section i have code like below,

} elseif ($payment_method == "Online Payment") {
            $onlineorderdata = [
                      'user_id' => $usercreate->id,
                      'order_type' => $orderType,
                      "order_no" => $get_order_id,
                      "address_id" => $address_id,
                      "billing_id" => $billing_address_id,
                      "bill_same_status" => $bill_same_as_address,
                      "coupon_id"     => session()->get('coupon')['couponid'] ?? 0,
                      "coupon_price" => $couponAmount,
                      "shipping_price" => $shippingPrice,
                      "subtotal"  => $subTotal,
                      "offerprice" => $offerPrice,
                      "total_price" => $totalPrice,
                      "mode"  => $request->payment_type,
                      "order_status" => "Pending",
                      "pay_status" => "Pending",
                      "order_date" => date('Y-m-d'),
                  ];
            // return $onlineorderdata;
            $order = Order::create($onlineorderdata);
            foreach ($cart_items as $cartitem) {
                $ordercart = new CartOrder;
                $ordercart->cart_id = $cartitem->id;
                $ordercart->order_id = $order->id;

                $ordercart->save();
            }
            $order_id = $order->id;
            $order_no = $get_order_id;

            $myAddress = Order::with('myaddress')->where('id', $order->id)->first();
            $myBillAddress = Order::with('mybillingaddress')->where('id', $order->id)->first();

            $myAddressVal = ($myAddress) ? $myAddress->address : '';
            $myBillAddressVal = ($myBillAddress) ? $myBillAddress->address : '';

            $arr = array(
                'receipt' => 'order_rcptid_'.$order_id,
                'amount' =>  $totalPrice * 100,
                'currency'=> 'INR',
                'payment_capture' => 1,

                );
            $orderId = $this->api->Order->create($arr);

            $razorpayOrderId = $orderId['id'];

            $displayAmount = $amount = $orderId['amount'];

            $logourl = url('websiteimages').'/'.'App\Setting'::getSettings()['logo'];
            $data = [
                  "key"               => $this->razorKey,
                  "amount"            => $totalPrice * 100,
                  "name"              => "Website",
                  "description"       => "websiteOnline Payment",
                  "image"             => $logourl,
                  "prefill"           => [
                  "name"              => $usercreate->name,
                  "email"             => $usercreate->email,
                  "contact"           => $usercreate->mobile,
                  ],
                  "notes"             => [
                  "address"           => $myBillAddressVal,
                  "merchant_order_id" => $order_id,
                  "slotdate"          => date('Y-m-d', strtotime($slotdate)),
                  "slottime"          => $slottime,
                  ],
                  "theme"             => [
                  "color"             => "#F37254"
                  ],
                  "order_id"          => $razorpayOrderId,
              ];
            $data['display_currency']  = 'INR';
            $data['display_amount']    = $displayAmount;

            $jsondata = json_encode($data);

            $callbackurl = url('payment-status');
            $cancelurl = url('payment-cancel'); ?>
            <form method="POST" name="redirect" action="https://api.razorpay.com/v1/checkout/embedded">
              <input type="hidden" name="key_id" value="<?php echo $this->razorKey; ?>">
              <input type="hidden" name="order_id" value="<?php echo $razorpayOrderId; ?>">
              <input type="hidden" name="name" value="<?php echo $data['name']; ?>">
              <input type="hidden" name="description" value="<?php echo $data['description']; ?>">
              <input type="hidden" name="image" value="<?php echo $data['image']; ?>">
              <input type="hidden" name="prefill[name]" value="<?php echo $data['prefill']['name']; ?>">
              <input type="hidden" name="prefill[contact]" value="<?php echo $data['prefill']['contact']; ?>">
              <input type="hidden" name="prefill[email]" value="<?php echo $data['prefill']['email']; ?>">
              <input type="hidden" name="notes[address]" value="<?php echo $myBillAddressVal; ?>" >
              <input type="hidden" name="notes[merchant_order_id]" value="<?php echo $order_id; ?>" >
              <input type="hidden" name="notes[merchant_order_no]" value="<?php echo $order_no; ?>" >
              <input type="hidden" name="notes[slotdate]" value="<?php echo date('Y-m-d', strtotime($slotdate)); ?>" >
              <input type="hidden" name="notes[slottime]" value="<?php echo $slottime; ?>" >
              <input type="hidden" name="callback_url" value="<?php echo $callbackurl; ?>">
              <input type="hidden" name="cancel_url" value="<?php echo $cancelurl; ?>">
              <!-- <button>Submit</button> -->
            </form>
            <script language='javascript'>document.redirect.submit();</script>


          <?php
        }

This is callback_url function but if i return Auth::user() then i dont find auth user.

public function postThankYouPage(Request $request)
    {
        $success = true;
        $error = "Payment Failed";
        if (empty($request->razorpay_payment_id) === false) {
            try {

                // Please note that the razorpay order ID must
                // come from a trusted source (session here, but
                // could be database or something else)
                $attributes = array(
                  'razorpay_order_id' => $request->razorpay_order_id,
                  'razorpay_payment_id' => $request->razorpay_payment_id,
                  'razorpay_signature' => $request->razorpay_signature
              );

                $this->api->utility->verifyPaymentSignature($attributes);
                session()->forget('coupon');
            } catch (SignatureVerificationError $e) {
                $success = false;
                $error = 'Razorpay Error : ' . $e->getMessage();
            }

            if ($success === true) {
                $post = $request->getContent();

                $data = json_decode($post, true);

                $payment = $this->getPaymentEntity($request->razorpay_payment_id, $data);
                $orderId = $payment['notes']['merchant_order_id'];
                $orderNo = $payment['notes']['merchant_order_no'];
                $slotdate = $payment['notes']['slotdate'];
                $slottime = $payment['notes']['slottime'];

                $checkOrder = Order::with('cartorders')
                            ->where('id', '=', $orderId)
                            ->where('order_no', '=', $orderNo)
                            ->first();

                $amount = $checkOrder->total_price;

                if ($checkOrder->txn_id != $request->razorpay_payment_id) {
                    if ($checkOrder->pay_status == "Pending" || $checkOrder->order_status == "Pending") {
                        if ($payment['status'] === 'captured') {
                            $success = true;
                        } elseif ($payment['status'] === 'authorized') {
                            //
                            // If the payment is only authorized, we capture it
                            // If the merchant has enabled auto capture
                            //
                            try {
                                $payment->capture(array('amount' => $amount));

                                $success = true;
                            } catch (Exception $e) {
                                //
                                // Capture will fail if the payment is already captured
                                //
                                $log = array(
                                  'message'         => $e->getMessage(),
                                  'payment_id'      => $razorpayPaymentId,
                                  'event'           => $data['event']
                              );

                                error_log(json_encode($log));

                                //
                                // We re-fetch the payment entity and check if the payment is captured now
                                //
                                $payment = $this->getPaymentEntity($razorpayPaymentId, $data);

                                if ($payment['status'] === 'captured') {
                                    $success = true;
                                }
                            }
                        }

                        $this->updatePaymentOrder($checkOrder, $request->razorpay_payment_id, $payment, $orderId, $slotdate, $slottime);
                    }
                }

              
                return redirect('order-confirmation/onlinepayment/'.$checkOrder->order_no)->with('message', 'You have successfully placed an order. we will deliver it soon. Check details below.');
            } else {
                return redirect('order-confirmation/onlinepayment/'.$checkOrder->order_no)->withErrors('Payment Failed. Go to checkout and complete the payment.');
            }
        } else {
            return redirect('order-confirmation/onlinepayment/'.$checkOrder->order_no)->withErrors('Payment Failed. Go to checkout and complete the payment.');
        }
    }

But the same auth code is working if i select cod as payment method the code is like below,

elseif ($payment_method == "COD") {
            $order = $this->createGuestOrder($orderdata, $cart_items, $usercreate->id);
            $this->deleteCartItems($usercreate->id);
            $this->updateCouponQuantity($order->coupon_id);
            $my_order_det = $this->getOrderForTable($order->id);

            return redirect('order-confirmation/cod/'.$get_order_id)->with('message', 'You have successfully placed an order. we will deliver it soon.');
        }

Here if i return auth user then it is working fine.

Any solution for this?

Activity icon

Started a new Conversation Auth Login Not Working With Payment Gateway But It Is Working For Cash On Delivery

Hi, I have guest checkout option where if user enters details and select create account with these details then i am adding that user to db with auto created password like below,

at first user will be created like below,

if ($data['createaccount'] == 0) {
            $orderType = "Guest";
            $usercreate = User::create([
                             'user_type' => "G",
                             'name'      => $request->username,
                             'email'     => $request->useremail,
                             'mobile'    => $request->usermobile,
                             'active_status' => 1,
            ]);
        } else {
            $orderType = "Normal";
            $userPassword = generatePassword();
            $usercreate = User::create([
                              'role_id'  => 2,
                              'user_type' => "N",
                              'name'      => $request->username,
                              'email'     => $request->useremail,
                              'mobile'    => $request->usermobile,
                              'password' => bcrypt($userPassword),
                              'token'   => generateToken(),
                              'otp_status' => 1,
                              'active_status' => 1,
             ]);
            if ($usercreate) {
                Auth::loginUsingId($usercreate->id, TRUE);
                Mail::to($request->useremail)->send(new \App\Mail\RegisterEmail($usercreate, $userPassword, "Guest"));
            }
        }

and user should select mode of payment and in online payment section i have code like below,

} elseif ($payment_method == "Online Payment") {
            $onlineorderdata = [
                      'user_id' => $usercreate->id,
                      'order_type' => $orderType,
                      "order_no" => $get_order_id,
                      "address_id" => $address_id,
                      "billing_id" => $billing_address_id,
                      "bill_same_status" => $bill_same_as_address,
                      "coupon_id"     => session()->get('coupon')['couponid'] ?? 0,
                      "coupon_price" => $couponAmount,
                      "shipping_price" => $shippingPrice,
                      "subtotal"  => $subTotal,
                      "offerprice" => $offerPrice,
                      "total_price" => $totalPrice,
                      "mode"  => $request->payment_type,
                      "order_status" => "Pending",
                      "pay_status" => "Pending",
                      "order_date" => date('Y-m-d'),
                  ];
            // return $onlineorderdata;
            $order = Order::create($onlineorderdata);
            foreach ($cart_items as $cartitem) {
                $ordercart = new CartOrder;
                $ordercart->cart_id = $cartitem->id;
                $ordercart->order_id = $order->id;

                $ordercart->save();
            }
            $order_id = $order->id;
            $order_no = $get_order_id;

            $myAddress = Order::with('myaddress')->where('id', $order->id)->first();
            $myBillAddress = Order::with('mybillingaddress')->where('id', $order->id)->first();

            $myAddressVal = ($myAddress) ? $myAddress->address : '';
            $myBillAddressVal = ($myBillAddress) ? $myBillAddress->address : '';

            $arr = array(
                'receipt' => 'order_rcptid_'.$order_id,
                'amount' =>  $totalPrice * 100,
                'currency'=> 'INR',
                'payment_capture' => 1,

                );
            $orderId = $this->api->Order->create($arr);

            $razorpayOrderId = $orderId['id'];

            $displayAmount = $amount = $orderId['amount'];

            $logourl = url('websiteimages').'/'.'App\Setting'::getSettings()['logo'];
            $data = [
                  "key"               => $this->razorKey,
                  "amount"            => $totalPrice * 100,
                  "name"              => "Website",
                  "description"       => "websiteOnline Payment",
                  "image"             => $logourl,
                  "prefill"           => [
                  "name"              => $usercreate->name,
                  "email"             => $usercreate->email,
                  "contact"           => $usercreate->mobile,
                  ],
                  "notes"             => [
                  "address"           => $myBillAddressVal,
                  "merchant_order_id" => $order_id,
                  "slotdate"          => date('Y-m-d', strtotime($slotdate)),
                  "slottime"          => $slottime,
                  ],
                  "theme"             => [
                  "color"             => "#F37254"
                  ],
                  "order_id"          => $razorpayOrderId,
              ];
            $data['display_currency']  = 'INR';
            $data['display_amount']    = $displayAmount;

            $jsondata = json_encode($data);

            $callbackurl = url('payment-status');
            $cancelurl = url('payment-cancel'); ?>
            <form method="POST" name="redirect" action="https://api.razorpay.com/v1/checkout/embedded">
              <input type="hidden" name="key_id" value="<?php echo $this->razorKey; ?>">
              <input type="hidden" name="order_id" value="<?php echo $razorpayOrderId; ?>">
              <input type="hidden" name="name" value="<?php echo $data['name']; ?>">
              <input type="hidden" name="description" value="<?php echo $data['description']; ?>">
              <input type="hidden" name="image" value="<?php echo $data['image']; ?>">
              <input type="hidden" name="prefill[name]" value="<?php echo $data['prefill']['name']; ?>">
              <input type="hidden" name="prefill[contact]" value="<?php echo $data['prefill']['contact']; ?>">
              <input type="hidden" name="prefill[email]" value="<?php echo $data['prefill']['email']; ?>">
              <input type="hidden" name="notes[address]" value="<?php echo $myBillAddressVal; ?>" >
              <input type="hidden" name="notes[merchant_order_id]" value="<?php echo $order_id; ?>" >
              <input type="hidden" name="notes[merchant_order_no]" value="<?php echo $order_no; ?>" >
              <input type="hidden" name="notes[slotdate]" value="<?php echo date('Y-m-d', strtotime($slotdate)); ?>" >
              <input type="hidden" name="notes[slottime]" value="<?php echo $slottime; ?>" >
              <input type="hidden" name="callback_url" value="<?php echo $callbackurl; ?>">
              <input type="hidden" name="cancel_url" value="<?php echo $cancelurl; ?>">
              <!-- <button>Submit</button> -->
            </form>
            <script language='javascript'>document.redirect.submit();</script>


          <?php
        }

This is callback_url function but if i return Auth::user() then i dont find auth user.

public function postThankYouPage(Request $request)
    {
        $success = true;
        $error = "Payment Failed";
        if (empty($request->razorpay_payment_id) === false) {
            try {

                // Please note that the razorpay order ID must
                // come from a trusted source (session here, but
                // could be database or something else)
                $attributes = array(
                  'razorpay_order_id' => $request->razorpay_order_id,
                  'razorpay_payment_id' => $request->razorpay_payment_id,
                  'razorpay_signature' => $request->razorpay_signature
              );

                $this->api->utility->verifyPaymentSignature($attributes);
                session()->forget('coupon');
            } catch (SignatureVerificationError $e) {
                $success = false;
                $error = 'Razorpay Error : ' . $e->getMessage();
            }

            if ($success === true) {
                $post = $request->getContent();

                $data = json_decode($post, true);

                $payment = $this->getPaymentEntity($request->razorpay_payment_id, $data);
                $orderId = $payment['notes']['merchant_order_id'];
                $orderNo = $payment['notes']['merchant_order_no'];
                $slotdate = $payment['notes']['slotdate'];
                $slottime = $payment['notes']['slottime'];

                $checkOrder = Order::with('cartorders')
                            ->where('id', '=', $orderId)
                            ->where('order_no', '=', $orderNo)
                            ->first();

                $amount = $checkOrder->total_price;

                if ($checkOrder->txn_id != $request->razorpay_payment_id) {
                    if ($checkOrder->pay_status == "Pending" || $checkOrder->order_status == "Pending") {
                        if ($payment['status'] === 'captured') {
                            $success = true;
                        } elseif ($payment['status'] === 'authorized') {
                            //
                            // If the payment is only authorized, we capture it
                            // If the merchant has enabled auto capture
                            //
                            try {
                                $payment->capture(array('amount' => $amount));

                                $success = true;
                            } catch (Exception $e) {
                                //
                                // Capture will fail if the payment is already captured
                                //
                                $log = array(
                                  'message'         => $e->getMessage(),
                                  'payment_id'      => $razorpayPaymentId,
                                  'event'           => $data['event']
                              );

                                error_log(json_encode($log));

                                //
                                // We re-fetch the payment entity and check if the payment is captured now
                                //
                                $payment = $this->getPaymentEntity($razorpayPaymentId, $data);

                                if ($payment['status'] === 'captured') {
                                    $success = true;
                                }
                            }
                        }

                        $this->updatePaymentOrder($checkOrder, $request->razorpay_payment_id, $payment, $orderId, $slotdate, $slottime);
                    }
                }

              
                return redirect('order-confirmation/onlinepayment/'.$checkOrder->order_no)->with('message', 'You have successfully placed an order. we will deliver it soon. Check details below.');
            } else {
                return redirect('order-confirmation/onlinepayment/'.$checkOrder->order_no)->withErrors('Payment Failed. Go to checkout and complete the payment.');
            }
        } else {
            return redirect('order-confirmation/onlinepayment/'.$checkOrder->order_no)->withErrors('Payment Failed. Go to checkout and complete the payment.');
        }
    }

But the same auth code is working if i select cod as payment method the code is like below,

elseif ($payment_method == "COD") {
            $order = $this->createGuestOrder($orderdata, $cart_items, $usercreate->id);
            $this->deleteCartItems($usercreate->id);
            $this->updateCouponQuantity($order->coupon_id);
            $my_order_det = $this->getOrderForTable($order->id);

            return redirect('order-confirmation/cod/'.$get_order_id)->with('message', 'You have successfully placed an order. we will deliver it soon.');
        }

Here if i return auth user then it is working fine.

Any solution for this?

Activity icon

Replied to Best Way To Store Raw Password Along With Bcrypt Password For Guest Users Who Wants To Create Account

this flow sounds good?

  1. Create one signed URL
  2. crate a form if i run that url
  3. user will enter the password using that form and create only password.
  4. this link should not expire because user can click that link and create password any time

Is this fine?

Activity icon

Started a new Conversation Best Way To Store Raw Password Along With Bcrypt Password For Guest Users Who Wants To Create Account

Hi, I have a guest checkout option where users enter details like name email mobile and other details and there is a option to select the checbox "Create an account with these details" if user selects this and select the payment gateway then on webhook or success i should send an email to crated user with automatically created password for this i should store the raw password. what is the best way to encode the password and decode?

Dec
27
1 month ago
Activity icon

Started a new Conversation Filter Questions Count Based On Language In Relationship

I have tables like below,

tests table with columns

id, testname

categories with columns

id, category_name

Questions table with columns

id, test_id, category_id,question_name, correct_option, language

user_tests table with columns

id,user_id,test_status,marks_scored,test_language

user_answers table with columns

id, user_test_id,user_answer

Now i am trying to display category wise analysis like total questions

i am getting total questions using below query,

$get_user_test_id = UserTest::where('course_id',$course_id)->where('attempt',1)->where('user_id','=',uid())->groupBy('test_id')->get(['test_id','user_test_id','test_language']);

$totaltestids = $get_user_test_id->pluck('test_id');

$testlanguages = $get_user_test_id->pluck('test_language');

$categories = 'App\QuestionCategory'::withCount(['questionslist'=> function($q) use($totaltestids,$testlanguages){
        $q->whereIn('test_id',$totaltestids)
          ->whereIn('language',$testlanguages);
      }])->orderBy('question_category_id','ASC')->get();

it is displaying in below format,

[
  {
    "question_category_id": 1,
    "question_category_name": "Ancient and Medieval Indian History",
    "created_at": "2017-06-21 00:00:00",
    "updated_at": "-0001-11-30 00:00:00",
    "questionslist_count": 93
  },
  {
    "question_category_id": 2,
    "question_category_name": "Modern History and Indian National Movement",
    "created_at": "2017-06-21 00:00:00",
    "updated_at": "-0001-11-30 00:00:00",
    "questionslist_count": 22
  },
  {
    "question_category_id": 3,
    "question_category_name": "Art and Culture",
    "created_at": "2017-06-21 00:00:00",
    "updated_at": "-0001-11-30 00:00:00",
    "questionslist_count": 28
  },
  {
    "question_category_id": 4,
    "question_category_name": "Indian Geography - Physical, Social and Economic",
    "created_at": "2017-06-21 00:00:00",
    "updated_at": "-0001-11-30 00:00:00",
    "questionslist_count": 68
  },
  {
    "question_category_id": 5,
    "question_category_name": "World Geography - Physical and Human",
    "created_at": "2017-06-21 00:00:00",
    "updated_at": "-0001-11-30 00:00:00",
    "questionslist_count": 71
  },
  {
    "question_category_id": 6,
    "question_category_name": "Indian Polity and Governance",
    "created_at": "2017-06-21 00:00:00",
    "updated_at": "-0001-11-30 00:00:00",
    "questionslist_count": 70
  },
  {
    "question_category_id": 7,
    "question_category_name": "All Schemes and Programmes",
    "created_at": "2017-06-21 00:00:00",
    "updated_at": "-0001-11-30 00:00:00",
    "questionslist_count": 13
  },
 
]

And here questions table consists both english and hindi (another local language) for same test so if user takes one test in hindi and another in english then the above query displaying the question count *2 becuase pluck of language displays both language.

Now i want to get questions of user_test.test_language only. i tried using join like below,

$categories = 'App\QuestionCategory'::withCount(['questionslist'=> function($q) use($totaltestids,$testlanguages){
        $q->join('user_tests','questions.test_id','=','user_tests.test_id')
		->whereColumn('user_tests.test_language','=','questions.language')
		->whereIn('questions.test_id',$totaltestids);
      }])->orderBy('question_category_id','ASC')->get();

But no use it shows wrong data please check soon.

Dec
26
1 month ago
Activity icon

Replied to How To Match Two Columns Values In Relationship

Yes thank you this query is working fine now,

  $categories = 'App\QuestionCategory'::withCount(['questionslist as totalquestions'=> function($q) use($totaltestids,$testlanguages){
        $q->whereIn('test_id',$totaltestids)
          ->whereIn('language',$testlanguages);
        }])->withCount(['questionslist as csatcount'=> function($q) use($totaltestids,$testlanguages,$totalusertestids){
          $q->join('tests','questions.test_id','=','tests.test_id')
            ->whereIn('questions.test_id',$totaltestids)
            ->whereIn('questions.language',$testlanguages)
            ->where('tests.csat',1);
        }])->withCount(['questionslist as nocsatcount'=> function($q) use($totaltestids,$testlanguages,$totalusertestids){
          $q->join('tests','questions.test_id','=','tests.test_id')
            ->whereIn('questions.test_id',$totaltestids)
            ->whereIn('questions.language',$testlanguages)
            ->where('tests.csat',0);
        }])->withCount(['questionslist as csatcorrectcount'=> function($q) use($totaltestids,$testlanguages,$totalusertestids){
        $q->join('tests','questions.test_id','=','tests.test_id')
          ->join('user_answers','questions.question_id','=','user_answers.question_id')
          ->whereIn('questions.test_id',$totaltestids)
          ->whereIn('questions.language',$testlanguages)
          ->whereIn('user_answers.user_test_id',$totalusertestids)
          ->whereColumn('user_answers.user_answer','=','questions.correct_option')
          ->where('tests.csat',1);
        }])->withCount(['questionslist as nocsatcorrectcount'=> function($q) use($totaltestids,$testlanguages,$totalusertestids){
        $q->join('tests','questions.test_id','=','tests.test_id')
          ->join('user_answers','questions.question_id','=','user_answers.question_id')
          ->whereIn('questions.test_id',$totaltestids)
          ->whereIn('questions.language',$testlanguages)
          ->whereIn('user_answers.user_test_id',$totalusertestids)
          ->whereColumn('user_answers.user_answer','=','questions.correct_option')
          ->where('tests.csat',0);
        }])->withCount(['questionslist as csatincorrectcount'=> function($q) use($totaltestids,$testlanguages,$totalusertestids){
        $q->join('tests','questions.test_id','=','tests.test_id')
          ->join('user_answers','questions.question_id','=','user_answers.question_id')
          ->whereIn('questions.test_id',$totaltestids)
          ->whereIn('questions.language',$testlanguages)
          ->whereIn('user_answers.user_test_id',$totalusertestids)
          ->whereColumn('user_answers.user_answer','!=','questions.correct_option')
          ->where('tests.csat',1);
        }])->withCount(['questionslist as nocsatincorrectcount'=> function($q) use($totaltestids,$testlanguages,$totalusertestids){
        $q->join('tests','questions.test_id','=','tests.test_id')
          ->join('user_answers','questions.question_id','=','user_answers.question_id')
          ->whereIn('questions.test_id',$totaltestids)
          ->whereIn('questions.language',$testlanguages)
          ->whereIn('user_answers.user_test_id',$totalusertestids)
          ->whereColumn('user_answers.user_answer','!=','questions.correct_option')
          ->where('tests.csat',0);
        }])->orderBy('question_category_id','ASC')->get();
Activity icon

Replied to How To Match Two Columns Values In Relationship

Now i got a working query like below,

$categories = 'App\QuestionCategory'::withCount(['questionslist as totalquestions'=> function($q) use($totaltestids,$testlanguages){
        $q->whereIn('test_id',$totaltestids)
          ->whereIn('language',$testlanguages);
      }])->withCount(['questionslist as correctcount'=> function($q) use($totaltestids,$testlanguages,$totalusertestids){
        $q->join('user_answers','questions.question_id','=','user_answers.question_id')
          ->whereIn('questions.test_id',$totaltestids)
          ->whereIn('questions.language',$testlanguages)
          ->whereIn('user_answers.user_test_id',$totalusertestids)
          ->whereColumn('user_answers.user_answer','=','questions.correct_option');
      }])->withCount(['questionslist as incorrectcount'=> function($q) use($totaltestids,$testlanguages,$totalusertestids){
        $q->join('user_answers','questions.question_id','=','user_answers.question_id')
          ->whereIn('questions.test_id',$totaltestids)
          ->whereIn('questions.language',$testlanguages)
          ->whereIn('user_answers.user_test_id',$totalusertestids)
          ->whereColumn('user_answers.user_answer','!=','questions.correct_option');
      }])->with(['questionslist'=> function($q) use($totaltestids,$testlanguages,$totalusertestids){
        $q->join('tests','questions.test_id','=','tests.test_id')
          ->whereIn('questions.test_id',$totaltestids)
          ->whereIn('questions.language',$testlanguages);
      }])->orderBy('question_category_id','ASC')->get()

Now i have to add total marks concept we can calculate this using below condition,

if tests.csat == 1 then total marks will be no of questions * 2.5;
if tests.csat == 0 then total marks will be no of questions * 2;

How to get total marks in above query i have joined tests table in last relationship of above query.

Activity icon

Replied to How To Match Two Columns Values In Relationship

whereColumns is used for same table right?

Activity icon

Replied to Create Dynamic Route And Use From Multiple Tables

Will do that thank you.

Activity icon

Started a new Conversation How To Match Two Columns Values In Relationship

I have three tables,

tests table with columns

id, testname

categories with columns

id, category_name

Questions table with columns

id, test_id, category_id,question_name, correct_option

user_tests table with columns

id,user_id,test_status,marks_scored

user_answers table with columns

id, user_test_id,user_answer

Now i am trying to display category wise analysis like total questions, correct attempts, incorrect attempts

i am getting total questions using below query,

$get_user_test_id = UserTest::where('course_id',$course_id)->where('attempt',1)->where('user_id','=',uid())->groupBy('test_id')->get(['test_id','user_test_id','test_language']);

$totaltestids = $get_user_test_id->pluck('test_id');

$testlanguages = $get_user_test_id->pluck('test_language');

$categories = 'App\QuestionCategory'::withCount(['questionslist'=> function($q) use($totaltestids,$testlanguages){
        $q->whereIn('test_id',$totaltestids)
          ->whereIn('language',$testlanguages);
      }])->orderBy('question_category_id','ASC')->get();

it is displaying in below format,

[
  {
    "question_category_id": 1,
    "question_category_name": "Ancient and Medieval Indian History",
    "created_at": "2017-06-21 00:00:00",
    "updated_at": "-0001-11-30 00:00:00",
    "questionslist_count": 93
  },
  {
    "question_category_id": 2,
    "question_category_name": "Modern History and Indian National Movement",
    "created_at": "2017-06-21 00:00:00",
    "updated_at": "-0001-11-30 00:00:00",
    "questionslist_count": 22
  },
  {
    "question_category_id": 3,
    "question_category_name": "Art and Culture",
    "created_at": "2017-06-21 00:00:00",
    "updated_at": "-0001-11-30 00:00:00",
    "questionslist_count": 28
  },
  {
    "question_category_id": 4,
    "question_category_name": "Indian Geography - Physical, Social and Economic",
    "created_at": "2017-06-21 00:00:00",
    "updated_at": "-0001-11-30 00:00:00",
    "questionslist_count": 68
  },
  {
    "question_category_id": 5,
    "question_category_name": "World Geography - Physical and Human",
    "created_at": "2017-06-21 00:00:00",
    "updated_at": "-0001-11-30 00:00:00",
    "questionslist_count": 71
  },
  {
    "question_category_id": 6,
    "question_category_name": "Indian Polity and Governance",
    "created_at": "2017-06-21 00:00:00",
    "updated_at": "-0001-11-30 00:00:00",
    "questionslist_count": 70
  },
  {
    "question_category_id": 7,
    "question_category_name": "All Schemes and Programmes",
    "created_at": "2017-06-21 00:00:00",
    "updated_at": "-0001-11-30 00:00:00",
    "questionslist_count": 13
  },
  {
    "question_category_id": 8,
    "question_category_name": "Social Issues",
    "created_at": "2017-06-21 00:00:00",
    "updated_at": "-0001-11-30 00:00:00",
    "questionslist_count": 0
  },
  {
    "question_category_id": 9,
    "question_category_name": "Basic Economics and Institutional Economy",
    "created_at": "2017-06-21 00:00:00",
    "updated_at": "-0001-11-30 00:00:00",
    "questionslist_count": 3
  },
  {
    "question_category_id": 10,
    "question_category_name": "Indian Economy",
    "created_at": "2017-06-21 00:00:00",
    "updated_at": "-0001-11-30 00:00:00",
    "questionslist_count": 21
  },
  {
    "question_category_id": 11,
    "question_category_name": "Ecology and Environment",
    "created_at": "2017-06-21 00:00:00",
    "updated_at": "-0001-11-30 00:00:00",
    "questionslist_count": 48
  },
  {
    "question_category_id": 12,
    "question_category_name": "General Science",
    "created_at": "2017-06-21 00:00:00",
    "updated_at": "-0001-11-30 00:00:00",
    "questionslist_count": 27
  },
  {
    "question_category_id": 13,
    "question_category_name": "National Current Events",
    "created_at": "2017-06-21 00:00:00",
    "updated_at": "-0001-11-30 00:00:00",
    "questionslist_count": 30
  },
  {
    "question_category_id": 14,
    "question_category_name": "International Affairs",
    "created_at": "2017-06-21 00:00:00",
    "updated_at": "-0001-11-30 00:00:00",
    "questionslist_count": 7
  },
  {
    "question_category_id": 15,
    "question_category_name": "Institutions - National and International",
    "created_at": "2017-06-21 00:00:00",
    "updated_at": "-0001-11-30 00:00:00",
    "questionslist_count": 30
  },
  {
    "question_category_id": 16,
    "question_category_name": "Science and Technology (Current Events)",
    "created_at": "2017-06-21 00:00:00",
    "updated_at": "-0001-11-30 00:00:00",
    "questionslist_count": 20
  },
  {
    "question_category_id": 17,
    "question_category_name": "Defense and Security Issues",
    "created_at": "2017-06-21 00:00:00",
    "updated_at": "-0001-11-30 00:00:00",
    "questionslist_count": 2
  },
 
]

Now i want to display the correct attempts the condition will be,

where(user_answers.user_answer = questions.correct_option)

How to use useranswer modal in this existing query and match different table columns in where? Please help me with this.

Activity icon

Started a new Conversation Create Dynamic Route And Use From Multiple Tables

I have a route like below,

Route::get('{projectslug}',[WebsiteController::Class, 'getProjectDetail']);

this will work dynamically for every project slug

and now i want the same route structure for pages as well like below,

Route::get('{pagename}',[WebsiteController::Class, 'getPageDetail']);

But this route already defined for project how to use the same for pages as well? i need this for SEO purpose and it would be helpful for migrating from wordpress to laravel.

Dec
15
1 month ago
Activity icon

Started a new Conversation Laravel Nested Realtionsip With And Withcout

I have a three table,

products, categories and product_categories,

i have below query to display the bestsellers,

$bestsellers = Product::has('bestselling', '>' , 0)->withCount(['bestselling as bestsellingproduct' => function($query) {

					$query->select(DB::raw('sum(quantity)'));

				}]) ->where('active_status',1)->orderBy('bestsellingproduct','DESC')->take(8)->get();

Product Model,

public function bestselling() {

        return $this->hasMany('App\OrderDetail');
    }

in order details there s a product_id column,

Now i want to fetch the bestsellers products category wise,

$categories = Category::withCount('Products')->with('Products.bestselling')->where('parent_id',0)->where('active_status',1)->orderBy('priority','ASC')->get(['id','slug','category_name','image']);

here i want to get fetch bestsellers based on bestselling order by DESC.

how to use nested relation for this? how to fetch details just like in first query in category?

Activity icon

Started a new Conversation Accessor Change Date Format Not Working On Ajax Post

Hello, I am trying to display 24 hour format time in AM and PM format and i have written accessor like below,

i have a table data slots like below,

09:00:00 - 11:00:00
11:00:00 - 13:00:00
13:00:00 - 15:00:00
15:00:00 - 17:00:00

and Slot.php is,

protected $table = "slots";
    protected $appends = [
        'from_time','to_time'
    ];

    public function getFromTimeAttribute($value)
    {
        return date('h:i A', strtotime($value));
    }

    public function getToTimeAttribute($value)
    {
        return date('h:i A', strtotime($value));
    }

and it is displaying fine in below html ,

<div class="chk-bill mt-20">
            <div class="col-md-6">
            	<div class="form-group">
            		<label>Delivery Date*</label>
            		<input type="text" name="delivery_date" autocomplete="nope" id="delivery_date" value="{{ $setDate }}" class="form-control" required>
            	</div>
            </div>
            <div class="col-md-6">
            	<div class="form-group">
            		<label>Select Slot*</label>
                <select name="slottime" id="slottime" class="form-control" required>
                @foreach($getCurrentSlots as $slot)
            		<option value="{{ $slot->id }}">{{ $slot->from_time }} - {{ $slot->to_time }}</option>
                @endforeach
              </select>
            	</div>
            </div>
            <div class="clearfix"></div>
          </div>

i have written on change date code where it will display the slots based on onchange date like below,

  // $('#delivery_date').datepicker();
  $('#delivery_date').datepicker({
    minDate: 0, // your min date
    maxDate: '+1w', // one week will always be 5 business day - not sure if you are including current day
    // beforeShowDay: $.datepicker.noWeekends // disable weekends
    dateFormat: 'dd-mm-yy',
    onSelect: function(date, instance) {
      var fd = new FormData();
      fd.append( '_token', "{{ csrf_token() }}" );
      fd.append( 'getdate', date );

        $.ajax({
            type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
            url         : "{{url('get-slots-by-date')}}",
  					data        : fd,
            dataType    : 'json', // what type of data do we expect back from the server
            encode      : true,
            processData	: false,
            contentType	: false
        })
  			.done(function(data) {
          console.log(data);
          var appendhtml = '';
          $.each(data, function (key, val) {
            appendhtml += '<option value="'+val.id+'">'+val.from_time+' - '+val.to_time+'</option>';
  			    });

          $('#slottime')
          .empty()
          .append(appendhtml);
        });
  			return false;
     }
});

and controller code is,

$date = $request->getdate;
      $currentDate = date('d-m-Y');
      if($date == $currentDate)
      {
        $currentTime = date('H:i:s');
        $getCurrentSlots = Slots::where('from_time','>',$currentTime)->where('active_status',1)->get();

      } else {
        $getCurrentSlots = Slots::where('active_status',1)->get();
      }

      return $getCurrentSlots;

But this returning the response like below,

[{"id":1,"from_time":"12:00 AM","to_time":"12:00 AM","active_status":1,"created_at":"2020-12-15 00:08:52","updated_at":"2020-12-15 00:08:52"},{"id":2,"from_time":"12:00 AM","to_time":"12:00 AM","active_status":1,"created_at":"2020-12-15 00:08:52","updated_at":"2020-12-15 00:08:52"},{"id":3,"from_time":"12:00 AM","to_time":"12:00 AM","active_status":1,"created_at":"2020-12-15 00:09:30","updated_at":"2020-12-15 00:09:30"},{"id":4,"from_time":"12:00 AM","to_time":"12:00 AM","active_status":1,"created_at":"2020-12-15 00:33:44","updated_at":"2020-12-15 00:09:30"},{"id":6,"from_time":"12:00 AM","to_time":"12:00 AM","active_status":1,"created_at":"2020-12-15 00:33:48","updated_at":"2020-12-15 00:10:43"},{"id":7,"from_time":"12:00 AM","to_time":"12:00 AM","active_status":1,"created_at":"2020-12-15 00:33:51","updated_at":"2020-12-15 00:11:15"}]

it is displaying 12 AM for all from and to time.

Activity icon

Replied to How To Use Imagepng Function To Store In Default Public Folder

@ftiersch Thank you for the response. i tired like below but qr folder has not created,

 public function genQR($data){
 		$size = '400x400';
 		$QR = imagecreatefrompng('https://chart.googleapis.com/chart?cht=qr&chld=H|1&chs='.$size.'&chl='.urlencode($data));
		$initfilename = uniqid() . ".png";
 		$imagename= public_path("qr/" . $initfilename);
 		imagepng($QR,$imagename);
 		imagedestroy($QR);
 		return $imagename;
 		}
Activity icon

Started a new Conversation How To Use Imagepng Function To Store In Default Public Folder

i have php function like below which stores qr code image to a directory named qr,

public function genQR($data){
		$size = '400x400';
		$QR = imagecreatefrompng('https://chart.googleapis.com/chart?cht=qr&chld=H|1&chs='.$size.'&chl='.urlencode($data));
		$imagename="qr/".uniqid().'.png';
		imagepng($QR,$imagename);
		imagedestroy($QR);
		return $imagename;
	}

i tried to add this to laravel but image is not saving to any directory i tried to change the imagename like below,

$imagename=url('/')."/qr/".uniqid().'.png';

but it is now storing inside public folder. how to rewrite this one?

Activity icon

Replied to Store Image To Public Path

can you please write it as i am not getting it

Dec
14
1 month ago
Activity icon

Replied to Store Image To Public Path

please mention where it is?

Activity icon

Replied to Store Image To Public Path

Here i am not getting any file. i have google chart api generated qr code thats it how to store that to folder?

Activity icon

Started a new Conversation Store Image To Public Path

Hello I have php code like below to store the qr code in a folder,

public function genQR($data){
		$size = '400x400';
		$QR = imagecreatefrompng('https://chart.googleapis.com/chart?cht=qr&chld=H|1&chs='.$size.'&chl='.urlencode($data));
		$imagename="qr/".uniqid().'.png';
		imagepng($QR,$imagename);
		imagedestroy($QR);
		return $imagename;
	}

Here i can get the imagename of the qr code but image is not storing in qr folder and it is not creating in public too. how to store this image name like 1245786.png to a folder. i tired below code,

$imagename=uniqid().'.png';
$imagename->move(public_path().'/qr/', $imagename);

But i am getting below error,

Call to a member function move() on string
Dec
07
1 month ago
Activity icon

Replied to Trying To Use Controller Function In Href Tag Action In Laravel 8

@thinkverse Thank you. i was thinking to avoid including full path to access controller function. Thank you will follow this.

Dec
06
1 month ago
Activity icon

Started a new Conversation Trying To Use Controller Function In Href Tag Action In Laravel 8

I am trying to access controller function in action like below,

<a href="{{ action('[email protected]', $type,$project->id) }}">

it is giving below error,

Action [email protected] not defined
Activity icon

Replied to Add Another Route File In Laravel 8.12

now i want to add middleware to isAdmin middleware where it will check if admin already logged in or not in this case i want to exclude adminlogin get and post routes. i have some confusions in laravel 8.2 route changes. how can i exclude these two function directly in Routeserviceprovider.php file?

Activity icon

Replied to Add Another Route File In Laravel 8.12

now i created admin middleware to check the authentication based on role id like below,

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Auth;

class isAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        if(Auth::check()) {
        
            if(Auth::user()->role_id && Auth::user()->role_id == 1) {
            
               return $next($request);
            
            } else {
            
              return redirect('adminlogin');
            }
        
        } else {
            
           return redirect('adminlogin');
            
        }
    }
}

Activity icon

Replied to Add Another Route File In Laravel 8.12

@nakov how to add except for the admin middleware in routeserviceprovider.php file code?

Activity icon

Replied to Add Another Route File In Laravel 8.12

@nakov sorry there was no admin middleware i have created and it is working fine thank you

Activity icon

Replied to Add Another Route File In Laravel 8.12

@nakov this is how my admin.php file looks like,

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Admin\AdminController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

//admin routes
Route::get('adminlogin',[AdminController::Class, 'getAdminLogin']);
Route::post('adminlogin',[AdminController::Class, 'postAdminLogin']);

i am using users table for this.

Activity icon

Started a new Conversation Add Another Route File In Laravel 8.12

I have created admin.php inside routes folder and i have added this in routeserviceprovider like below,

public function boot()
    {
        $this->configureRateLimiting();

        $this->routes(function () {
            Route::prefix('api')
                ->middleware('api')
                ->namespace($this->namespace)
                ->group(base_path('routes/api.php'));

            Route::middleware('web')
                ->namespace($this->namespace)
                ->group(base_path('routes/web.php'));

            Route::middleware('admin')
                ->namespace($this->namespace)
                ->group(base_path('routes/admin.php'));
        });
    }

But it is showing the error like below,

Illuminate\Contracts\Container\BindingResolutionException
Target class [admin] does not exist.
Dec
04
1 month ago
Activity icon

Replied to Throw Throttling Error Message For Ajax

@automica i have used below code and it is returning response with status code,

$message = 'Too Many Attempts. Please try again in ' . $this->availableIn($request) . ' seconds';
throw ValidationException::withMessages([
        $message
    ])->status(Response::HTTP_TOO_MANY_REQUESTS);

and in ajax i have used below code,

.error(function(jqXHR, textStatus, errorThrown) {
              if(jqXHR.status == 429)
              {
								printErrorMsg(jqXHR.responseJSON.errors.email);
                return false;
              } else if(jqXHR.status == 423)
              {
								printErrorMsg(jqXHR.responseJSON.errors.email);
                return false;
              } else {
                swal(jqXHR.responseJSON.message);
                return false;
              }
          });

it is working now.

Activity icon

Started a new Conversation Throw Throttling Error Message For Ajax

Hello, I am using below function to redirect to particular page if he exceeds max limit in throttling

protected function sendThrottledResponse(Request $request)
    {
        throw ValidationException::withMessages([
          'Too Many Attempts. Please try again in '.$this->availableIn($request).' seconds'
        ])->status(Response::HTTP_TOO_MANY_REQUESTS)->redirectTo('user-login');
    }

This is okay if i use reload or without ajax but i want to use this for ajax part how to return this to make compatible with ajax part in json format?