amitshahc

amitshahc

Member Since 1 Year Ago

Vadodara

Experience Points 3,750
Experience Level 1

1,250 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 31
Lessons
Completed
Best Reply Awards 0
Best Reply
Awards
  • start-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-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-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist 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.

14 Sep
1 day ago

amitshahc left a reply on $schedule->job Alway Goes To OnFailure

no, i don't think it will have any change in it's behavior as per your explanations, so i just let it be like this.

09 Sep
6 days ago

amitshahc left a reply on $schedule->job Alway Goes To OnFailure

it will take me till today, as i come office only during working days. :P

class SubscriptionRenewal // implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, SerializesModels; // Queueable

still same.. anyways it's going into after() block but still i am not satisfied with the way it always going into onFailure() block too.

08 Sep
1 week ago

amitshahc left a reply on $schedule->job Alway Goes To OnFailure

I will try that tomorrow. but note that my default queue is sync so won't go to database. whereas in notification class i have added $this->connection = 'database'

amitshahc left a reply on $schedule->job Alway Goes To OnFailure

You are not understanding me either.

The scheduler creates a job. That job is queued. (in my case the job is executing and no being queued, only the notifications inside that jobs are being queue. but that's not the point i am asking anyways...)

The scheduler is done. (here it should at least go inside after() function. even if it do not supports the job result evaluation in terms of success or failure.

amitshahc left a reply on $schedule->job Alway Goes To OnFailure

"SubscriptionRenewal job is started" is being printed so the before block is executing. the jobs are also being added in jobs table. but then it always prints the text which is inside onFailure(), i know its working fine. but my question is it's not reporting truth. what if in failure case we want to do something else?

again, my question is only with regards to its wrong reporting. whereas the the other codes with $schedule->commands are reporting exact truth.

amitshahc left a reply on $schedule->job Alway Goes To OnFailure

same flow and behavior like it does for commands.

06 Sep
1 week ago

amitshahc left a reply on $schedule->job Alway Goes To OnFailure

yes, as i mentioned the notification jobs are being added to the jobs table successfully.

amitshahc started a new conversation $schedule->job Alway Goes To OnFailure

I have this code as one of the scheduler task in my Kernel.php file:

$schedule->job(new SubscriptionRenewal($this->repo))->everyMinute()
            ->before(function () {
                echo "\r\n\nSubscriptionRenewal job is started..\n";
            })
            ->after(function () {
                echo "\r\n\nFinished.!\n";
                // $this->_runDBqueue($schedule);
            })
            ->onSuccess(function () use ($schedule) {
                echo "\r\n\nSuccess\n";
                // $this->_runDBqueue($schedule);
            })
            ->onFailure(function () {
                echo "\r\n\nFailed\n";
            })
        // ->withoutOverlapping()
            ->appendOutputTo($this->logfile)
            ->emailOutputTo(config('constants.scheduler.report_email'));

When i run php artisan schedule:run from CLI it always print the Failed message even if the Queued notification i am executing in that job are being added in jobs table. So the task is successfully adding the jobs in table but still it is being considered as Failed task. no log can be found anywhere in the system.

This is my SubscriptionRenewal job class:

<?php

namespace Modules\SuperAdmin\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Modules\SuperAdmin\Entities\Repository\Contract\CronjobRepository;
use Modules\SuperAdmin\Notifications\SubscriptionRenewal as RenewalNotification;

class SubscriptionRenewal implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $repo;
    
    // public $tries   = 10; // Max tries
    // public $timeout = 60; // Timeout seconds

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(CronjobRepository $repo)
    {
        $this->repo = $repo;
        // $this->connection = 'database';
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $shopowners_expiring = $this->repo->getExpiringSubscriptions($days = 7);
        // dd($shopowners_expiring->toArray());
        $shopowners_expiring->each(function ($shopowner) {

            \Notification::send($shopowner, new RenewalNotification);

            // \Mail::to($shopowner)->send((new SubscriptionRenewal($shopowner))->onConnection('database'));

            // dump($shopowner->toArray());
        });

        return true;
    }

    public function failed(\Exception $e)
    {
        dump($e);
        report($e);
    }
}

30 Aug
2 weeks ago

amitshahc left a reply on Informal Poll: Routes File

The beginner will go blank about the route file location.. where to put it for first run. What is the problem for default route file is there?

amitshahc left a reply on Custom Command Running Directly From CLI But Not From Schedule:run In CLI

New issue of execution order

I refactored my Kernel.php as follows:

<?php

namespace App\Console;

use Artisan;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use Modules\SuperAdmin\Entities\Repository\Contract\CronjobRepository;
use Modules\SuperAdmin\Jobs\SubscriptionRenewal;

class Kernel extends ConsoleKernel
{
    protected $repo;
    protected $logfile;
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        \App\Console\Commands\FreeSubscriptionFallback::class,
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $today         = \DateTimeOperations::today()->toDateString();
        $this->logfile = config('constants.scheduler.logfile_path') . $today . '.log';
        $this->repo    = resolve(CronjobRepository::class);

        $this->_renewalNotificationJob($schedule);
        $this->_subscriptionFallback($schedule);

        $schedule->command("inspire")->everyMinute()
        // ->appendOutputTo($logfile)
            ->emailOutputTo(config('constants.scheduler.report_email'));

    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__ . '/Commands');

        require base_path('routes/console.php');
    }

    private function _renewalNotificationJob(&$schedule)
    {
        $schedule->job(new SubscriptionRenewal($this->repo))->everyMinute() //daily()
            ->before(function () {
                echo "SubscriptionRenewal job is started..\n";
            })
            ->after(function () {
                echo "Databse queue is started..\n";
                echo $exitCode = Artisan::call('queue:work database --stop-when-empty');
                echo "Finished.!\n";
                echo Artisan::output();
            })
        // ->withoutOverlapping()
            ->appendOutputTo($this->logfile)
            ->emailOutputTo(config('constants.scheduler.report_email'));
    }

    private function _subscriptionFallback(&$schedule)
    {
        $schedule->command("subscriptions:fallback 2")->everyMinute()
            ->before(function () {
                echo "subscriptions:fallback command is started..\n";
            })
            ->after(function () {
                echo "Finished.!\n";
            })
            ->onSuccess(function () {
                echo "Success\n";
            })
            ->onFailure(function () {
                echo "Failed\n";
            })
        // ->withoutOverlapping()
            ->appendOutputTo($this->logfile)
            ->emailOutputTo(config('constants.scheduler.report_email'));
    }
}

