JamesFreeman

JamesFreeman

Member Since 4 Years Ago

::1

Experience Points 43,820
Experience Level 9

1,180 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 440
Lessons
Completed
Best Reply Awards 1
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.

15 Jul
2 months ago

JamesFreeman left a reply on Mocking 3rd Party Classes Within Singleton

I do agree this is at a low level, I wouldn't normally go down this far, but it's for a service integration which has an expected input, It'll be nice to know moving forward that it is getting the parameters it needs.

I did think about doing that, unfortunately, it's on a 3rd party class so I can't create those methods on the class, I'm thinking I could potentially extend the base class and add those methods on.

What do you think?

JamesFreeman left a reply on Mocking 3rd Party Classes Within Singleton

Hi Martin, Thanks for the reply.

I'm trying to test that TwitterOAuth is receiving certain config values from this singleton.

$this->app->singleton(TwitterOAuth::class, function () {
    return new TwitterOAuth(
        config('twitter.consumer_key'),
        config('twitter.consumer_secret'),
        config('twitter.oauth_key'),
        config('twitter.oauth_secret')
    );
});

I could imagine that the test would look something like this:

function test_take_it_gets_the_correct_params()
{
    $mock = Mockery::mock(TwitterOAuth::class);
    
    config('twitter.consumer_key', 'A');
    config('twitter.consumer_secret', 'B');
    config('twitter.oauth_key', 'C');
    config('twitter.oauth_secret', 'D');
    
    $mock->shouldRecieve('__construct')->once()->with('A', 'B', 'C', 'D');
    
    $this->artisan('app:load-tweets');
}

JamesFreeman started a new conversation Mocking 3rd Party Classes Within Singleton

I'm looking to test that TwitterOAuth is initiated with the correct config information, I have attached the code I have at the moment. Is it possible to dependency inject within the singleton call?

Anyone have an ideas on how I can complete this task?

TwitterServiceProvider

<?php

namespace App\Services\Twitter;

use Abraham\TwitterOAuth\TwitterOAuth;
use Illuminate\Support\ServiceProvider;

class TwitterServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton(TwitterOAuth::class, function () {
            return new TwitterOAuth(
                config('twitter.consumer_key'),
                config('twitter.consumer_secret'),
                config('twitter.oauth_key'),
                config('twitter.oauth_secret')
            );
        });

        $this->app->singleton(Twitter::class, function(){
            return new Twitter($this->app->make(TwitterOAuth::class));
        });
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
}

TwitterCommandTest

<?php


namespace Tests\App\Commands;

use Mockery;
use Tests\App\TestCase;
use App\Services\Twitter\Twitter;
use Illuminate\Support\Facades\Cache;

/**
 * @runTestsInSeparateProcesses
 * @preserveGlobalState disabled
 */
class TwitterCommandTest extends TestCase
{
    /**
     * @test
     */
    public function test_tweets_should_be_cached()
    {
        $this->instance(Twitter::class, Mockery::mock(Twitter::class, function ($mock) {
            $mock->shouldReceive('get')->once()->andReturn('[1,2,3]');
        }));

        $this->artisan('app:load-tweets');

        $this->assertSame(Cache::get('twitter.cache'), '[1,2,3]');
    }
}

LoadTweets

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Services\Twitter\Twitter;
use Illuminate\Support\Facades\Cache;

class LoadTweets extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:load-tweets';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';


    protected $twitter;

    /**
     * Create a new command instance.
     *
     * @param Twitter $twitter
     */
    public function __construct(Twitter $twitter)
    {
        parent::__construct();

        $this->twitter = $twitter;
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->info('Loading Tweets');

        Cache::forever(
            'twitter.cache',
            $this->twitter->get()
        );

        $this->info('Saved Tweets');
    }
}

09 Apr
5 months ago

JamesFreeman left a reply on How To Access Laravel Site From Another Computer

@KONRMS - Yeah, either port forward your router (I would advise against this), or set up a cheap digital ocean server, and host a staging environment.

Alternatively like @mcangueiro said above, ngork is the way forward (which will handle your port forwarding securely).

JamesFreeman left a reply on Laravel 5.8 - Route Not Working { HTTPS }

Sounds likes a stupid question, but did you restart apache after the config change?

JamesFreeman left a reply on Laravel 5.8 - Route Not Working { HTTPS }

I've found this for you: https://askubuntu.com/questions/157293/i-need-a-file-etc-apache2-sites-available-default-ssl

Make sure you have installed mod_ssl aswell :)

