bensampo

bensampo

Member Since 1 Year Ago

Experience Points 53,730
Experience
Level
Lessons Completed 532
Lessons
Completed
Best Reply Awards 0
Best Answer
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.

06 Jul
5 months ago

bensampo left a reply on Ensuring That There Are Tests For A Given Set Of Classes (static Analysis?)

@click This is pretty much what I have ended up with. I have a test which loops over all of the files in the resource folder and makes sure that a corresponding test files exists.

Thanks for the suggestions all!

bensampo left a reply on Ensuring That There Are Tests For A Given Set Of Classes (static Analysis?)

If anyone is interested, this is my solution:

public function test_resource_tests_exist_test()
    {
        // Get all of the resource test files
        $resourceTestFiles = array_map(function(SplFileInfo $file) {
            return $file->getFilename();
        }, array_filter(File::allFiles('tests/Unit'), function(SplFileInfo $file) {
            $filename = $file->getFilename();
            if (substr($filename, -strlen('ResourceTest.php'))==='ResourceTest.php') {
                return true;
            }
        }));

        // Loop over each of the resource files and assert that a test file exists for them
        $resourceFiles = array_map(function(SplFileInfo $file) use ($resourceTestFiles) {
            $resourceFilename = $file->getFilename();
            $expectedTestFile = str_replace('.php', 'Test.php', $resourceFilename);

            $this->assertContains($expectedTestFile, $resourceTestFiles);

        }, File::allFiles('app/Http/Resources'));
    }

This relies on the naming convention of: ModelResource.php for your model ModelResourceTest.php for your test

bensampo left a reply on Ensuring That There Are Tests For A Given Set Of Classes (static Analysis?)

Thanks @martinbean, to clarify: I want to check that the output contains the data I expect, rather than that it conforms to a standard.

bensampo started a new conversation Ensuring That There Are Tests For A Given Set Of Classes (static Analysis?)

I'm building an API using Laravel's resources. I want to make sure that the output of each one conforms to my expectations, so for each resource class I have a corresponding unit test.

What I'd ideally like to do is have a test which grabs a list of all of my resource classes and makes sure there is a corresponding unit test.

Essentially I want to test that there are tests.

Is there a sensible/standard way to do this?

bensampo left a reply on Counting A Related Model Using Lazy Eager Loading

Turns out this was all fine, I just hadn't set up the likes relation on the Comment model. Doh!

bensampo started a new conversation Counting A Related Model Using Lazy Eager Loading

Hi,

I have a model for Houses. Each house can have many Comments. Comments can be liked by users. I want to include the number of likes alongside each of the comments.

I'm using route model binding and lazy eager loading on my controller action for [email protected]:

public function show(House $house)
    {
        $house->load([
            'comments' => function($query) {
                $query->withCount('likes');
            },
            'comments.user'
        ]);

        return new HouseResource($house);
    }
        

This doesn't work and I get the error:

Method Illuminate\Database\Query\Builder::likes does not exist.

Anyone know how I might be able to achieve this without re-querying the model?

30 May
6 months ago

bensampo left a reply on Flagged Enum

I wrote a package which simulates enums but actually uses class constants.

https://github.com/BenSampo/laravel-enum

You could set up an enum like this:

// DaysEnum.php
namespace DummyNamespace;

use BenSampo\Enum\Enum;

final class Days extends Enum
{
    const Sunday = 0;
    const Monday = 1;
    const Tuesday = 2;
    const Wednesday = 3;
    const Thursday = 4;
    const Friday = 5;
    const Saturday = 6;
}

Your type in the DB column would be an int and you'd store the values 0-6 depending on the day.

You could then use the enum like this:

if ($day == Days::Tuesday) {
    // Do Tuesday stuff
}
11 Sep
1 year ago

bensampo left a reply on Laravel Enum

I was looking for a similar solution recently and ended up building an abstract enum class pulled together from lots of different resources.

I've split it out into a package in case it's of use to anyone in future: https://github.com/BenSampo/laravel-enum

As an example you can do:

final class UserType extends Enum
{
    const Administrator = 0;
    const Moderator = 1;
    const Subscriber = 2;
    const SuperAdministrator = 3;
}

And grab the value back like:

UserType::Administrator // 0

Of course, you can then store this in the DB as an int.

22 Aug
1 year ago

bensampo left a reply on Sanity Check On My Deployment, Staging, Production Plan. Is It Good?

I believe that the environment variables should be added in Forge for production and staging and the .env should only be read on dev/local.

See: https://scotch.io/tutorials/understanding-laravel-environment-variables

I would be interested to hear others feedback on the rest, as I'm in a similar position and had a very similar idea on infrastructure to you.

14 Aug
1 year ago

bensampo left a reply on A Clean Way For Users To Opt Out Of Emails

In the end I found an event which is fired just before sending a message. I've set up a listener for this event which grabs the users from the to address on the message and checks for a setting on the user model. Depending on if the users has emails enabled the event is either stopped or it continues. Code below:

EventServiceProvider.php

protected $listen = [
    'Illuminate\Mail\Events\MessageSending' => [
        'App\Listeners\MessageBeforeSendListener',
    ],
];

MessageBeforeSendListener.php

<?php

namespace App\Listeners;

use App\Repositories\IUserRepository;
use Illuminate\Mail\Events\MessageSending;

class MessageBeforeSendListener
{
    private $userRepo;

    /**
     * Create the event listener.
     */
    public function __construct(IUserRepository $userRepo)
    {
        $this->userRepo = $userRepo;
    }

    /**
     * Handle the event.
     *
     * @param MessageSending $event
     */
    public function handle(MessageSending $event)
    {
        $toAddress = key($event->message->getTo());
        $user = $this->userRepo->findWhere([
            'email' => $toAddress,
        ])->first();

        return $user->send_notification_emails ? $event : false;
    }
}
13 Aug
1 year ago

bensampo left a reply on A Clean Way For Users To Opt Out Of Emails

@IgorBabko - thanks for the response. I could do that, but if I have 100 calls to different notifications, I'm going to need to do that for every one.

Ideally I'd like to say "only send emails to users who have opted in" globally.

bensampo started a new conversation A Clean Way For Users To Opt Out Of Emails

I have a flag on my user model which allows people to opt out of emails. I want to use this flag to only send notification emails to users who have opted in. Is there a way to do this in one place rather than wrapping every call to Mail in a condition?

Thanks, Ben