Braunson

Member Since 5 Years Ago

Ontario, Canada

Founder at Geekybeaver

Experience Points 29,855
Experience Level 6

145 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 120
Lessons
Completed
Best Reply Awards 34
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 Aug
1 week ago

Braunson left a reply on Are Event Listeners Cached In Some Way?

From the docs..

... during your deployment process, you should run the event:cache Artisan command to cache a manifest of all of your application's events and listeners

So yes event & listeners are cached. Clear your cache on deployment and if you are using queue's, restart them on deploy.

01 Aug
3 weeks ago

Braunson left a reply on Saving API Usage For Metered Billing

I don't know of any handy package but I want to suggest using Middleware to do the counting for you, it abstracts that logic away from your API endpoint controller methods.

If you do build one, you should publish it as a package, I'm sure others would appreciate it :)

Braunson left a reply on How To Setup A Callback API Endpoint That Recieves Payment Status From A Payment Gateway

I'm not sure what Payment Processor you are using but you would look at their dev docs to see what is being sent to your server when you provide them with a webhook. Are they providing a POST or GET request?

They should also provide you with some information as to what they are POSTing. Typically a webhook will be a POST especially when they are sending you a bunch of data.

So check your PP's dev docs to see what they send you and how. Outside of that it's up to you to do with the $request as you choose.

As an example, MailGun will POST to a webhook URL I provide. I used their docs to find out what they POST to me and I actually validate the incoming request (using custom Middleware) well I validate the signature included in the request.

So check the docs, and what you are provided with do what you need to with the $request :)

30 Jul
3 weeks ago

Braunson left a reply on Change Request Body Middleware

Your looking at (from the title) a method for Slim maybe?

You can do this with Middleware doing so like this:

Example File: app/Http/Middleware/TestMiddleware.php

<?php namespace App\Http\Middleware;

use Closure;

class TestMiddleware
{

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $input = $request->all();

        if (isset($input['foo'])) {
        $input['foo'] = 'bar';

            // Input modification
            $request->replace($input);

            \Log::info($request->all()); // Shows modified request
        }

        return $next($request);
    }

}
24 Jul
4 weeks ago

Braunson left a reply on Convert String Array To Array Of Int(s)

array_map to intval ;-)

$array = ["123", "34", "223"];
$integerIDs = array_map('intval', $array);
17 Jul
1 month ago

Braunson left a reply on Saving For Each Loop

Try clearning your cache and cookies:

php artisan cache:clear then delete browser cookies. This issue has been posted previously on this form, try searching next time :)

14 Jul
1 month ago

Braunson left a reply on Laravel Make Service Pattern Command

Just a suggestion, good job but perhaps stub out some example methods in the service stub as a starting point for others? :)

27 Jun
1 month ago

Braunson left a reply on How Can I Show Edit And Delete Button To The Post Owner In Vuejs Comeponent Larave?

You will need some way to know the current logged in user as well as the post user. Since you are passing in the post parameter to the deletePost method in Vue you should have access to post.user_id now you just need to find a way to get the currently logged in user.

You can set it like so https://stackoverflow.com/a/52703853/610880

Then you would use v-if something like this:

<li><a @click="deletePost(post,key)" v-if="post.user_id === user.id" title="Edit Post" class="pencil-edit">Edit Post</a></li>
24 Jun
1 month ago

Braunson left a reply on Laravel Cashier - Adding Days To Subscription

@Tyler The repo is your friend in this case, you can see what happens then you 'cancel' a subscription via the cancel method.

For Stripe: https://github.com/laravel/cashier/blob/707ef5ec28974f74c57461ef25c125c46050d885/src/Subscription.php#L404

The code will cancel the subscription at the end of the billing period. The code will set the cancel_at_period_end field in stripe to true. Stripe will end the subscription at the end of the billing period.

For BrainTree: https://github.com/laravel/cashier-braintree/blob/1b9c2500a030fa7589386d829160d63669ead7fa/src/Subscription.php#L369

You can see the code uses the BraintreeSubscription class to call cancel() which if we dig into the braintree/braintree_php package you'll see here it calls the Braintree API Gateway and calls here to cancel the subscription in Braintree.