The issue is if i run the job first then no more command are being executed.

$this->_renewalNotificationJob($schedule);
$this->_subscriptionFallback($schedule);

but if i run all the command first and job at last, then everything is being executed.


        $this->_subscriptionFallback($schedule);

        $schedule->command("inspire")->everyMinute()
            ->appendOutputTo($this->logfile)
            ->emailOutputTo(config('constants.scheduler.report_email'));
        
        $this->_renewalNotificationJob($schedule);

The moral of the story is $schedule->job stops further execution.

amitshahc left a reply on Custom Command Running Directly From CLI But Not From Schedule:run In CLI

SOLVED

For those who are failing without having any error logs anywhere make sure this things first. In my case there were a combinations of the reasons.

  1. The "--force" option does not exist remove any options that do not support your custom command and try to run it independent.
  2. This was the most important change: the $logfile path was inside /storage/logs/schedule/today.log so i was expecting that the schedule sub directory will be getting created by its own like a normal behavior. but i was wrong either keep the log file path directly in to /storage/logs/ or create/keep the sub directory /schedule/ being existed before running this command.

amitshahc left a reply on Schedule:run Not Calling Artisan Command

I have created new thread here: https://laracasts.com/discuss/channels/laravel/custom-command-running-directly-from-cli-but-not-from-schedulerun-in-cli#

I realized it's going into onFailure after adding that block. but can't find any logs anywhere.

amitshahc started a new conversation Custom Command Running Directly From CLI But Not From Schedule:run In CLI

My OS is Windows 7 : Laravel 5.8

Some how I also found the same issue and tried everything listed here but no solution yet. I am using Laravel 5.8 and when i run the command from my windows cmd using

php artisan subscription:fallback it's running and i can verify the entries in the database which been created by that job.

But the same command is not executing when i call php artisan schedule:run it prints the messages in before() and after() hooks plus sending the email but with blank content. but no code being executed inside the handle() method.

myLaravelProject >php artisan schedule:run
Running scheduled command: "D:\Installation\php7114\php.exe" "artisan" inspire >> "D:\Installation\Apache24\htdocs\spaadvisor.com\storage\logs/schedule/2019-08-29.log" 2>&1
Running scheduled command: "D:\Installation\php7114\php.exe" "artisan" subscriptions:fallback 2 --force >> "D:\Installation\Apache24\htdocs\spaadvisor.com\storage\logs/schedule/2019-08-29.log" 2>&1
subscriptions:fallback command is started..
Finished.!

