Tippin

Tippin

Member Since 4 Months Ago

TAMPA

Experience Points
11,750
Total
Experience

3,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
13
Lessons
Completed
Best Reply Awards
18
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

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

Level 3
11,750 XP
Jul
04
1 day ago
Activity icon

Awarded Best Reply on I'd Like To Remove The Old Token. (passport, Password Grant)

@yng When a new token is created (any kind of access token), Passport raises an event. You can subscribe for the event and create your own listener to revoke old tokens for the user id and client id https://laravel.com/docs/7.x/passport#events

Example of the revoke listener

<?php

namespace App\Listeners;

use Laravel\Passport\Events\AccessTokenCreated;
use DB;

class RevokeOldTokens
{
    /**
     * The name of the queue the job should be sent to.
     *
     * @var string|null
     */
    public $queue = 'default';

    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  AccessTokenCreated  $event
     * @return void
     */
    public function handle(AccessTokenCreated $event)
    {
        DB::table('oauth_access_tokens')
            ->where('id', '<>', $event->tokenId)
            ->where('user_id', $event->userId)
            ->where('client_id', $event->clientId)
            ->update(['revoked' => true]);
    }
}

Event service provider

<?php

namespace App\Providers;

use App\Listeners\RevokeOldTokens;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Laravel\Passport\Events\AccessTokenCreated;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        AccessTokenCreated::class => [
            RevokeOldTokens::class,
        ],
    ];

    /**
     * Register any events for your application.
     *
     * @return void
     */
    public function boot()
    {
        parent::boot();
    }
}
Activity icon

Replied to I'd Like To Remove The Old Token. (passport, Password Grant)

@yng When a new token is created (any kind of access token), Passport raises an event. You can subscribe for the event and create your own listener to revoke old tokens for the user id and client id https://laravel.com/docs/7.x/passport#events

Example of the revoke listener

<?php

namespace App\Listeners;

use Laravel\Passport\Events\AccessTokenCreated;
use DB;

class RevokeOldTokens
{
    /**
     * The name of the queue the job should be sent to.
     *
     * @var string|null
     */
    public $queue = 'default';

    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  AccessTokenCreated  $event
     * @return void
     */
    public function handle(AccessTokenCreated $event)
    {
        DB::table('oauth_access_tokens')
            ->where('id', '<>', $event->tokenId)
            ->where('user_id', $event->userId)
            ->where('client_id', $event->clientId)
            ->update(['revoked' => true]);
    }
}

Event service provider

<?php

namespace App\Providers;

use App\Listeners\RevokeOldTokens;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Laravel\Passport\Events\AccessTokenCreated;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        AccessTokenCreated::class => [
            RevokeOldTokens::class,
        ],
    ];

    /**
     * Register any events for your application.
     *
     * @return void
     */
    public function boot()
    {
        parent::boot();
    }
}
Activity icon

Awarded Best Reply on When I Made Passport Client(Password Grant Token)

@yng The name is simply so you can give the client something easy to reference by (name), and in case you ever want to pull the name directly to show in a view or through API. The providers is simply asking which "model" the client is linked to for authorization. If you say had users, admins, companies models, you may want different oauth clients to be linked to different auth models. In that case, you would also setup more models in the passport config under the providers array.

Jul
03
2 days ago
Activity icon

Replied to When I Made Passport Client(Password Grant Token)

@yng The name is simply so you can give the client something easy to reference by (name), and in case you ever want to pull the name directly to show in a view or through API. The providers is simply asking which "model" the client is linked to for authorization. If you say had users, admins, companies models, you may want different oauth clients to be linked to different auth models. In that case, you would also setup more models in the passport config under the providers array.

Jul
02
3 days ago
Activity icon

Replied to Best Way To Manage Device FCM Token ?

@michaelnguyen547 On both iOS and Android, you can get the Unique device ID (not the FCM token) and use that on login/register/app wakeup to post FCM token and Device ID, Then in the logic, you can check if you have that device ID, and if you do update to w.e FCM token is sent as well. If new device ID, store new row in DB instead of update. I also let the user id be nullable so that I can link to a user once authed if I collected the device as a guest.

    public function up()
    {
        Schema::create('user_devices', function (Blueprint $table) {
            $table->uuid('user_id')->nullable();
            $table->string('device_id', 255)->unique();
            $table->string('device_token', 255)->unique();
            $table->string('voip_token', 255)->nullable();
            $table->integer('badges')->nullable();
            $table->integer('device_type')->nullable(); //0 = android, 1 = iOS
            $table->timestamps();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
        });
    }