So to answer your question simply:

  1. Yes there is a difference in using the cancel subscription method vs deleting the entry from the DB. The subscription is technically stored on the Processor side (Stripe/Braintree), your app's database just keeps reference of it, deleting it in your db will just delete your app's reference, the customer will still be billed by the processor (Stripe/Braintree) since that's where the actual processing/charging magic happenbs.

  2. Cashier-Braintree is just a wrapper to help facilitate the use of BrainTree in Laravel, if you want to use t he direct BrainTree PHP library, go for it, but I'd personally use Cashier and if it doesn't do what I need, to just extend it to suit my needs.

I hope this helps give you more insight and a better idea on how things work under the hood with Laravel's Cashier/Cashier-Braintree :)

Braunson left a reply on Integrate PHP Code With Contact Form 7 Fields

@hassanshahzadaheer You can see how to do it in the CF7 docs https://contactform7.com/selectable-recipient-with-pipes I've updated my answer to include an example of a dropdown in the CF7 edito.

An example of how to create dropdowns in CF7 editor:

[select cows "1" "2" "3"]
21 Jun
2 months ago

Braunson left a reply on Laravel Cashier - Adding Days To Subscription

Yes that sounds like your best bet. I'm not familiar at all with BrainTree myself but from the flow you've described.

  1. Cancel users existing subscription $user->subscription('fooSub')->cancel();
  2. Create a subscription that ends on X date
  3. Subscribe the user to the new subscription.

On step 2, since Cashier (BrainTree) doesn't seem to have methods to create custom subscriptions, you'll have to do this likely with the BrainTree PHP library @ https://developers.braintreepayments.com/reference/request/subscription/create/php manually. You will want to set the billing day of month to the new date you need.

$result = $gateway->subscription()->create([
  'paymentMethodToken' => $token,
  'planId' => 'custom_plan_foo1234',
  'billingDayOfMonth' => 30,
  // ...
]);

After that you can just re-subscribe your user using Cashier like so: $user->newSubscription('newSub')->create($token); You will need the CC token also to re-subscribe the user.

Braunson left a reply on 'no Input Specified' Challenge On The Browser When Trying To Load 'homestead.test'

Looks like you have another issue here where the base box won't download. Please check this solution https://github.com/mitchellh/vagrant/issues/6725#issuecomment-223733553

Braunson left a reply on Laravel Cashier - Adding Days To Subscription

Yes anchorBillingCycleOn is for Stripe only. As for BrainTree it doesn't look like there is an option for what you need in Cashier.

I can suggest another option, is using the 'trial days' instead and requiring CC on setup so they have X many days before they are "subscribed". This however only works on initial sign up but not necessarily when they are/have been subscribed already.

You cannot change the billing date on an existing subscription, you must cancel the subscription and create a new one.

With Braintree, the next billing date is calculated, and so can't be changed unfortunately.

Braunson left a reply on 'no Input Specified' Challenge On The Browser When Trying To Load 'homestead.test'

Make sure your Homestead.yaml project / folders paths are correct. Then run vagrant up --provision and try the URL again.

Braunson left a reply on Lavacharts Gauge Colors

I'm not super familiar with Lavacharts but looking at the docs on both Lavacharts and Google it looks like only

  • greenColor
  • redColor
  • yellowColor

https://developers.google.com/chart/interactive/docs/gallery/gauge#Configuration_Options

Braunson left a reply on Database Sessions Pruning

Yes they are cleaned out. There is another thread on Laracasts here asking the same question. Check out https://github.com/laravel/laravel/blob/master/config/session.php specifically look at the comment for Lottery.


    /*
    |--------------------------------------------------------------------------
    | Session Sweeping Lottery
    |--------------------------------------------------------------------------
    |
    | Some session drivers must manually sweep their storage location to get
    | rid of old sessions from storage. Here are the chances that it will
    | happen on a given request. By default, the odds are 2 out of 100.
    |
    */

Laravel cleans up expired session entries based on a lottery setting.

However note that not all session drivers require manual cleanup, something like Redis doesn't need it because it automatically deletes expired keys.

You can see in the StartSession middleware where it cleans up the sessions using the method collectGarbage which cleanrs the session based on the lottery config (above).

https://github.com/illuminate/session/blob/master/Middleware/StartSession.php

The default configurations are [2, 100]. It means that a random integer is chosen between 1 and 100, if it's lower or equals to 2 the cache will be cleared. (Aka you have a 2% possibility to clear the cache every call).

20 Jun
2 months ago

Braunson left a reply on Integrate PHP Code With Contact Form 7 Fields