FreeSubscriptionFallback:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Modules\SuperAdmin\Entities\Repository\Contract\CronjobRepository;

class FreeSubscriptionFallback extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'subscriptions:fallback {days=2: number of max days from today to calculate expiry date range}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Auto renewal of shop-owner\'s subscriptions to Free for which are expiring within next {days=2} days';

    /**
     * Create a new command instance.
     *
     * @return void
     */

    protected $repo;

    public function __construct(CronjobRepository $repo)
    {
        parent::__construct();
        $this->repo = $repo;
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->info('Subscription fallback command logic : STARTED');
        // dd('hello');
        $days       = (int) $this->argument('days');
        $shopowners = $this->repo->getActiveSubscriptions($days);
        // dd($shopowners);
        try {
            $shopowners->each(function ($shopowner) {
                $this->line('Creating default subscription for shopowner id:', $shopowner->id);
                $this->repo->beginTransaction();
                $this->repo->createSubscription_default($shopowner);
                $this->repo->commit();
            });

            $this->info('Subscription fallback command logic : ENDED');

        } catch (\Throwable $th) {
            $this->repo->rollback();
            $this->error('Subscription fallback command logic : ERROR', $th);
            report($th);
        }
    }
}

Kernel.php:

<?php

namespace App\Console;

use Artisan;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use Modules\SuperAdmin\Jobs\SubscriptionRenewal;
use Modules\SuperAdmin\Entities\Repository\Contract\CronjobRepository;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        \App\Console\Commands\FreeSubscriptionFallback::class,
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        // $schedule->command('inspire')
        //          ->hourly();
        $today    = \DateTimeOperations::today()->toDateString();
        $logfile  = config('constants.scheduler.logfile_path') . $today . '.log'; //storage_path("logs/schedule/". $today .".log");
        $cronRepo = resolve(CronjobRepository::class);

        $schedule->job(new SubscriptionRenewal($cronRepo))->daily()
            ->before(function () {
                echo "SubscriptionRenewal job is started..\n";
            })
            ->after(function () {
                echo "Databse queue is started..\n";
                echo $exitCode = Artisan::call('queue:work database --stop-when-empty');
                echo "Finished.!\n";
                echo Artisan::output();
            })
            ->appendOutputTo($logfile)
            ->emailOutputTo(config('constants.scheduler.report_email'));

        $schedule->command("inspire")->everyMinute()
            ->appendOutputTo($logfile)
            ->emailOutputTo(config('constants.scheduler.report_email'));

        $schedule->command("subscriptions:fallback 2 --force")->everyMinute()
            ->before(function () {
                echo "subscriptions:fallback command is started..\n";
            })
            ->after(function () {
                echo "Finished.!\n";
                // echo Artisan::output();
            })
            ->onSuccess(function () {
                echo "Success";
            })
            ->onFailure(function () {
                echo "Failed";
            })
            ->appendOutputTo($logfile)
            ->emailOutputTo(config('constants.scheduler.report_email'));
        // echo Artisan::output();
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__ . '/Commands');

        require base_path('routes/console.php');
    }
}

After adding ->onFailure() in above i realized that it's printing Failed but no logs anywhere can be found (email, logfile, laravel log, catch..) So how to print the Failure reason?

29 Aug
2 weeks ago

amitshahc left a reply on Schedule:run Not Calling Artisan Command

Some how I also found the same issue and tried everything listed here but no solution yet. I am using Laravel 5.8 and when i run the command from my windows cmd using

php artisan subscription:fallback it's running and i can verify the entries in the database which been created by that job.

But the same command is not executing when i call php artisan schedule:run it prints the messages in before() and after() hooks plus sending the email but with blank content. but no code being executed inside the handle() method.

myLaravelProject >php artisan schedule:run
Running scheduled command: "D:\Installation\php7114\php.exe" "artisan" inspire >> "D:\Installation\Apache24\htdocs\spaadvisor.com\storage\logs/schedule/2019-08-29.log" 2>&1
Running scheduled command: "D:\Installation\php7114\php.exe" "artisan" subscriptions:fallback 2 --force >> "D:\Installation\Apache24\htdocs\spaadvisor.com\storage\logs/schedule/2019-08-29.log" 2>&1
subscriptions:fallback command is started..
Finished.!

FreeSubscriptionFallback:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Modules\SuperAdmin\Entities\Repository\Contract\CronjobRepository;