Jun
30
5 days ago
Activity icon

Replied to Video Call App

My code above is simply a full demo, but not separated into an installable package. You would have to extract out my ideas/code into your own project right now. Assuming you have my prerequisites installed (DB, REDIS, laravel-echo-server), my install docs should work. I am currently in the process of rewriting it from scratch and having a proper API/Documentation for all of my methods.

Activity icon

Replied to Routes Horizon And Websockets

@slickness Horizon already provides an authorization gate on the route you define in their config. Follow their instructions adding the authorize gate in Horizons service provider.

https://laravel.com/docs/7.x/horizon#dashboard-authorization

You can also create your own gates on routes or actions to enforce on whatever route you created for your websocket admin page. You may also create middleware and attach them to the routes as well

https://laravel.com/docs/7.x/authorization#gates https://laravel.com/docs/7.x/middleware#defining-middleware

Jun
29
6 days ago
Activity icon

Replied to Laravel Horizon Install Error

@shuvobhai You are missing the php extension ext-pcntl. Now this extension is NOT supported on windows directly, but if you have Windows Subsystem for Linux installed, you can indeed install that extension through WSL, then you just have to be sure to use WSL terminal when running composer install. This also means if you use artisan serve locally, you must run it through WSL if you wish to actually run horizon locally.

Jun
24
1 week ago
Activity icon

Replied to Is There A Way To Prevent User From Accessing Non-GET Routes?

@chron You can override what you want certain exceptions to do in the Exceptions/Handler.php, for example catch the Method not allowed exception and check if it is a JSON response, otherwise redirect to w.e route you want

    /**
     * Render an exception into an HTTP response.
     *
     * @param  Request  $request
     * @param  Throwable $exception
     * @return Response
     *
     * @throws Throwable
     */
    public function render($request, Throwable $exception)
    {
        if($exception instanceof MethodNotAllowedHttpException){
            if($request->expectsJson()){
                return response()->json([
                    'message' => "Method not allowed"
                ], 405);
            }
            return redirect()->route('home');
        }
            
        return parent::render($request, $exception);
    }
Jun
22
1 week ago
Activity icon

Awarded Best Reply on API Nested Shallow Resource Policy Not Registering Correctly?

One other thing I think you missed is naming the parameter in your constructor, try:

public function __construct()
{
    $this->authorizeResource(MainMachine::class, 'machine');
}

https://laravel.com/docs/7.x/authorization#via-controller-helpers

Jun
21
2 weeks ago
Activity icon

Replied to API Nested Shallow Resource Policy Not Registering Correctly?

One other thing I think you missed is naming the parameter in your constructor, try:

public function __construct()
{
    $this->authorizeResource(MainMachine::class, 'machine');
}

https://laravel.com/docs/7.x/authorization#via-controller-helpers

Activity icon

Replied to API Nested Shallow Resource Policy Not Registering Correctly?

@rotario Route model bindings must match the type hinted variable name, and in this case it expects MainMachine to be $machine instead of $mainMachine. Try

    public function update(User $user, MainMachine $machine)
    {
        return true;
    }

Be sure the type hints also match in your controller methods

May
23
1 month ago
Activity icon

Replied to How Does Cmgmyr/messenger Do What It Does??

All that is doing is calling extra calls to the database from within the blade files. When it loads the thread model itself in the controller, it does not include any relations at that point. However, if you check the blade files, you will see it load relations such as $thread->messages, and the thread model already has a hasMany relation to the message class. As for the user object, notice it calls $thread->creator()->name. You can trace that back to their Thread model class in the src:

    public function creator()
    {
        if ($this->creatorCache === null) {
            $firstMessage = $this->messages()->withTrashed()->oldest()->first();
            $this->creatorCache = $firstMessage ? $firstMessage->user : Models::user();
        }

        return $this->creatorCache;
    }