You'll want to look into the Hooks the Contact Form 7 provides. You'll hook into the response to output what you want.

As for the dropdowns, you create them in the Contact Form 7 form editor with the provided options.

You can see a list of hooks at http://hookr.io/plugins/contact-form-7/5.1.3/hooks/#index=a (for the latest version of CF7), you'll probably want something like the wpcf7_ajax_json_echo hook to modify the outbound response returned to the user. Here's an example:

Something like this (untested), but it would go in your wp-content/themes/footheme/functions.php (your theme, functions file).

add_filter('wpcf7_ajax_json_echo', function( $response, $result )
{
    $cow  = 100;
    $goat = 200;

    if (isset($response['cow']) || isset($response['goat'])) {
        if (isset($response['cow'])) {
            $cowSelect = $response['cow'];
            $cow = ($cow - $response['cow']);

            switch ($cowSelect) {
                case '1':
                case '2':
                case '3':
                case '4':
                case '5':
                    $message .= 'Total '.$cow.' cows remaning'.'<br/>';
                    break;
            }
        }

        if (isset($response['goat'])) {
            $goatSelect = $response['goat'];
            $goat = ($goat - $response['goat']);

            switch ($goatSelect) {
                case '1':
                case '2':
                case '3':
                case '4':
                case '5':
                    $message .= 'Total '.$goat.' goats remaning'.'<br/>';
                    break;
            }
        }
    }

    return $response;
}, 10, 2);

Then you just need to create a dropdown with the options you want, make the dropdown required (if it needs to be required) in the Contact Form 7 form editor.

29 May
2 months ago

Braunson left a reply on Injecting Bugsnag In Queuefailed

Just a thought, why not use the event illuminate.queue.failed and create a listener to log this. The parameters provided are $connection, $job, $data.

As for your error, you have too many params according to the error in your closure it's providing one, you expect two (JobFailed, Bugsnag).

Queue::failing(function (JobFailed $event) {
            // $event->connectionName
            // $event->job
            // $event->exception
        });
08 May
3 months ago

Braunson left a reply on Event Listener With Popup Notification?

@splendidkeen @princeoo7

Using the package I linked above: Laravel Websockets https://docs.beyondco.de/laravel-websockets/1.0/basic-usage/pusher.html as your pusher replacement

Also you can use this tutorial to give you an idea of what to do https://www.youtube.com/watch?v=i6Rdkv-DLwk in order to build real time user notifications with Laravel Echo (which you'll use with the above package)

03 May
3 months ago

Braunson left a reply on Any Recommendation For Text Editor With Image Uploads?

This is what your looking for https://alex-d.github.io/Trumbowyg/ with this plugin https://alex-d.github.io/Trumbowyg/demos/#plugins-upload

Then you would set the upload endpoint in Laravel so it could be S3/DO whatever you want from there at the server endpoint.

If you want just an uploader.. Uppy is great and supports multiple providers which looks awesome https://uppy.io/ - I plan on seeing if I can integrate Uppy with Trumbowyg in the future.

Braunson left a reply on Multiple Variants Of Same App...how To Manage

I suggest checking out Git Submodules or even think about modularizing your app from a code level.

You have some options:

  1. Have two separate apps running with two different code bases
  2. Have two separate apps running with the same code base but with different "enabled modules"
  3. Run both apps together with different "modules enabled"

I've been thinking about this same thing and I think making things into modules in Laravel and making use of Git Submodules to manage the shared submodules is the best way to manage the code. I guess it depends how much is similiar between the two projects.

Braunson left a reply on Event Listener With Popup Notification?

I think you would be better off either using native web push notifications OR using something like Pusher or the alternatives Laravel Websockets for this and then you can push real-time to specific channels.

Again if your just doing all this for one popup and only ever one, the top two may be overkill.

If you want to do it using your example, the easiest method is setting a a notification table, where you set the message to the user, and on page load, you have a partial that checks for any new notifications (provided in a global view composer) and if there are show them the user and mark them as read, so the next page load they don't appear again.

In the backend you'd trigger an event (i.e. PostApproved) and a listener would be like .. NotifySubmitterOfApproval and in that listener you would create a new notifications table entry for that user.

Personally if I'm going to be using more than just one notification, I'd make use of webpush/sockets ;-)

Braunson left a reply on Perfectly Smooth Looped Eased Css Animation