class FreeSubscriptionFallback extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'subscriptions:fallback {days=2: number of max days from today to calculate expiry date range}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Auto renewal of shop-owner\'s subscriptions to Free for which are expiring within next {days=2} days';

    /**
     * Create a new command instance.
     *
     * @return void
     */

    protected $repo;

    public function __construct(CronjobRepository $repo)
    {
        parent::__construct();
        $this->repo = $repo;
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->info('Subscription fallback command logic : STARTED');
        // dd('hello');
        $days       = (int) $this->argument('days');
        $shopowners = $this->repo->getActiveSubscriptions($days);
        // dd($shopowners);
        try {
            $shopowners->each(function ($shopowner) {
                $this->line('Creating default subscription for shopowner id:', $shopowner->id);
                $this->repo->beginTransaction();
                $this->repo->createSubscription_default($shopowner);
                $this->repo->commit();
            });

            $this->info('Subscription fallback command logic : ENDED');

        } catch (\Throwable $th) {
            $this->repo->rollback();
            $this->error('Subscription fallback command logic : ERROR', $th);
            report($th);
        }
    }
}

Kernel.php:

<?php

namespace App\Console;

use Artisan;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use Modules\SuperAdmin\Jobs\SubscriptionRenewal;
use Modules\SuperAdmin\Entities\Repository\Contract\CronjobRepository;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        \App\Console\Commands\FreeSubscriptionFallback::class,
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        // $schedule->command('inspire')
        //          ->hourly();
        $today    = \DateTimeOperations::today()->toDateString();
        $logfile  = config('constants.scheduler.logfile_path') . $today . '.log'; //storage_path("logs/schedule/". $today .".log");
        $cronRepo = resolve(CronjobRepository::class);

        $schedule->job(new SubscriptionRenewal($cronRepo))->daily()
            ->before(function () {
                echo "SubscriptionRenewal job is started..\n";
            })
            ->after(function () {
                echo "Databse queue is started..\n";
                echo $exitCode = Artisan::call('queue:work database --stop-when-empty');
                echo "Finished.!\n";
                echo Artisan::output();
            })
            ->appendOutputTo($logfile)
            ->emailOutputTo(config('constants.scheduler.report_email'));

        $schedule->command("inspire")->everyMinute()
            ->appendOutputTo($logfile)
            ->emailOutputTo(config('constants.scheduler.report_email'));

        $schedule->command("subscriptions:fallback 2 --force")->everyMinute()
            ->before(function () {
                echo "subscriptions:fallback command is started..\n";
            })
            ->after(function () {
                echo "Finished.!\n";
                // echo Artisan::output();
            })
            ->appendOutputTo($logfile)
            ->emailOutputTo(config('constants.scheduler.report_email'));
        // echo Artisan::output();
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__ . '/Commands');

        require base_path('routes/console.php');
    }
}
21 Aug
3 weeks ago

amitshahc left a reply on SQLSTATE[HY000] [1045] Access Denied For User 'root'@'localhost' (using Password: YES)

Recently I just upgraded my project from Laravel 5.5 to 5.8. But was getting an error when I deployed on the live web server.

SQLSTATE[HY000] [1045] Access denied for user 'avixxxxx_xxxxx'@'localhost' (using password: YES) (SQL: select * from `users` where `username` = [email protected] limit 1)

The password DB_PASSWORD=qoq#12ba i had entered in the .env file was completely fine. but when I checked the /bootstrap/cache/config.php file there it was compiled as 'qoq'. that means the # was being parsed as a comment in .env file.

I was forced to wrap the password inside quotes DB_PASSWORD="qoq#12ba" then it worked.

20 May
3 months ago

amitshahc left a reply on Override Old Input Values

@GIACOMOM - This is what exactly I wanted to achieve. If I come directly on getting route using route or view, not by redirect and I want some dynamic tab name to be loaed based on the data fetched and it checks the old in view input, then this is required.

08 May
4 months ago

amitshahc left a reply on Validate The Password Reset Token Before Showing The Reset Form

@SNAPEY - That's sound logical. But again if the token is valid then he has to find the matching email id too. so checking combination of the token + email is difficult for the attacker. still it's logical. thanks.

amitshahc left a reply on Model::create($data) With Carbon Dates Fields In $data Returns Carbon Object.

@TISUCHI - @TISUCHI -

$data['start_time']    = $dateTimeOperations->getTimestamp($sdate, $startTime, $timezone); //This will return carbon datetime object.

$record = $model::create($data);