<IfModule mod_ssl.c>
<VirtualHost _default_:443>
        ServerAdmin [email protected]

        DocumentRoot /var/www
        <Directory />
                Options FollowSymLinks
                AllowOverride None
        </Directory>
        <Directory /var/www/>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride None
                Order allow,deny
                allow from all
        </Directory>

        ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
        <Directory "/usr/lib/cgi-bin">
                AllowOverride None
                Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
                Order allow,deny
                Allow from all
        </Directory>

        ErrorLog ${APACHE_LOG_DIR}/error.log

        # Possible values include: debug, info, notice, warn, error, crit,
        # alert, emerg.
        LogLevel warn

        CustomLog ${APACHE_LOG_DIR}/ssl_access.log combined

        Alias /doc/ "/usr/share/doc/"
        <Directory "/usr/share/doc/">
                Options Indexes MultiViews FollowSymLinks
                AllowOverride None
                Order deny,allow
                Deny from all
                Allow from 127.0.0.0/255.0.0.0 ::1/128
        </Directory>

        #   SSL Engine Switch:
        #   Enable/Disable SSL for this virtual host.
        SSLEngine on

        #   A self-signed (snakeoil) certificate can be created by installing
        #   the ssl-cert package. See
        #   /usr/share/doc/apache2.2-common/README.Debian.gz for more info.
        #   If both key and certificate are stored in the same file, only the
        #   SSLCertificateFile directive is needed.
        SSLCertificateFile    /etc/ssl/certs/ssl-cert-snakeoil.pem
        SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key

        #   Server Certificate Chain:
        #   Point SSLCertificateChainFile at a file containing the
        #   concatenation of PEM encoded CA certificates which form the
        #   certificate chain for the server certificate. Alternatively
        #   the referenced file can be the same as SSLCertificateFile
        #   when the CA certificates are directly appended to the server
        #   certificate for convinience.
        #SSLCertificateChainFile /etc/apache2/ssl.crt/server-ca.crt

        #   Certificate Authority (CA):
        #   Set the CA certificate verification path where to find CA
        #   certificates for client authentication or alternatively one
        #   huge file containing all of them (file must be PEM encoded)
        #   Note: Inside SSLCACertificatePath you need hash symlinks
        #         to point to the certificate files. Use the provided
        #         Makefile to update the hash symlinks after changes.
        #SSLCACertificatePath /etc/ssl/certs/
        #SSLCACertificateFile /etc/apache2/ssl.crt/ca-bundle.crt

        #   Certificate Revocation Lists (CRL):
        #   Set the CA revocation path where to find CA CRLs for client
        #   authentication or alternatively one huge file containing all
        #   of them (file must be PEM encoded)
        #   Note: Inside SSLCARevocationPath you need hash symlinks
        #         to point to the certificate files. Use the provided
        #         Makefile to update the hash symlinks after changes.
        #SSLCARevocationPath /etc/apache2/ssl.crl/
        #SSLCARevocationFile /etc/apache2/ssl.crl/ca-bundle.crl

        #   Client Authentication (Type):
        #   Client certificate verification type and depth.  Types are
        #   none, optional, require and optional_no_ca.  Depth is a
        #   number which specifies how deeply to verify the certificate
        #   issuer chain before deciding the certificate is not valid.
        #SSLVerifyClient require
        #SSLVerifyDepth  10

        #   Access Control:
        #   With SSLRequire you can do per-directory access control based
        #   on arbitrary complex boolean expressions containing server
        #   variable checks and other lookup directives.  The syntax is a
        #   mixture between C and Perl.  See the mod_ssl documentation
        #   for more details.
        #<Location />
        #SSLRequire (    %{SSL_CIPHER} !~ m/^(EXP|NULL)/ \
        #            and %{SSL_CLIENT_S_DN_O} eq "Snake Oil, Ltd." \
        #            and %{SSL_CLIENT_S_DN_OU} in {"Staff", "CA", "Dev"} \
        #            and %{TIME_WDAY} >= 1 and %{TIME_WDAY} <= 5 \
        #            and %{TIME_HOUR} >= 8 and %{TIME_HOUR} <= 20       ) \
        #           or %{REMOTE_ADDR} =~ m/^192\.76\.162\.[0-9]+$/
        #</Location>

        #   SSL Engine Options:
        #   Set various options for the SSL engine.
        #   o FakeBasicAuth:
        #     Translate the client X.509 into a Basic Authorisation.  This means                                                                              that
        #     the standard Auth/DBMAuth methods can be used for access control.                                                                               The
        #     user name is the `one line' version of the client's X.509 certific                                                                             ate.
        #     Note that no password is obtained from the user. Every entry in th                                                                             e user
        #     file needs this password: `xxj31ZMTZzkVA'.
        #   o ExportCertData:
        #     This exports two additional environment variables: SSL_CLIENT_CERT                                                                              and
        #     SSL_SERVER_CERT. These contain the PEM-encoded certificates of the
        #     server (always existing) and the client (only existing when client
        #     authentication is used). This can be used to import the certificat                                                                             es
        #     into CGI scripts.
        #   o StdEnvVars:
        #     This exports the standard SSL/TLS related `SSL_*' environment vari                                                                             ables.
        #     Per default this exportation is switched off for performance reaso                                                                             ns,
        #     because the extraction step is an expensive operation and is usual                                                                             ly
        #     useless for serving static content. So one usually enables the
        #     exportation for CGI and SSI requests only.
        #   o StrictRequire:
        #     This denies access when "SSLRequireSSL" or "SSLRequire" applied ev                                                                             en
        #     under a "Satisfy any" situation, i.e. when it applies access is de                                                                             nied
        #     and no other module can change it.
        #   o OptRenegotiate:
        #     This enables optimized SSL connection renegotiation handling when                                                                              SSL
        #     directives are used in per-directory context.
        #SSLOptions +FakeBasicAuth +ExportCertData +StrictRequire
        <FilesMatch "\.(cgi|shtml|phtml|php)$">
                SSLOptions +StdEnvVars
        </FilesMatch>
        <Directory /usr/lib/cgi-bin>
                SSLOptions +StdEnvVars
        </Directory>

        #   SSL Protocol Adjustments:
        #   The safe and default but still SSL/TLS standard compliant shutdown
        #   approach is that mod_ssl sends the close notify alert but doesn't wa                                                                             it for
        #   the close notify alert from client. When you need a different shutdo                                                                             wn
        #   approach you can use one of the following variables:
        #   o ssl-unclean-shutdown:
        #     This forces an unclean shutdown when the connection is closed, i.e                                                                             . no
        #     SSL close notify alert is send or allowed to received.  This viola                                                                             tes
        #     the SSL/TLS standard but is needed for some brain-dead browsers. U                                                                             se
        #     this when you receive I/O errors because of the standard approach                                                                              where
        #     mod_ssl sends the close notify alert.
        #   o ssl-accurate-shutdown:
        #     This forces an accurate shutdown when the connection is closed, i.                                                                             e. a
        #     SSL close notify alert is send and mod_ssl waits for the close not                                                                             ify
        #     alert of the client. This is 100% SSL/TLS standard compliant, but                                                                              in
        #     practice often causes hanging connections with brain-dead browsers                                                                             . Use
        #     this only for browsers where you know that their SSL implementatio                                                                             n
        #     works correctly.
        #   Notice: Most problems of broken clients are also related to the HTTP
        #   keep-alive facility, so you usually additionally want to disable
        #   keep-alive for those clients, too. Use variable "nokeepalive" for th                                                                             is.
        #   Similarly, one has to force some clients to use HTTP/1.0 to workarou                                                                             nd
        #   their broken HTTP/1.1 implementation. Use variables "downgrade-1.0"                                                                              and
        #   "force-response-1.0" for this.
        BrowserMatch "MSIE [2-6]" \
                nokeepalive ssl-unclean-shutdown \
                downgrade-1.0 force-response-1.0
        # MSIE 7 and newer should be able to use keepalive
        BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown

</VirtualHost>
</IfModule>

JamesFreeman left a reply on How To Access Laravel Site From Another Computer

I have this set up in the office so that other users can get on to our developer system,

  • Don't worry about running serve with a host and port, run it like you normally would through your xampp.
  • Set up their host file with 192.168.1.101 laravel.site (make sure your internal IP hasn't changed)
  • One of the problems I have encountered is your windows firewall blocking traffic through port 80 internally, so you may have to allow xampp in your local firewall

Hope this helps :)

13 Jul
1 year ago

JamesFreeman started a new conversation Multiple Search Refinements On Controller

Hi All,

I've been working on a section of my website where a user can refine down order information, so you can easily find an order. ( https://imgur.com/a/rq5SpbI ) My problem is the controller can get rather cluttered with all the different conditions. So I built myself a "Filter" class which will dynamically filter the model by different method names.

<?php

namespace App\Http\Filters;

use App\Order;
use Illuminate\Support\Collection;

class OrdersFilter extends BaseFilter
{
    public $model = Order::class;

    public function defaultWhere()
    {
        return $this->query()->where(function ($query) {
            $query->where('archived', false)
                ->where('proforma', false);
        });
    }

    public function filterID($id)
    {
        if (!$id) return false;

        return $this->query()->where('id', $id);
    }