I think this is what you want.. check this out http://codepen.io/empreintes/pen/jyWQym

Other solutions for what you want at https://stackoverflow.com/q/41587802/610880

Braunson left a reply on Route::getRoutes() Returns Only Package Routes

I don't think there's an easy way to specify a package and get the routes but you can sort by controller using a slightly modified code snippet from here..

$userRoutesArray = [];
$lookFor = 'UserController';
foreach (\Route::getRoutes() as $value) {
    $controller = $value->getAction();

    if (! isset($controller['controller'])) {
        continue;
    }

    if (strpos($controller['controller'], $lookFor)) {
        array_push($userRoutesArray, $value->uri());
    }
}

dd($userRoutesArray);

If you wanted to get all routes from t he app, you could run this snippet:

$routes = collect(\Route::getRoutes())->map(function ($route) { 
    return $route->uri(); 
});

dd($routes);

Braunson left a reply on Create Account When User Registers

If you check in the Spark code, it shows the above but also where it appends the user who registered as the owner to the team.

If you have access to the repo https://github.com/laravel/spark-aurelius/blob/23107d494edb3165fd80b27c04f83528e4537c53/src/Interactions/Settings/Teams/CreateTeam.php#L72-L84

If you do not.. this is the code. You can see on the Spark::interact(AddTeamMemberContract part it adds the user to the team ;-)

    public function handle($user, array $data)
    {
        event(new TeamCreated($team = Spark::interact(
            TeamRepository::class.'@create', [$user, $data]
        )));

        Spark::interact(AddTeamMemberContract::class, [
            $team, $user, 'owner'
        ]);
        
        event(new TeamOwnerAdded($team, $user);

        return $team;
    }

So I'm not sure why your looking to change the Spark registration process as it already creates the team and adds the user registered as the owner already on register?

01 May
3 months ago

Braunson left a reply on Trying To Get Property Of Non-object

Try dumping out $print via dd inside your foreach loop to see what's available or what is being returned. See if duedate is in the array. Make sure duedate is hot hidden in the Model also.

30 Apr
3 months ago

Braunson left a reply on How To Process Mail Send Issues?

Typically this depends on what provider your using. If your using something like MailGun, you would setup a webhook, and have it record any webhook calls for "failed" or the like for those reasons.

If your using plain PHP's mail method, it just literally sends an email regardless and return true/false without any explanation. You'd have to dig into your server's mail logs (if any) and it may give you reasons why, but not always.

So your best bet at this point is using a third party like MailGun or SendMail and setting up Webhooks for these success/failed/dropped/bounced events and use the message id to track them.

Braunson left a reply on Laravel Telescope System Requirements

Try increasing your PHP's memory_limit.

There's an Issue thread for composer here https://github.com/composer/composer/issues/945 with some other debug steps/solutions to try which may help.

26 Apr
3 months ago

Braunson left a reply on Doing Something Before Delete In Eloquent Models Even In Mass Deleting

You can override deleting event in the Model's boot method OR you can use an observer to observe the deleting event and do the image deletion there before the Product finishes deleting.

An example of the first thing I suggested is:

    public static function boot()
    {
        parent::boot();

        static::deleting(function($team) {

            // Delete your photo here

        });
    }

I'd suggest creating an event listener / observer instead tho it's a bit cleaner especially when you have more and more logic.

25 Apr
3 months ago

Braunson left a reply on How To Sort Posts By Latest Commented

@memele Whoops, here you are

$latestComments = Post::with('comments')->get()->sortByDesc('comments.created_at');

We sort using Collection helpers after getting the results :)

Braunson left a reply on Validation On Required_if

I'm not entirely sure what your trying to do. If you want to (on the Update Form Request) only require the banner field when it's filled out then you would likely use the sometimes validation method.

https://laravel.com/docs/5.8/validation#conditionally-adding-rules

In some situations, you may wish to run validation checks against a field only if that field is present in the input array. To quickly accomplish this, add the sometimes rule to your rule list:

i.e

'banner' => 'sometimes|required|mimes:jpeg,png|dimensions:width=1920,height=1080',

Braunson left a reply on (1/1) FatalErrorException Maximum Execution Time Of 60 Seconds Exceeded

Looks like if the file is large it's taking too long to load it.

In this case I'd suggest offloading this type of large operation to the queue system and queue it.

Alternatively you could batch loop and batch insert the data (instead of one by one) which may speed up the script but again all depends on the file size and contents it has to go through, your best bet is to queue this up.