// now returned $record->start_time is carbon object and not same as start_time fetched using $record::find(id);

07 May
4 months ago

amitshahc left a reply on Model::create($data) With Carbon Dates Fields In $data Returns Carbon Object.

@TISUCHI - Thanks tisuchi,

But that's not my question.

Just assume there is a start_time[timestamp] field in my table other than created_at, updated_at, deleted_at. And i want to read it. but in both the case of ::create and ::find it returns different format.

Hope you will get the right direction now.

amitshahc started a new conversation Model::create($data) With Carbon Dates Fields In $data Returns Carbon Object.

In my case, using observer, I am trying to save a model object in json format on both events of Create, Update.

  1. When i get $record = $model::create($data); the $record->start_time field remains a Carbon object.
  2. but while updating i fetch that $record using $record = model::find($id); and the $record->start_time is string date format.

Ideally it should be the same in both case and should be string data format.

Why the difference? how to resolve it?

amitshahc left a reply on Validate The Password Reset Token Before Showing The Reset Form

@SNAPEY - Hi Snapey, Thanks for the answer. this i have already seen somewhere.

  1. Can you elaborate more about weakness in security?
  2. I am using different guards for the different roles. how can i fetch the guard's password reset table name dynamically?
03 May
4 months ago

amitshahc left a reply on Validate The Password Reset Token Before Showing The Reset Form

@SNAPEY - Does it even matter if I just want to know how should I achieve this technically, :P?

But Well yes I have good reasons too,

Firstly, This class only comes in execution when someone clicks a reset password link from his/her email. so no issue of traffic.

Secondly, If the token is expired or used, the user comes to know it only after filling the valid form data. instead, it will notify the user on the landing page itself that you no need to go through this useless exercise.

Finally, It's all about UX and client requirement. we can't say no to at least this.

amitshahc started a new conversation Validate The Password Reset Token Before Showing The Reset Form

I am looking for the code modifications in below class where I can put the token validation before showing the password reset form. [in showResetForm() method]

<?php

namespace App\Http\Controllers\ShopmanagerAuth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Password;
use Illuminate\Http\Request;

class ResetPasswordController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Password Reset Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password reset requests
    | and uses a simple trait to include this behavior. You're free to
    | explore this trait and override any methods you wish to tweak.
    |
    */

    use ResetsPasswords;

    /**
     * Where to redirect users after login / registration.
     *
     * @var string
     */
    public $redirectTo = '/shopmanager/dashboard';


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

    /**
     * Display the password reset view for the given token.
     *
     * If no token is present, display the link request form.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  string|null  $token
     * @return \Illuminate\Http\Response
     */
    public function showResetForm(Request $request, $token = null)
    {
        return view('shopmanager.auth.passwords.reset')->with(
            ['token' => $token, 'email' => $request->email]
        );
    }

    /**
     * Get the broker to be used during password reset.
     *
     * @return \Illuminate\Contracts\Auth\PasswordBroker
     */
    public function broker()
    {
        return Password::broker('shopmanagers');
    }

    /**
     * Get the guard to be used during password reset.
     *
     * @return \Illuminate\Contracts\Auth\StatefulGuard
     */
    protected function guard()
    {
        return Auth::guard('shopmanager');
    }

    protected function rules(){
        return [
            'token' => 'required',
            'email' => 'required|email',
            'password' => 'required|confirmed|min:8,max:20',
        ];
    }
}
04 Apr
5 months ago

amitshahc left a reply on Laravel Blade `@auth` Condition Not Working As Expected

@SNAPEY - "hesto/multi-auth" is the plugin i am using.

Routegroup for shopmanger