Thread model

https://github.com/cmgmyr/laravel-messenger/blob/master/src/Models/Thread.php#L104

Thread blade

https://github.com/cmgmyr/laravel-messenger/blob/master/examples/views/messenger/partials/thread.blade.php#L11

May
09
1 month ago
Activity icon

Replied to Maintenance Mode Exception

Seems you may want to use the Http Kernal.php to throw your own custom message if site is down. I have used this method in the past where I check the exception class thrown and use a switch case to return my own message if is json request, or regular render if not a json request. You can add all the exceptions you want in the switch, such as (TokenMismatchException, ThrottleRequestsException, NotFoundHttpException, etc)

class Handler extends ExceptionHandler
{
    /**
     * @param Exception $exception
     * @return mixed|void
     * @throws Exception
     */
    public function report(Exception $exception)
    {
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param Request $request
     * @param Exception $exception
     * @return Response|JsonResponse|RedirectResponse|Redirector
     * @throws Exception
     */
    public function render($request, Exception $exception)
    {
        switch(class_basename($exception)){
            case 'MaintenanceModeException':
                if ($request->expectsJson()){
                    return response()->json(['error' => 'The site is currently down for maintenance, please check back with us soon'], 503);
                }
                return parent::render($request, $exception);
            break;
        }
        if (app()->isProduction()){
            if ($request->expectsJson()){
                return response()->json('Server Error',500);
            }
            return response()->view('errors.500', [], 500);
        }
        return parent::render($request, $exception);
    }
May
08
1 month ago
Activity icon

Replied to Validation Problems

Validate is called on a request as that is where you validate user input. If it passes, you can go down in your store method and create the new tag class. And use the custom rule to write your logic for the lowercase portion. If it passes validation, you can then lowercase it again if you choose before creating tag. https://laravel.com/docs/7.x/validation#quick-writing-the-validation-logic

Activity icon

Replied to Validation Problems

Look into writing your own custom rule you can use in laravels validator. Also, validate is called on a request, and you seem to be calling it on your Tag class.

https://laravel.com/docs/7.x/validation#custom-validation-rules

May
03
2 months ago
Activity icon

Awarded Best Reply on I Don't Receive A Broadcast Message In The Front End Laravel-echo-server

@jorge_dev96 It could be the event name your Echo is listening for. By default laravel will broadcast the event's class name and prepend the namespace as well, so you may be receiving App\Events\NewMessage and did not setup Echo namespace. I prefer to name my events instead using their broadcastAs method. Then in your listener you use your defined name prepended with a "." as such:

NewMessage Event class add

    public function broadcastAs()
    {
        return 'NewMessage';
    }

ChatApp.vue

    Echo.private(`messages.${this.user.id}`)
        .listen('.NewMessage', (e) => {
          console.log(e);
          if (this.selectedContact && e.message.from == this.selectedContact.id){
                    this.saveNewMessage(e.message);
                    alert('fired');
                }
      });
Apr
27
2 months ago
Activity icon

Replied to If Output Of \Log::info Depens On Some Options?

@petrogromovo Calling the log facade will always write a log to your specified log channels. You could wrap it inside your own logging class that checks for ENV or your own custom config flags and runs the Log::info() if met.

class MyLogService
{
    public static function info(string $string, array $context = [])
    {
        if(!app()->isProduction() || config('logging.custom.info'))
            Log::info($string, $context);
    }

    public static function warning(string $string, array $context = [])
    {
        if(!app()->isProduction() || config('logging.custom.warning'))
            Log::warning($string, $context);
    }
}
    $lol = 'ok';
    MyLogService::info($lol)
Apr
25
2 months ago
Activity icon

Awarded Best Reply on How To Send Http Post Request With Timer In Laravel

Look into the docs for the laravel scheduler https://laravel.com/docs/7.x/scheduling

You setup the cronjob that will call artisan schedule each minute

* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1

From there you can tell it when exactly to trigger either a command, job, etc. I personally would create a new custom artisan command that just calls your method in your controller. Then tell the scheduler to call that command at your choosing

$schedule->command('api:store-data')->daily();
Activity icon

Replied to How To Send Http Post Request With Timer In Laravel

Look into the docs for the laravel scheduler https://laravel.com/docs/7.x/scheduling

You setup the cronjob that will call artisan schedule each minute

* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1

From there you can tell it when exactly to trigger either a command, job, etc. I personally would create a new custom artisan command that just calls your method in your controller. Then tell the scheduler to call that command at your choosing

$schedule->command('api:store-data')->daily();
Activity icon

Awarded Best Reply on Detect API Request In Laravel

@dutchman1990 Does your app use different headers or authorization token at all? If it does, you can make a helper function to check the headers for a key. Our app sends Authorization header (for passport) while our web end uses the passport web cookie in the web session, so I just lookout for the Authorization key to know it is app:

if(request()->hasHeader('Authorization')){
    //is from app
}
Apr
24
2 months ago
Activity icon

Replied to Missunderstanding Php Artisan Schedule:run Use

@meredevelopment The scheduler is "dumb" in the sense that it does not know how many times it was called within one minute. What is actually happening is when you call the schedule command, it matches the time on the server and sees if anything matches, and everyMinute() would be called every time you ran it as the time matches a minute of any hour, where everyFiveMinutes would only run at any 5min interval of an hour (1pm, 1:05pm, 1:10pm, etc). If you ran it twice at 1:05pm, you would have fired off twice (everyMinute and everyFiveMinutes). Daily runs when the time matches 12am. The goal is to setup a cronjob that runs the artisan schedule command once per minute on your server. Running locally and triggering manually will always cause the everyMinute to fire, or any matching "times". everyTenMinutes added in would fire all 3 (minute, 5 minute, 10 minute) if the time were 1:10.

Setup the cronjob to hit it once per minute and you are golden :

* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
Activity icon

Awarded Best Reply on POST Http://127.0.0.1:8000/messages 500 (Internal Server Error)

First it looks like your ChatEvent expects a Chat::class, but from your controller it looks like you send it a Message class? Unless you creating a message() is Chat.

Also as per the docs, when you authorize a presence channel, you need to return an array about the user yourself, not the model directly (though I have never tried that)

Broadcast::channel('chat', function ($user) {
    return ['id' => $user->id, 'name' => $user->name];
});

Last note, assuming you are testing on local directly, you may want to go into the broadcasting.php config file and turn encrypted to false in local dev

        'pusher' => [
            'driver' => 'pusher',
            'key' => env('PUSHER_APP_KEY'),
            'secret' => env('PUSHER_APP_SECRET'),
            'app_id' => env('PUSHER_APP_ID'),
            'options' => [
                'cluster' => env('PUSHER_APP_CLUSTER'),
                'encrypted' => false
            ],
        ],

Activity icon

Replied to Detect API Request In Laravel

@dutchman1990 Does your app use different headers or authorization token at all? If it does, you can make a helper function to check the headers for a key. Our app sends Authorization header (for passport) while our web end uses the passport web cookie in the web session, so I just lookout for the Authorization key to know it is app:

if(request()->hasHeader('Authorization')){
    //is from app
}
Activity icon

Replied to POST Http://127.0.0.1:8000/messages 500 (Internal Server Error)

First it looks like your ChatEvent expects a Chat::class, but from your controller it looks like you send it a Message class? Unless you creating a message() is Chat.

Also as per the docs, when you authorize a presence channel, you need to return an array about the user yourself, not the model directly (though I have never tried that)

Broadcast::channel('chat', function ($user) {
    return ['id' => $user->id, 'name' => $user->name];
});

Last note, assuming you are testing on local directly, you may want to go into the broadcasting.php config file and turn encrypted to false in local dev

        'pusher' => [
            'driver' => 'pusher',
            'key' => env('PUSHER_APP_KEY'),
            'secret' => env('PUSHER_APP_SECRET'),
            'app_id' => env('PUSHER_APP_ID'),
            'options' => [
                'cluster' => env('PUSHER_APP_CLUSTER'),
                'encrypted' => false
            ],
        ],

Apr
21
2 months ago
Activity icon

Awarded Best Reply on How To Have Multiple Domains For COOKIE Session?

@martinzeltin What I did to solve this was create a middleware to override the config at runtime depending on domain match. Then I was sure to use the middleware priority in the kernal to run my middleware before start session.

Middleware

class SessionDomains
{
    /**
     * Handle an incoming request.
     *
     * @param  Request  $request
     * @param  Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if($request->getHost() === 'best4games.com'){
            config([
                'session.domain' => '.best4games.com'
            ]);
        }
        return $next($request);
    }
}

and in the http Kernal.php, add it at the top of your web middleware group:

    protected $middlewareGroups = [
        'web' => [
            SessionDomains::class,
        ],
    ];

and above start session in priority group

    protected $middlewarePriority = [
        SessionDomains::class,
        StartSession::class,
        ShareErrorsFromSession::class,
        Authenticate::class,
        ThrottleRequests::class,
        AuthenticateSession::class,
        SubstituteBindings::class,
        Authorize::class,
    ];

Activity icon

Replied to How To Have Multiple Domains For COOKIE Session?

@martinzeltin What I did to solve this was create a middleware to override the config at runtime depending on domain match. Then I was sure to use the middleware priority in the kernal to run my middleware before start session.

Middleware

class SessionDomains
{
    /**
     * Handle an incoming request.
     *
     * @param  Request  $request
     * @param  Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if($request->getHost() === 'best4games.com'){
            config([
                'session.domain' => '.best4games.com'
            ]);
        }
        return $next($request);
    }
}

and in the http Kernal.php, add it at the top of your web middleware group:

    protected $middlewareGroups = [
        'web' => [
            SessionDomains::class,
        ],
    ];

and above start session in priority group

    protected $middlewarePriority = [
        SessionDomains::class,
        StartSession::class,
        ShareErrorsFromSession::class,
        Authenticate::class,
        ThrottleRequests::class,
        AuthenticateSession::class,
        SubstituteBindings::class,
        Authorize::class,
    ];

Apr
18
2 months ago
Activity icon

Replied to Where To Put Controller Logic If It Is Sufficiently Complex?

I have more methods in there, again was making an example, not pasting working code that is ready to use. My whole point is I have many areas I may want to log the users "login", thus showed two examples of calling a service method to do that in 2 locations

Activity icon

Awarded Best Reply on Where To Put Controller Logic If It Is Sufficiently Complex?

@catinodev I view a service layer mainly as a place to put business logic that you plan to utilize in more than one location, however it can be a good place to put the bulk of logic as you mentioned outside of a controller. What I do is in my main app directory, I have a Services directory in which I make my service classes. Inside the controller, I type hint the service class dependency in the constructor so laravels service container auto loads the service class I want. Say you have alot of email logic and maybe you want to use methods in more than one controller, make an EmailService.php class in Services directory, add business logic, and inject into controller. i.e:

Email Controller

<?php
namespace App\Http\Controllers;

use App\Services\EmailService;

class EmailController extends Controller
{
    protected $emailService;

    public function __construct(EmailService $emailService)
    {
        $this->emailService = $emailService;
    }

    public function resendVerifyEmail($userId)
    {
        $user = User::findOrFail($userId);
        
        $this->emailService->dispatchVerifyEmail($user);
        
        return response()->json([
            'status' => true
        ]);
    }

EmailService.php

<?php

namespace App\Services;

use App\Mail\RemindVerifyEmail;
use App\User;
use Mail;

class EmailService
{

    public function dispatchVerifyEmail(User $user)
    {
        if(!$user->active) Mail::to($user->email)->send((new RemindVerifyEmail($user))->onQueue('emails'));
    }

}
Activity icon

Replied to Where To Put Controller Logic If It Is Sufficiently Complex?

I was not saying exactly to use it to send mail, but rather just how to move code into one spot for easy use anywhere else in the app. But I understand what you are saying. I do not actually use the above myself, was just writing up a quick example. One of my main services I use is a login logger I can call from web login, register, or from login through passport:

LoginLoggerService

class LoginLoggerService
{

    /**
     * @var LocationService
     */
    private $locateService;

    public function __construct(LocationService $locateService)
    {
        $this->locateService = $locateService;
    }

    /**
     * Get location details from IP through LocationService
     * Store location data and IP to login logs for user
     * @param User $user
     */
    public function store(User $user)
    {
        try{
            $location = $this->locateService->locate();
            $user->loginLogs()->create([
                'ip' => $location['ip'],
                'data' => $location['data'] ? json_encode($location['data']) : null
            ]);
        }catch (Exception $e){
            report($e);
        }
    }

LoginController

class LoginController extends Controller
{
    use AuthenticatesUsers;

    protected $redirectTo = '/dashboard';

    protected $decayMinutes = 5;

    protected $request;
    /**
     * @var LoginLoggerService
     */
    protected $loggerService;

    public function __construct(Request $request, LoginLoggerService $loggerService)
    {
        $this->request = $request;
        $this->loggerService = $loggerService;
    }

    protected function authenticated(Request $request, User $user)
    {
        //other login logic

        $this->loggerService->store($user);

        return response()->json([
            'auth' => true,
            'intended' => session()->get('url.intended')
        ]);
    }

RegisterController

class RegisterController extends Controller
{
    use RegistersUsers;

    protected $redirectTo = '/';

    protected $registerService;

    protected $request;
    /**
     * @var LoginLoggerService
     */
    protected $loggerService;

    public function __construct(Request $request, LoginLoggerService $loggerService)
    {
        $this->request = $request;
        $this->loggerService = $loggerService;
    }

    public function register()
    {
        //Register logic, grabbed new user back

        $this->loggerService->store(auth()->user());

        return response()->json(['registered' => true]);
    }
Activity icon

Replied to Where To Put Controller Logic If It Is Sufficiently Complex?

@catinodev I view a service layer mainly as a place to put business logic that you plan to utilize in more than one location, however it can be a good place to put the bulk of logic as you mentioned outside of a controller. What I do is in my main app directory, I have a Services directory in which I make my service classes. Inside the controller, I type hint the service class dependency in the constructor so laravels service container auto loads the service class I want. Say you have alot of email logic and maybe you want to use methods in more than one controller, make an EmailService.php class in Services directory, add business logic, and inject into controller. i.e:

Email Controller

<?php
namespace App\Http\Controllers;

use App\Services\EmailService;

class EmailController extends Controller
{
    protected $emailService;

    public function __construct(EmailService $emailService)
    {
        $this->emailService = $emailService;
    }

    public function resendVerifyEmail($userId)
    {
        $user = User::findOrFail($userId);
        
        $this->emailService->dispatchVerifyEmail($user);
        
        return response()->json([
            'status' => true
        ]);
    }

EmailService.php

<?php

namespace App\Services;

use App\Mail\RemindVerifyEmail;
use App\User;
use Mail;

class EmailService
{

    public function dispatchVerifyEmail(User $user)
    {
        if(!$user->active) Mail::to($user->email)->send((new RemindVerifyEmail($user))->onQueue('emails'));
    }

}
Apr
15
2 months ago
Activity icon

Replied to I Don't Receive A Broadcast Message In The Front End Laravel-echo-server

@jorge_dev96 It could be the event name your Echo is listening for. By default laravel will broadcast the event's class name and prepend the namespace as well, so you may be receiving App\Events\NewMessage and did not setup Echo namespace. I prefer to name my events instead using their broadcastAs method. Then in your listener you use your defined name prepended with a "." as such:

NewMessage Event class add

    public function broadcastAs()
    {
        return 'NewMessage';
    }

ChatApp.vue

    Echo.private(`messages.${this.user.id}`)
        .listen('.NewMessage', (e) => {
          console.log(e);
          if (this.selectedContact && e.message.from == this.selectedContact.id){
                    this.saveNewMessage(e.message);
                    alert('fired');
                }
      });
Apr
13
2 months ago
Activity icon

Awarded Best Reply on Which Class To Use "implements ShouldQueue"? Notifications V. Queue Job

I queue all of my notifications and jobs. The only items I do not queue are my realtime events that I want broadcasted immediately. The main difference between notification and a job is notification allows specifying multiple channels to send the data on and injects the notifiable model class automatically. I usually use jobs for business logic that does not need to directly notify one person or loops through multiple models to run actions/notification on. I notify for single case uses and house no business logic inside a notification class.

Activity icon

Replied to Which Class To Use "implements ShouldQueue"? Notifications V. Queue Job

I queue all of my notifications and jobs. The only items I do not queue are my realtime events that I want broadcasted immediately. The main difference between notification and a job is notification allows specifying multiple channels to send the data on and injects the notifiable model class automatically. I usually use jobs for business logic that does not need to directly notify one person or loops through multiple models to run actions/notification on. I notify for single case uses and house no business logic inside a notification class.

Activity icon

Replied to Which Class To Use "implements ShouldQueue"? Notifications V. Queue Job

If you are running the worker without horizon, you would run the artisan:work command as you stated above. If you have horizon installed and are using that to work your queue, than you have to use it's startup command php artisan horizon and do not run the regular worker command

Activity icon

Replied to Which Class To Use "implements ShouldQueue"? Notifications V. Queue Job

@trevorpan If you are using horizon, is there a reason you are using: php artisan queue:work redis and not php artisan horizon ?

Activity icon

Replied to Websocket Auth For Private Channels When Using Sanctum SPA Auth

I will attempt to look further into your files as soon as I get more time. I went over your basic files and it seems you followed the laravel docs exactly. I will add I have not worked with sanctum before, so that part is new to me. I do see I was wrong above about the broadcast routes being in service provider, as sanctum does want them in the api.php routes file. One thing I did notice was it seems most of your routes are in the web.php, but should they not be inside api.php? In their docs, it states to put sanctum protected routes/middleware in the api.php

api.php

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});
Apr
12
2 months ago
Activity icon

Replied to Horizon Is Active But Jobs Not Processing

Just wondering, on local I see it works the "default" queue, and on production it works the 'vehicles', 'notifications' queues. Are you sure you are pushing jobs to the non-default queues on production? You may also want to add default to that array in case to test, and be sure to config:cache and restart horizon

Activity icon

Replied to Bootstrap Not Working After Laravel Upgraded Jquery To Version 3.5

@joejobeh I had this same issue two days ago! For now, I removed the caret from my package.json for jquery and left it at

"jquery": "3.4.1",
Activity icon

Replied to Websocket Auth For Private Channels When Using Sanctum SPA Auth

@jalfie Just curious, did you set the Broadcast routes in your api routes file, or from the broadcast service provider, example below:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Broadcast;

class BroadcastServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Broadcast::routes(["prefix" => "api", "middleware" => ["auth:sanctum"]]);
        require base_path('routes/channels.php');
    }
}
Activity icon

Awarded Best Reply on Reasons For Erratic Behaviour Loading Constants From Env->config->blade?

@brainmaniac Try caching the config files first to update your cached configs, assuming you already ran that command in the past. If on local, you can also clear your config cache and have it read directly from your .env

php artisan config:clear
php artisan config:cache
Activity icon

Replied to Reasons For Erratic Behaviour Loading Constants From Env->config->blade?

@brainmaniac Try caching the config files first to update your cached configs, assuming you already ran that command in the past. If on local, you can also clear your config cache and have it read directly from your .env

php artisan config:clear
php artisan config:cache
Apr
09
2 months ago
Activity icon

Replied to Class 'Arcanedev\LogViewer\LogViewerServiceProvider' Not Found

@zaster You may need to manually go into your bootstrap/cache folder and remove the files inside. Then rerun config:cache, route cache if you use that, etc

config.php
packages.php
services.php

You may also need to remove that from your config/app.php if you placed that line under your providers

Activity icon

Replied to Laravel 7 Breaks JSON Responses

I have not done this myself, but found an article that uses middleware to force it

https://medium.com/@DarkGhostHunter/laravel-convert-to-json-all-responses-automatically-c4a72b2fd3ac

Activity icon

Replied to Laravel 7 Breaks JSON Responses

I see comments online about being able to return an array directly in laravel 5 and it turning into json, however I have always been using the example I posted above for 3 years now myself if I want json. If you need to check if json is expected or not to change your return methods you can also use request()->expectsJson() check

Activity icon

Replied to Laravel 7 Breaks JSON Responses

Can you show your controller method code please? In the upgrade guide, it stated

The deprecated Illuminate\Http\Resources\Json\Resource class has been removed. Your resources should extend the Illuminate\Http\Resources\Json\JsonResource class instead.

You can still return json using:

return response()->json([
    'data' => 'Some Data'
]);
Apr
08
2 months ago
Activity icon

Replied to How To Get User Id In Constructor

@jinsonjose It is not recommended to try to access Auth inside the constructor of the controller, however at one point I was playing around with this, and if you MUST do it, you can reorder the session middleware to run before your web group middleware is run. Inside your Http/Kernal.php, move the session middleware from web to the global middleware, but know this means it is run for ANY request at any time through your app.

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        CheckForMaintenanceMode::class,
        ValidatePostSize::class,
        TrimStrings::class,
        ConvertEmptyStringsToNull::class,
        TrustProxies::class,

        //put session middleware here instead of web group below
        StartSession::class,
        AuthenticateSession::class,
        ShareErrorsFromSession::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            EncryptCookies::class,
            AddQueuedCookiesToResponse::class,
            VerifyCsrfToken::class,
            SubstituteBindings::class,
        ],

