Braunson

Member Since 5 Years Ago

Ontario, Canada

Founder at Geekybeaver

Experience Points 29,165
Experience Level 6

835 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 33
Best Reply
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

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

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

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

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    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 Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

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

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

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

24 Jun
1 day 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
4 days 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
5 days 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
3 weeks 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
1 month 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
1 month 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 () 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
1 month 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
1 month 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
1 month 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.

25 Apr
2 months ago

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

@memele Whoops, here you are

$latestComments = Post::with('comments')->get()->orderByDesc('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.

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
2 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);

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
2 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) so something like..

`$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
2 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
2 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
2 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)[https://github.com/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

Braunson left a reply on Checking If File Is Done

An interesting challenge. There are a few methods to solve this. Once you have a solution below to check agianst if the file is completed or not, if not you can re-queue the job ;-)

  1. Use a signal file tthat is created before the upload and removed when completed.
  2. Get a list of all currently opened files in that dir by parsing the output of UNIX/Linuxlsof` command and check if your file is in that list (tho you may encounter permission issues with this)
  3. Some FTP managers offer a configuration option that for example gives uncompletes files the extension of .part or locks the file system level (similiar to vsftp)
  4. Check if the file's last modification of that file is longer than a specific threshold.

I'm thinking #4 is likely your best bet here.

Additionally another option if you have PECL Inotify extension installed you can make use of inotify_read and check for the event code (IN_CLOSE_WRITE)[https://www.php.net/manual/en/function.inotify-read.php#113281]

These above solutions were mainly taken from (this thread)[https://stackoverflow.com/q/9964625/610880] on SO and there are a few more options to ponder there.

Braunson left a reply on How To Conditionally Chain Queue Jobs

You can use the normal job chaining..

ProcessDownload::withChain([
    new SmpWorkbookExport($data),
    new MergeWorkSheets($data)
])->dispatch($data);

Pass an array of data needed for each job so you can do the logic calculation inside each job. If a chained job needs not to run you can do the check inside the job and either $job->delete() or return false to end the job.

If you need to pass data from one chained job to another sequentially, I don't have a solid Laravel answer but Guzzle's Promises may be an option.. check this https://stackoverflow.com/a/46801397/610880

Additionally if you need to pass data to another job in the chain, you could use something like redis/cache to temporarily store the data to pass it down the line and at the end delete/empty that cached data (cached data is set in the first queue job, cleared out in the last when it's no longer needed)

Braunson left a reply on Remove Header From Laravel Markdown Template

You will want to check out this in the docs https://laravel.com/docs/5.8/mail#customizing-the-components

  1. Publish the components
  2. Edit the templates/components/theme

Then you can edit any aspect of the markdown template you want i.e. /resources/views/text/header.blade.php

Braunson left a reply on Laravel Horizon Critical Issue

Looks like this is an ongoing issue https://github.com/laravel/horizon/issues/25 (Even with Laravel 5.8)

Braunson left a reply on How Do You Manage Models Views?

Hey there,

I think this depends on your requirements. You gave the example of increasing a view counter at every refresh. I have a use-case where each view is unique to the IP so it's a bit more complex than increasing the counter ever refresh.

In my case I need to track views for multiple models, so I created a polymorphic table called Views and I have a trait I can add to each model that gives me access to the Views relation as well as some helpers to increase views.

Inside those helpers takes care of checking against IP and logging, essentially it checks if there's been a view form the same IP to the same page in the last X mins/hours/day, if so it doesn't log the view. This can of course be changed to use a cookie (set a cookie when viewing, check for cookie if viewing again, etc) to cut down on DB calls.

Another way to do it is queue the view calls (bonus you can do logic in there). This way you don't necessarily lock the table your updating views on, i.e. if your keeping a view_counton the model in question, if two people viewed at the same time and you tried to up the count at the same time, you may run into table lock issues.

Queueing them to record (and using Laravel's increment tool) along with making sure they get called one at a time, will avoid the table lock issue, allow you a place to do some logic and offload the heavy lifting/checking to another server/queue runner.

If it's a low traffic site, you can just increment each refresh, again it depends on your requirements and preferences.

28 Mar
2 months ago

Braunson left a reply on Laravel Homestead With Apache Server

Check the docs :)

Specifically under "Adding Additional Sites > Site Type" https://laravel.com/docs/master/homestead#adding-additional-sites

Homestead supports several types of sites which allow you to easily run projects that are not based on Laravel. For example, let's add the apache type..

sites:
    - map: project.test
      to: /home/vagrant/code/my-project/web
      type: "apache"

Also check out "Web Servers" https://laravel.com/docs/master/homestead#web-servers

Homestead uses the Nginx web server by default. However, it can install Apache if apache is specified as a site type. While both web servers can be installed at the same time, they cannot both be running at the same time. The flip shell command is available to ease the process of switching between web servers. The flip command automatically determines which web server is running, shuts it off, and then starts the other server. To use this command, SSH into your Homestead machine and run the command in your terminal:

flip

;-)

20 Mar
3 months ago

Braunson left a reply on Can't Update Config File

Config::set will set the value for runtime only. It won't save it to the config file.

If you want persistent configurations take a look at Update Config on Runtime Persistently

Braunson left a reply on How Search For Multiple Words In Eloquent?

If you wanted to use space as the the delimiter.. something like this

$query = Input::get('q'); //  'john doe';

// Let's split on 1+ whitespace & ignore empty (eg. trailing space)
$searchValues = preg_split('/\s+/', $query, -1, PREG_SPLIT_NO_EMPTY); 

$deviceInspections  = DeviceInspection::whereHas('sale', function ($query) use ($searchValues) {
    foreach ($searchValues as $value) {
        $query->orWhere('sale_number', 'like', "%{$value}%");
    }
})->paginate(20);