Braunson left a reply on Logging Raw Data

This is the function of the logger. I don't think there's an easy way to disable timestamps other than to create your own Logger/driver.

https://laravel.com/docs/5.8/logging

Braunson left a reply on How To Sort Posts By Latest Commented

Try something like this..

$latestComments = Post::with('comments')->orderBy('comments.created_at', 'desc')->get();
24 Apr
3 months ago

Braunson left a reply on Achieve Available Venue On That Date.

Hmm you are checking for Venues with bookings between your start and end date.

What about using whereNotBetween

$availableVenue = Venue::with(['bookings' => function ($query) use ($startDate, $endDate) {
    $query->whereNotBetween('startDate', [$startDate, $endDate])
            ->whereNotBetween('endDate', [$startDate, $endDate]);
}])->get();

dd($availableVenue);

There's likely a more ideal way to do this but it should work...

Braunson left a reply on How To Validate URL Query Parameters?

Look into using Form Requests to validate your inbound form requests before you need to do any logic.

https://laravel.com/docs/5.8/validation

Braunson left a reply on Swift_IoException Unable To Open File For Reading [1]

Sounds like your path to the file is wrong. Does it say which line? Perhaps it's the first one, are you referencing an existing file somewhere in SalesregisterExport?

Have you confirmed permissions are correct (so it can create a file)?

Braunson left a reply on Scheduling Sending Multiple Queued Mails

Can you confirm your server has mail enabled/installed? Try adding this in a php file and running it to test mail.

<?php
$sender = '[email protected]'; // Update this
$recipient = '[email protected]'; // Update this

$subject = "php mail test";
$message = "php test message";
$headers = 'From:' . $sender;

if (mail($recipient, $subject, $message, $headers))
{
    echo "Message accepted";
}
else
{
    echo "Error: Message not accepted";
}
?>

If that works and you get an email let us know, otherwise it may be you have to enable/fix mail on your local server first before you'll receive anything.

Additionally if mail is enabled and working properly elsewhere, do you have any errors in your log? Have you tried changing your .env file MAIL_DRIVER to log? If it's logging them it's likely a mail related issue.

Braunson left a reply on How Do I Implement An Interface Onto A Laravel Project Properly?

From what I understand, it's not possible to pass the route variable to the Controller's constructor. However there are other methods.. such as getting the Route::current()->parameter('accountType') and then setting it in the constructor but you wouldn't inject the dependency tho necessarily.

For example:

public function __construct(AccountTypeInterface $accountType)
{
    $accountType = \Route::current()->parameter('accountType');
    $this->accountType = $accountType->where('slug', $accountType)->first();
}

You may be able to use the request() help also instead of route()/Route:: This is untested but may be a possible solution.. no it's not ideal but it may work.

FWIW: There was a proposal in the Laravel framework repo for this same feature at https://github.com/laravel/framework/issues/1025 it was rejected :(

23 Apr
3 months ago

Braunson left a reply on Validation On Required_if

Have you tried using the required_unless rule?

The field under validation must be present and not empty unless the anotherfield field is equal to any value.

'fee' => 'required',
'amount' => 'bail|required_unless:fee,=,2|integer|gte:1',

bail = Stop running validation rules after the first validation failure.

So it'll try and validate required_unless, but if that fails then it'll bail.

Braunson left a reply on Best Way To Tackle This App? Ideas Welcome

Welcome! Ok so there are couple ways you can do this but since it's super simple, you can literally use a flag like you mentioned on the users table.

A user registers and by default is a Client.

You don't necessarily have to have a flag to specify client/admin just admin. This way by default all users are clients. You'd have to manually (at least for the first user) update their to have the is_admin flag set to true/1.

So you'll have 1 users table, with an additional flag called is_admin set to 0 by default. This way you can use the auth/register system that comes with Laravel.