        'api' => [
            //\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
            'bindings'
        ],


    ];
Apr
07
2 months ago
Activity icon

Replied to Laravel Passport When Pass Bad Credential, This Error Is Show

Are you asking how to suppress the error message itself, assuming you are also getting that in your error log? If so, edit your Exceptions/Handler.php to ignore them, and you can also add the unauthenticated method to catch such errors and return your own message:

<?php

namespace App\Exceptions;

use App;
use Exception;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Laravel\Passport\Exceptions\OAuthServerException;
use Symfony\Component\HttpFoundation\Response;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        OAuthServerException::class,
        \League\OAuth2\Server\Exception\OAuthServerException::class
    ];

    /**
     * Convert an authentication exception into an unauthenticated response.
     *
     * @param  Request  $request
     * @param AuthenticationException $exception
     * @return RedirectResponse|JsonResponse
     */
    protected function unauthenticated($request, AuthenticationException $exception)
    {
        session()->flash('info_message', 'Please login to continue');
        if ($request->expectsJson()) {
            return response()->json(['error' => 'Unauthenticated'], 401);
        }
        return redirect()->guest(route('login'));
    }
Activity icon

Replied to Load Balancers

On a setup I have running I used a single wildcard flag in my trusted proxies

<?php

namespace App\Http\Middleware;

