DonSchoeman

DonSchoeman

Member Since 4 Years Ago

Experience Points
10,255
Total
Experience

4,745 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
112
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start-engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-session Created with Sketch.

    School In Session

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

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

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

  • subscriber-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist Created with Sketch.

    Laracasts Evangelist

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

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

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

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

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

Level 3
10,255 XP
Feb
28
1 year ago
Activity icon

Started a new conversation How To Provide Custom Facade Alias For Artisan Console Script?

I am receiving a naming conflict Cannot declare class Event, because the name is already in use for the Event class when installing the pecl-event extension for PHP and then trying to use the php artisan console command. Is there a way to specify a facade alias specifically when using the php artisan command?

PS: Note that I am not using Facades in my project itself and don't want to either.

Mar
15
2 years ago
Activity icon

Started a new conversation Now That Laravel 5.4 No Longer Support 'kernel.handled' Events, What Do We Do In Lumen?

Some popular libraries such as barryvdh/laravel-cors requires HTTP headers being added after a request have been handled. It does it in the following way so it works both in Laravel and Lumen:

if (class_exists(RequestHandled::class)) {
    $this->events->listen(RequestHandled::class, function(RequestHandled $event) use ($cors) {
        $cors->addActualRequestHeaders($event->response, $event->request);
    });
} else {
    $this->events->listen('kernel.handled', function($request, $response) use ($cors) {
        $cors->addActualRequestHeaders($response, $request);
    });
}