Now for checking if they are an admin or not.. you can create a custom Blade Directive for use in Blade Views (see the Laravel docs about creating directives) and you would add the helper on the User.php model (which you'd also use to check in the blade directive). Let me give you the code..

User.php (the model, place in the class)

/**
 * A helper to determine if the current user is an admin
 */
public function isAdmin()
{
    return $this->is_admin;
}

AppServiceProvider.php (put this code inside boot() method

/**
 * If statement check if user is an admin
 *
 * Usage: @admin yep they are an admin @admin
 */
Blade::if('admin', function() {
    return auth()->check() && auth()->user()->isAdmin();
});

Now you can use the directive in your views like this..

@admin
This is text for the admin
@endadmin

And you can use the helper method in the code/middleware on a user like so:

if ($user->isAdmin()) {
    // Do admin stuff
}

If you wanted, you could create a helper and directive to return bool if they are a client.. like so..

User.php (the model, place in the class)

/**
 * A helper to determine if the current user is a client
 */
public function isClient()
{
    return ! $this->is_admin;
}

AppServiceProvider.php (put this code inside boot() method

/**
 * If statement check if user is an admin
 *
 * Usage: @admin yep they are an admin @admin
 */
Blade::if('client', function() {
    return auth()->check() && auth()->user()->isClient();
});

Hope this helps!

An example middleware for checking if admin is this..

app/Http/Middleware/CheckAdmin.php

<?php

namespace App\Http\Middleware;

use Closure;

class CheckAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {        
        // Is there current user an admin
        if ($request->user()->isAdmin()) {
            return $next($request);
        }

        return response('Unauthorized.', 401);
    }
}

Don't forget to register the middleware in your app\Http\Middleware\Kernel.php file and use it wherever needed

Braunson left a reply on How Can I Get Data From Database?

Hmm not entirely sure what your having issues with as you don't specifically explain. You should be able to access the variable $totalMarks in your blade view and use it?

Braunson left a reply on How Can I Get Chunked Value From Nested Eloquent Collection

I'm not sure how products relate to brands (assuming it's by brand_id on products) so something along the lines of ..

$brands->groupBy('products.brand_id')`

Braunson left a reply on What Is Your Laravel Design Pattern?

In existing projects you'll have to plan a way to move things part by part or module by module. It'll be tedious in an existing project, especially when it's a larger project.

A good Laracasts series is https://laracasts.com/series/solid-principles-in-php if your looking to learn more SOLID principles in PHP.

I'd suggest if you are trying to use SOLID to stick to it as much as possible but no code is perfect and you'll likely not be able to stick to it 100% for every piece of code so don't sweat the small things ;-)

18 Apr
4 months ago

Braunson left a reply on How Do I Get All Users On A Team With A Specific Role?

Something like this.. at least for Spark.. we query the pivot table team_users

$users = User::whereHas('teams', function($query) {
    $query->where('team_users.role', '=', 'professional');
})->distinct()->get();
17 Apr
4 months ago

Braunson left a reply on How To Access DB As A Class Instance?

Sure you can conditionally build a query with the DB facade.

An example:

$results = DB::table('orders')
    ->where('branch_id', Auth::user()->branch_id)
    ->when($request->customer_id, function($query) use ($request){
        return $query->where('customer_id', $request->customer_id);
    })
    ->get();

Checkout this article https://themsaid.com/laravel-query-conditions-20160425/

10 Apr
4 months ago

Braunson left a reply on Using Laravel Cashier How Can I Access User's Subscribed Plan?

While I'm not sure what version of Cashier your using, if you take a look at the repo and check the Billable.php file you'll see a relation to Subscriptions.

https://github.com/laravel/cashier/blob/9.0/src/Billable.php#L210

So you can check a user's $user->subscriptions()

Additionally you can check a user's subscription status for a specific plan like so:

if ($user->subscribed('default')) {
    //
}

Braunson started a new conversation Inconsistency Of Post Timeline Data On Profile

I noticed the timeline posts on a user's profile are cached/stored separately to the updated post?

i.e. https://laracasts.com/@Braunson

I posted an initial response to someone with a broken link (I mis-formatted it) but edited the post and fixed it. When I go to my profile, I still see the previous post.

Perhaps it's queued and hasn't updated but just an inconsistency of same-data I noticed.

Braunson left a reply on I Need Structural Advices For A Complex Logic To Create A Calendar With Events

You'll want to create "filtering" classes to filter inbound data as well as outbound data (if you need to). I'd suggest checking out the spatie/laravel-fractal package for doing this.

This will help take input from your third party and filter and format it to something you can use to insert into models, insert into events, etc.

Now you can use Controllers, Events, Queues normally without the bloated logic to process the raw data.

An examaple of incoming raw data flow/path..

API IN -> Raw Data -> Controller -> Fractal -> (back to) Controller -> Create Calendar + Events