    public function filterCustomerName($customerName)
    {
        if (!$customerName) return false;

        return $this->query()->where(function ($query) use ($customerName) {
            $query->where('invoice_name', 'like', '%' . $customerName . '%')
                ->orWhere('delivery_name', 'like', '%' . $customerName . '%')
                ->orWhere('company', 'like', '%' . $customerName . '%');
        });
    }

    public function filterPostCode($postCode)
    {
        if (!$postCode) return false;

        return $this->query()->where(function ($query) use ($postCode) {
            $query->whereRaw('LOWER(REPLACE(delivery_postcode, " ", "")) like ? ', '%' . $postCode . '%')
                  ->orWhereRaw('LOWER(REPLACE(invoice_postcode, " ", "")) like ? ', '%' . $postCode . '%');
        });
    }

    public function filterAllOrderDateRange(Collection $input)
    {
        if($input->has('date_from') && $input->has('date_to')){
            
        }
    }
}

I was wondering if I'm going about this the wrong way. How would you get around this?

I look forward to your feedback.

02 Mar
1 year ago

JamesFreeman left a reply on How Do You Only Update Validated Inputs?

Oh right, so there is no "official" way to do this then - seems to me like people would want to do this a lot, I could be wrong tho.

Thanks for your help. :)

JamesFreeman started a new conversation How Do You Only Update Validated Inputs?

Hi All,

Is it possible to validate your request without forcing Illuminate\Validation\ValidationException to be thrown?

public function store(Request $request)
    {
        $fields = $request->validate([
            'name' => 'required',
            'email' => 'required|email',
            'telephone' => 'required',
        ]);

        return tap(Auth::user(), function($user) use($fields){
            $user->update($fields);
        });
    }

My tests are as follow:

public function testThatAValidEmailIsProvider()
    {
        $user = $this->signInJohn();

        $this->post(route('profile.info'), [
            'name' => 'Barry White',
            'email' => 'not-an-email.com',
            'telephone' => '07779 555111',
        ])->assertStatus(201);

        $user = $user->fresh();

        $this->assertEquals('Barry White', $user->name);
        $this->assertEquals('[email protected]', $user->email);
        $this->assertEquals('07779 555111', $user->telephone);

    }
12 Feb
3 years ago

JamesFreeman started a new conversation Dynamic Static Variables In Models.

Dynamic Static Variables in Models. What I really want to be able to do is access my model via a key and get back the relevant id.

For example:

ModulesPublicKeys::$defaultWhere; //should return 1.

What I thought I could potentially do is run this method in routes.php:

public static function setConsts()
{
    foreach(self::all() as $row)
    {
        self::${$row->module_key_value} = $row->module_id;
    }
}

But I get the following error:

Access to undeclared static property: App\Models\ModulesPublicKeys::$defaultWhere

What I did have was a simple method, which would go and retrieve the value from the database each time, but ofcourse this isn't ideal.

public static function getId($key = '')
        {
            return self::where('module_value', $key)->first()->module_key_id;
        }

Would love to hear some of your thoughts on how you would do this?

10 Dec
4 years ago

JamesFreeman left a reply on Dynamic Call Of Class

@arabsight I'll try that when I get home. I'm pretty new to this name spacing lark. Thanks for your help.

JamesFreeman left a reply on Dynamic Call Of Class

@arabsight that's not the issue because new Test(); works but new $name(); doesn't.

JamesFreeman left a reply on Dynamic Call Of Class

Any one have any ideas?

09 Dec
4 years ago

JamesFreeman left a reply on Dynamic Call Of Class

Thanks for the advise, updated post now.

JamesFreeman started a new conversation Dynamic Call Of Class

Hi People,

I'm starting a new package. However I've run into a problem at square one and I really cannot understand it.

//Routes.php
$ebay->Test('1', '1');

//Ebay.php
use Freeman\Ebay\Requests\Test;
public function __call($name, $args)
{
new Test; //works fine
//return new $name($args); //doesn't work not a clue why
}

When I init the object within the namespace normally it works fine, but when I try to do it dynamically even though the request is the same I get "class not found" error.

Seems really strange any thoughts?

Thanks, James.