use Illuminate\Http\Request;
use Fideloper\Proxy\TrustProxies as Middleware;

class TrustProxies extends Middleware
{
    /**
     * The trusted proxies for this application.
     *
     * @var array
     */
    protected $proxies = '*';

    /**
     * The headers that should be used to detect proxies.
     *
     * @var int
     */
    protected $headers = Request::HEADER_X_FORWARDED_ALL;
}

My nginx conf is as follows:

map $http_upgrade $type {
  default "web";
  websocket "ws";
}

upstream php {
    server ${PHP_SERVICE_HOST}:${PHP_SERVICE_PORT};
    server ${PHP_SERVICE_HOST}:${PHP_SERVICE_PORT} backup;
}

server {
    listen 80;
    server_name example.com www.example.com;
    client_max_body_size 50M;

    access_log /var/log/example.com.access.log;
    error_log /var/log/example.com.error.log warn;

    root /var/www/html/public/;

    # security headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "no-referrer-when-downgrade" always;
    add_header Content-Security-Policy "default-src * data: 'unsafe-eval' 'unsafe-inline'" always;
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;

    index index.html index.htm index.php;

    charset utf-8;

    #GZIP
    gzip on;
    gzip_disable "msie6";

    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;
    gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;

    location /socket.io {
        proxy_pass http://echo:6001;
        proxy_read_timeout     300;
        proxy_connect_timeout  60;
        proxy_redirect         off;
        proxy_set_header        X-Real-IP       $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;

        # Allow the use of websockets
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'Upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }

    location / {
        try_files /nonexistent @$type;
    }

    location @web {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }
    error_page 404 /index.php;

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass php;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
        fastcgi_next_upstream error timeout;
        fastcgi_buffers 8 16k;
        fastcgi_buffer_size 32k;
        fastcgi_read_timeout 600;
        proxy_read_timeout     300;
        proxy_connect_timeout  60;
        proxy_set_header        X-Real-IP       $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    location ~ /\.(?!well-known).* {
            deny all;
    }
}