Route::group(['middleware' => ['web', 'auth:shopmanager', 'shopmanagerVerified'], 'prefix' => 'shopmanager', 'namespace' => 'Modules\ShopManager\Http\Controllers'],
    function () {
    ...
    }

Routegroup for shopowner

Route::group([
    'middleware' => ['web', 'auth:shopowner', 'shopmanagerVerified'],
    'prefix'     => 'shop',
    'namespace'  => 'Modules\ShopManager\Http\Controllers',
],
    function () {
    ...
    }

amitshahc left a reply on Laravel Blade `@auth` Condition Not Working As Expected

@SNAPEY - I didn't get your point. but as per my above code block to verify current login in user and print dd() it is printing correct user i.e. 'shopowner' who is logged in.

amitshahc left a reply on Laravel Blade `@auth` Condition Not Working As Expected

@BOBBYBOUWMANN - inside my auth.php

  'guards' => [
        'superadmin' => [
            'driver' => 'session',
            'provider' => 'superadmins',
        ],

        'shopowner' => [
            'driver' => 'session',
            'provider' => 'shopowners',
        ],

        'shopadmin' => [
            'driver' => 'session',
            'provider' => 'shopadmins',
        ],

        'shopmanager' => [
            'driver' => 'session',
            'provider' => 'shopmanagers',
        ],
        
        'admin' => [
            'driver' => 'session',
            'provider' => 'admins',
        ],

        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        
    ],

amitshahc started a new conversation Laravel Blade `@auth` Condition Not Working As Expected

I am trying to pick the master blade template dynamically as per the current user roll logged in. (here it should go to the 'shopowner' auth block)

@auth('shopmanager')
@extends('theme::Admins.shopmanager.layout.master')
@endauth

@auth('shopowner')
@extends('theme::Admins.shopowner.layout.master')
@endauth

but this always gives error as it tries to compile the 'shopmanager' master template. It is not going into the 'shopmanager' @auth block because it's not printing anything if I print inside that block.

It only works if I completely comment that line.

P.S.: i tried using this syntax too.. but same results.

if (Auth::guard('shopmanager')->check())
...

also echo the condition check which works perfect without @extends(...) syntax. This goes in shopowner which is right.

@if(Auth::guard('shopmanager')->user())
   {{dd(Auth::guard('shopmanager')->user())}}
@else
   {{dd(Auth::guard('shopowner')->user())}}
@endif
23 Nov
9 months ago

amitshahc left a reply on How Do You Pass Constructor Parameters When You're Instantiating An Interface Through A Bind?

@MITHRANDIR - That thing I was already doing using this code. but i wanted to set the AuthId in counstuctor of the ShopManagerRepository. so I can pass at the time of making its instance.

public function __construct(ShopManagerRepository $repo)
{
    $this->repo = $repo;

    $this->middleware(function ($request, $next) {
        $this->repo->setAuthId(Auth::id());//new $repo(Auth::id());
        return $next($request);
    });
}
22 Nov
9 months ago

amitshahc left a reply on How Do You Pass Constructor Parameters When You're Instantiating An Interface Through A Bind?

But how can I pass (Auth::id()) to the target class while binding it? I am injecting the interface from the controller Constructor.

...

public function register()
{
    $this->app->singleton(ShopManagerRepository::class, ShopManagerEloquent::class);  
}

...

and in controller:

...

public function __construct(ShopManagerRepository $repo)
{        

    $this->middleware(function ($request, $next) {
        $this->repo = new ShopManagerRepository(Auth::id()); //new $repo(Auth::id());
        return $next($request);
    });
}

...

nothing works.

05 Nov
10 months ago

amitshahc left a reply on Laravel 5.1 Custom HTTP Status Code And Status Text

Laravel version: 5.5

I am trying to return custom http status code from the laravel controller. (Calling this url using jQuery Ajax $.get())

In my controller function I tried both the way mentioned bellow but it's not working.

  1. This one returns error "Method setStatusCode does not exist."

    return response()->setStatusCode(202);
    
  2. This one not throwing error but returning 200 always.

    $response = new Response();
    $response->setStatusCode(202);
    $response->header('custom', 555);
    return $response;`
    

Below is also not returning 200 ok:

return response()->json("response content", 202);
//or
return response()->make("response content", 202);
01 Nov
10 months ago

amitshahc left a reply on Undefined Method RouteNotificationFor While Saving Notification To Database

Did you find the solutions? I am getting the same error.

27 Oct
10 months ago

amitshahc left a reply on Laravel Pagination Showing Current Items Count Numbers

Update:

@Mithridates why so complex logic when it can be obtain by direct object members $shops->firstItem() and $shops->lastItem()

Also, in case of total 9 records it will show wrong in last page Showing 6 to 10 of total 9 entries

Showing {{ $shops->firstItem() }} to {{ $shops->lastItem() }}
of total {{$shops->total()}} entries
26 Oct
10 months ago

amitshahc left a reply on Laravel Pagination Showing Current Items Count Numbers

@Mithridates answer worked but wondering how come {{($shops->currentpage()-1)*$shops->perpage()+1}} evaluates. because if current page is 1 then it will be something (1-1) i.e. 0*anything = 0

11 Oct
11 months ago

amitshahc left a reply on Auth::user() Return Null In Construct.

@ModestasV 's answer worked for me.