The problem is that Laravel no longer seems to supports the listen('kernel.handled'... way of listening to events. What are Lumen developers suppose to do as the RequestHandled class form part of the Foundation classes in Laravel and is not available in Lumen, so now there doesn't seem to be a way to add this type of event listener any more, or am I missing something?

Nov
10
2 years ago
Activity icon

Replied to Lumen 5.2 Mail Not Working

I'd like to add something for if you got this working according to the instructions in this thread but you don't want to use Facades. You can replace all your: Mail:: references with app('mailer')->

For example, instead of:

$recipients = ['[email protected]'];
Mail::raw('This is a test message.', function ($message) use ($recipients) {
    $message->subject('This is a test to see if emails are working');
    $message->to($recipients);
});

You can do this:

$recipients = ['[email protected]com'];
app('mailer')->raw('This is a test message.', function ($message) use ($recipients) {
    $message->subject('This is a test to see if emails are working');
    $message->to($recipients);
});

Also, to make it a little cleaner you can add the following to your helpers.php (if you don't have one create one and then load it in your bootstrap/app.php:

if (! function_exists('mailer')) {
    /**
     * Returns the application mailer instance.
     *
     * @return \Illuminate\Mail\Mailer
     */
    function mailer()
    {
        return app('mailer');
    }
}

You can then call the mail functions like this:

$recipients = ['[email protected]'];
mailer()->raw('This is a test message.', function ($message) use ($recipients) {
    $message->subject('This is a test to see if emails are working');
    $message->to($recipients);
});
Nov
08
2 years ago
Activity icon

Started a new conversation How Environment Variables Can Screw You Around For Hours And How To Fix It

This is a tip for myself in the future and others who run into the same problem I did with environment variables, in this case the APP_ENV and APP_DEBUG settings. I should have picked up the reason for this problem much faster but being exhausted this kind of problem can easily lead you to spend way too much time trying to figure out what is going on.

So the issue can happen if you are running the following development environment:

  1. Using Homestead Box and Vagrant
  2. Using Laravel or Lumen

The issue: Making changes to APP_ENV and APP_DEBUG in your .env file have no effect. Making changes to other settings work, only those two doesn't. To test, ssh into your Homestead box and type env at the terminal. If you see the APP_ENV and APP_DEBUG variables listed you have the same problem I did.

Fixing the issue: You probably have the environment variables configured in your Homestead.yaml file. To fix it, edit your /home/yourname/.homestead/Homestead.yaml file and look for the following lines:

variables:
    - key: 'APP_ENV'
      value: 'local'
    - key: 'APP_DEBUG'
      value: 'true'

comment them out so it looks like this:

# variables:
#    - key: 'APP_ENV'
#      value: 'local'
#    - key: 'APP_DEBUG'
#      value: 'true'

Now reload the settings by running the following command from your Homestead directory in your home folder: vagrant reload --provision. This will stop the environment variables being injected into the Homestead vm when it boots up.

After doing that, ssh into your Homestead box, go to your project's directory and run: php artisan config:clear (Note that this command is not available for Lumen)

This should work and you should now be able to change the APP_ENV and APP_DEBUG settings and the changes will reflect when you run your app (remember to run php artisan config:clear each time you modify your .env file).

Oct
07
3 years ago
Activity icon

Replied to Question Regarding Task Scheduling And Long Running Tasks.

@AndrewMack: Thanks Andrew, I don't know how I missed that part of the docs, appreciated your help. @ZetecVan: Thanks, I'm going to try the standard method first. I would have gone for similar solution as yours if Laravel did not already have support for that.

Activity icon

Started a new conversation Question Regarding Task Scheduling And Long Running Tasks.

If I have tasks that was setup to run every minute and for some reason the task ends up running longer than a minute, will the same task be executed again even if the previous instance have not finished executing? If so, have any of you guys found an elegant solution around this problem?

Mar
24
3 years ago
Activity icon

Started a new conversation Extending A Model's Facade.

Is there a way to add additional methods to the facades of all my models?

I basically want to add a selectOrFail() method that works similar to findOrFail() that you get on the facade's of each eloquent model. As an example, instead of calling User::findOrFail() I'd be calling my own method called User::selectOrFail(). The seletOrFail() method must be available for all other model's too, not just the User model.

The reason for this question is that I have some models that are built using complex queries, these models will implement their own selectOrFail() methods. So when I call User::selectOrFail() it will call the model's custom/extended selectOrFail() method and return with an instance of the model, or a collection or even a DB QueryBuilder instance if needed.

Feb
26
3 years ago
Activity icon

Replied to How Do I Install The Dom Extension For PHP7?

Thanks guys, it turns out that it was indeed the php-xml package, so the following solved the problem:

sudo apt-get install php-xml

I am using Ubuntu 14.04 in case anyone else also runs into this problem.

Activity icon

Started a new conversation How Do I Install The Dom Extension For PHP7?

I am trying to do a composer install for a laravel project on a staging server of ours but the composer dependency check fails at phpunit stating that it requires the ext-dom extension. I can find no information on how to install or enable the dom extension for PHP7. I compared the list of extensions installed on the server vs a Homestead box but I can't find anything obvious. Can anyone tell me which extension to install in order to resolve the missing dependency?

Feb
16
3 years ago
Activity icon

Replied to Unit Testing And Helper Functions Problem

This is indeed an upgraded project but the error definitely does not originate from compiled.php as I don't have one yet. Here is the error I get from phpunit:

PHP Fatal error:  Cannot redeclare response() (previously declared in /home/vagrant/projects/acms/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php:550) in /home/vagrant/projects/acms/app/Http/helpers.php on line 22
PHP Stack trace:
PHP   1. {main}() /home/vagrant/projects/acms/vendor/phpunit/phpunit/phpunit:0
PHP   2. PHPUnit_TextUI_Command::main() /home/vagrant/projects/acms/vendor/phpunit/phpunit/phpunit:47
PHP   3. PHPUnit_TextUI_Command->run() /home/vagrant/projects/acms/vendor/phpunit/phpunit/src/TextUI/Command.php:100
PHP   4. PHPUnit_TextUI_Command->handleArguments() /home/vagrant/projects/acms/vendor/phpunit/phpunit/src/TextUI/Command.php:111
PHP   5. PHPUnit_TextUI_Command->handleBootstrap() /home/vagrant/projects/acms/vendor/phpunit/phpunit/src/TextUI/Command.php:596
PHP   6. PHPUnit_Util_Fileloader::checkAndLoad() /home/vagrant/projects/acms/vendor/phpunit/phpunit/src/TextUI/Command.php:779
PHP   7. PHPUnit_Util_Fileloader::load() /home/vagrant/projects/acms/vendor/phpunit/phpunit/src/Util/Fileloader.php:38

Fatal error: Cannot redeclare response() (previously declared in /home/vagrant/projects/acms/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php:550) in /home/vagrant/projects/acms/app/Http/helpers.php on line 22

Call Stack:
    0.0001     356008   1. {main}() /home/vagrant/projects/acms/vendor/phpunit/phpunit/phpunit:0
    0.0110    1429480   2. PHPUnit_TextUI_Command::main() /home/vagrant/projects/acms/vendor/phpunit/phpunit/phpunit:47
    0.0110    1429592   3. PHPUnit_TextUI_Command->run() /home/vagrant/projects/acms/vendor/phpunit/phpunit/src/TextUI/Command.php:100
    0.0110    1429592   4. PHPUnit_TextUI_Command->handleArguments() /home/vagrant/projects/acms/vendor/phpunit/phpunit/src/TextUI/Command.php:111
    0.0135    1875176   5. PHPUnit_TextUI_Command->handleBootstrap() /home/vagrant/projects/acms/vendor/phpunit/phpunit/src/TextUI/Command.php:596
    0.0136    1880584   6. PHPUnit_Util_Fileloader::checkAndLoad() /home/vagrant/projects/acms/vendor/phpunit/phpunit/src/TextUI/Command.php:779
    0.0145    1880664   7. PHPUnit_Util_Fileloader::load() /home/vagrant/projects/acms/vendor/phpunit/phpunit/src/Util/Fileloader.php:38


Variables in local scope (#7):
  $filename = '/home/vagrant/projects/acms/app/Http/helpers.php'
  $newVariableNames = *uninitialized*
  $newVariables = *uninitialized*
  $oldVariableNames = array (0 => 'filename')
  $variableName = *uninitialized*

To be honest I think that this is a bug in Laravel, I'll see if I have the time to start a new project and see if it has the same problem, if it does I'm definitely submitting it as a bug.

Activity icon

Replied to Unit Testing And Helper Functions Problem

Here is the content of the files:

phpunit.xml

<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         bootstrap="bootstrap/autoload.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false">
    <testsuites>
        <testsuite name="Application Test Suite">
            <directory>./tests/</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist>
            <directory suffix=".php">app/</directory>
        </whitelist>
    </filter>
    <php>
        <env name="APP_ENV" value="testing"/>
        <env name="CACHE_DRIVER" value="array"/>
        <env name="SESSION_DRIVER" value="array"/>
        <env name="QUEUE_DRIVER" value="sync"/>
    </php>
</phpunit>

bootstrap/autoload.php

<?php

define('LARAVEL_START', microtime(true));

/*
|--------------------------------------------------------------------------
| Register The Composer Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader
| for our application. We just need to utilize it! We'll require it
| into the script here so that we do not have to worry about the
| loading of any our classes "manually". Feels great to relax.
|
*/

require __DIR__.'/../app/Http/helpers.php';
require __DIR__.'/../vendor/autoload.php';

/*
|--------------------------------------------------------------------------
| Include The Compiled Class File
|--------------------------------------------------------------------------
|
| To dramatically increase your application's performance, you may use a
| compiled class file which contains all of the classes commonly used
| by a request. The Artisan "optimize" is used to create this file.
|
*/

$compiledPath = __DIR__.'/cache/compiled.php';

if (file_exists($compiledPath)) {
    require $compiledPath;
}

Http/helpers.php

<?php

/**
 * @param  string $content
 * @param  int    $status
 * @param  array  $headers
 *
 * @return \App\Http\JsonResponse
 */
function response($content = '', $status = 200, array $headers = [])
{
    $factory = app('App\Http\ResponseFactory');

    if (func_num_args() === 0) {
        return $factory;
    }

    return $factory->make($content, $status, $headers);
}

To reiterate, during normal execution this works fine, but during testing our bootstrap code is only loaded after Laravel have started instead of before, which then causes a conflict with the name of our response() function.

Activity icon

Started a new conversation Unit Testing And Helper Functions Problem

We require our own response() helper function to be loaded before Laravel starts up. This is done through the usual way of declaring the response() function in app/Http/helpers.php and then loading that file in the bootstrap/autoload.php file using:

require __DIR__.'/../app/Http/helpers.php';

This works fine but fails when we attempt to run tests as Laravel starts up and loads its own helpers.php before loading our helpers.php file which then ends up causes the error:

PHP Fatal error:  Cannot redeclare response()

The fact that the bootstrap/autoload.php is specified in the phpunit.xml to be bootstrapped doesn't make a difference and neither does bootstrapping the file in the command line, e.g.:

vendor/bin/phpunit --bootstrap 'bootstrap/autoload.php'

So now we either need to rename our own response() helper function or find a way to get our helper file to be loaded before Laravel's. This seems to be a potential bug or missing feature because surely you should be able to have your own code bootstrapped for testing just as you would during production. Can anyone help me with this issue?

Dec
08
3 years ago
Activity icon

Replied to Custom HTTP Response Codes And Status Text.

Please note that I made some changes to my own correct answer in the JsonResponse class and to copy and paste that source code instead of the source code from the "correct answer".

Dec
03
3 years ago
Activity icon

Replied to Custom HTTP Response Codes And Status Text.

Ok, I finally did it and here is how the future reader (you) can do it too. Since nobody responded to my original request I'm assuming it might be the only way to do it for now:

  1. Edit bootstrap/autoload.php and add the following:
require __DIR__.'/../app/Http/helpers.php';  // Add this line
require __DIR__.'/../vendor/autoload.php';
  1. Create a new file called: app/Http/helpers.php and add the following code:
<?php

/**
 * We supply our own instance of the response in order to load
 * our own response class when the response() helper is called.
 *
 * @param  string $content
 * @param  int    $status
 * @param  array  $headers
 *
 * @return \App\Http\JsonResponse
 */
function response($content = '', $status = 200, array $headers = [])
{
    $factory = app('App\Http\ResponseFactory');

    if (func_num_args() === 0) {
        return $factory;
    }

    return $factory->make($content, $status, $headers);
}

The above code basically declares the response() function so that when laravel's own helpers are created directly afterwards it will not declare a new one but use ours instead.

  1. Create a new file called: app/Http/ResponseFactory.php and add the following code:
<?php

namespace App\Http;

use JsonSerializable;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Routing\ResponseFactory as BaseFactory;

class ResponseFactory extends BaseFactory
{
    /**
     * Return a new JSON response from the application.
     *
     * @param  string|array  $data
     * @param  int  $status
     * @param  array  $headers
     * @param  int  $options
     * @return \App\Http\JsonResponse
     */
    public function json($data = [], $status = 200, array $headers = [], $options = 0)
    {
        if ($data instanceof Arrayable && ! $data instanceof JsonSerializable) {
            $data = $data->toArray();
        }

        return new JsonResponse($data, $status, $headers, $options);
    }
}

Here we declare our own factory that will return our own JsonResponse instance when used. The JsonResponse class is created next...

  1. Create a new file called: app/Http/JsonResponse.php and add the following code:
<?php

namespace App\Http;

use Illuminate\Http\JsonResponse as BaseResponse;

class JsonResponse extends BaseResponse
{
    const HTTP_AUTHENTICATION_TIMEOUT = 419;
    const HTTP_USER_NOT_FOUND = 425;
    const HTTP_TOKEN_INVALID = 498;
    const HTTP_TOKEN_REQUIRED = 499;

    public static $statusTexts = [
        419 => 'Authentication Timeout',
        425 => 'User Not Found',
        498 => 'Token Invalid',
        499 => 'Token Required'
    ];

    /**
     * Sets the response status code.
     *
     * @param int   $code HTTP status code
     * @param mixed $text HTTP status text
     *
     * If the status text is null it will be automatically populated for the known
     * status codes and left empty otherwise.
     *
     * @return Response
     *
     * @throws \InvalidArgumentException When the HTTP status code is not valid
     */
    public function setStatusCode($code, $text = null)
    {
        $this->statusCode = $code = (int) $code;
        if ($this->isInvalid()) {
            throw new \InvalidArgumentException(sprintf('The HTTP status code "%s" is not valid.', $code));
        }

        if (null === $text) {
            if (isset(self::$statusTexts[$code])) {
                $this->statusText = self::$statusTexts[$code];
            } else if (isset(parent::$statusTexts[$code])) {
                $this->statusText = parent::$statusTexts[$code];
            } else {
                $this->statusText = 'Unknown Status';
            }
            return $this;
        }

        if (false === $text) {
            $this->statusText = '';
            return $this;
        }

        $this->statusText = $text;

        return $this;
    }
}

This file overrides the Illuminate\Http\JsonResponse class which in turn overrides the Symfony\Component\HttpFoundation\JsonResponse class. We need to append our own response codes and status texts here, as an example I have added code 499 Token Required and a few others but you can add more or replace them. We then have to also override the setStatusCode() method so that we can check our own array as well as that of the parent class.

  1. Finally, to return a JSON response with you own new code you can do the following in your controller:
return response()->json(['foo' => 'bar'], 499);

I hope this helps anyone in the same situation as I am.

Dec
02
3 years ago
Activity icon

Replied to Custom HTTP Response Codes And Status Text.

Since my post was made I noticed that I'm setting the Response facade to point directly to my Response class which is obviously not correct since my Response class isn't in fact a Facade, so I changed it back to the default Response Facade.

I am now trying to implement a replacement response() function in my own autoloader.php with which I intend to return an instance of my own Response class but I have yet to figure out how I am going to do that as I don't know how to get the ResponseFactory contract to "know" about my Response class. I'm obviously missing something still...

Activity icon

Started a new conversation Custom HTTP Response Codes And Status Text.

I am trying to return custom HTTP response codes and status text for my REST API. To do this I thought it might be best to extend Illuminate\Http\Response with my own Response and then add the additional response codes and status text I require, for example:

<?php

namespace App\Http;

use Illuminate\Http\Response as BaseResponse;

class Response extends BaseResponse
{
    const HTTP_TOKEN_REQUIRED = 499;

    public static $statusTexts = [
        499 => 'Token Required'
    ];

    /**
     * Constructor.
     *
     * @param mixed $content The response content, see setContent()
     * @param int   $status  The response status code
     * @param array $headers An array of response headers
     *
     * @throws \InvalidArgumentException When the HTTP status code is not valid
     */
    public function __construct($content = '', $status = 200, $headers = array())
    {
        $this::$statusTexts = parent::$statusTexts + $this::$statusTexts;

        parent::__construct($content, $status, $headers);
    }
}

and then to obviously replace the Facade config in app.php to use my own, e.g.:

'Response'   => App\Http\Response::class

However, how do I now get the response() helper function to make an instance of my class instead of the default and is this even the right way to approach the problem in the first place?

Oct
30
3 years ago
Activity icon

Replied to File Session On Top Of Homestead + NFS Is Partially Broken.

The problem is that different hardware configurations may or may not cause issues. For example, your HDD and CPU speed may determine whether you have this problem or not, and that makes the situation very hard to resolve. One could of course fix it by moving the session files to a non-shared directory on the Homestead box all together, but using a different session driver is still better a better option in my humble opinion.

Activity icon

Replied to Laracast Videos Should Really Support Annotations.

Thanks for your hard work Jeffrey. I can imagine that it is ok to produce videos on new topics, but producing videos of the same tutorials can't be that much fun. Good luck with that!

Oct
29
3 years ago
Activity icon

Started a new conversation File Session On Top Of Homestead + NFS Is Partially Broken.

Today I ran into a weird issue where session data would randomly get lost between redirects. I eventually tracked it down to using a File session driver over a shared drive between my host machine and a Homestead box. I've opted to use NFS to speed up the mapped drive so I'm not sure if this happens with the standard network mapping as well.

I think the problem is caused due to a race condition in that the new page is redirected to and requested by the browser before the session is written to file, hence the randomness of it all. Changing the session and cache driver to memcached for example solves the problem.

I'm a seasoned developer (new to Laravel though) so I was able to solve the problem within minutes, but a beginner would potentially struggle for hours or even days given the inconsistency of the problem. Is there a way that perhaps new sites generated with the laravel new command could configure the default "file" cache and session driver with memcached or redis in the .env file? If not, then the issue I think should be displayed more prominently somewhere.

Activity icon

Started a new conversation Laracast Videos Should Really Support Annotations.

In case someone haven't suggested this before... I think the Laracast videos should really support annotations (like Youtube). I'm about halfway through the Laravel 5 Fundamentals beginners tutorial but this is also where things start falling apart as there are enough differences between Laravel 5.0 and 5.1.20 to invalidate some of the examples.

I understand that it is basically impossible to make new Laracast videos for every release so if the video player supported annotations then the videos where the tutorials are slightly broken can be amended with annotations to point out the differences (even it it simple points to links where one can find out how to deal with the differences). This would save tremendous frustration and time on the developer's side as well as buying time for the Laracast's team between releases.

Oct
22
3 years ago
Activity icon

Replied to Setting Up An Additional Non Laravel Site On A Homestead Box.

Excellent, I am going to try that then, thanks guys.

Oct
21
3 years ago
Activity icon

Started a new conversation Setting Up An Additional Non Laravel Site On A Homestead Box.

We're new to Laravel and its supporting tech and started a new project using Homestead. Our Laravel project is going to be purely a REST API as we are developing our front-end independently. We would like to host our front-end html/css/javascript on the same Homestead box but on a different nginx server block. What strategy can I use to get this up and running?

I am thinking that if it is possible to simply add an additional site using the Homestead.yaml file, but I think Homestead will think it is a Laravel project under the second (front-end) site and therefore won't setup ngxinx properly.

My other plan is to perhaps use the after.sh bootstrap script to setup an additional nginx server block to host our front-end. Do you guys have any tips or advise for me? It would be greatly appreciated!