roemer

Member Since 2 Years Ago

Amsterdam

Software Engineer at Self-employed

Experience Points 1,730
Experience Level 1

3,270 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 9
Lessons
Completed
Best Reply Awards 0
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.

12 Jun
6 days ago

roemer started a new conversation Job Never Ends And Keeps Queue Worker Pinned At 100% CPU Even Though Last Line Of Handle() Is Reached

My application has several jobs to process uploaded CSV files. These files can be pretty big, so they are handled on a queue worker. All my jobs work fine, except for one, which never seems to finish. This job usually takes a little longer to process than the other ones, so I run the queue worker with php artisan queue:work --timeout=300 --sleep=3 so that the process does not automatically get killed. The job does not actually take 5 minutes, the max is about 1:30.

The weird thing though, is that it is not stuck on some infinite loop or something, the last line of the handle() method of the Job class is actually reached (it's a Log::info() which tells me that the job has finished). In the worker console Processed is never displayed and the thread is pinned at 100% CPU usage. Interestingly, the thread is at around 85% CPU while the job is running, and actually increases to 100% when it's finished. It won't actually run forever, when the --timeout which I supplied in the queue worker is reached, the process gets killed.

The job is initiated in the same way as any of the other jobs are (contextually):

// I use repository classes in my application, which are called from Controllers.
// In this case, the processFile method inside my ImportRepository dispatches the job that
// will process the file.
public function processFile(UploadedFile $file, string $type, $delimiter = ';') : Import
{
    // Each uploadable file has it's own class which defines the columns etc. This function
    // will initiate that class for the uploaded file. It also has information on which job
    // to call etc. which is used later
    $import = $this->getImportClassForType($file, $type);

    // Model is a Eloquent model to track the status, create it
    $model = $this->create([
        'type'      => $type,
        'started_on'    => Carbon::now(),
        'status'        => 'initiated',
        'line_count'    => $file->getLineCount(),
    ]);

    // Returns the specific job to dispatch to handle this type of file.
    $import::getValidationJobClass()::dispatch($import, $model);

    return $model;
}

The actual processing job is pretty simple, it has a foreach loop to iterate over the lines of the CSV file. I don't think the issue lies there, as this foreach loop is completed as expected and the final line of the processing Job is reached.

Could it have something to do with the fact that the job usually takes a little longer to process than any other? I had to use --timeout=300 because the queue process would get killed before. I can execute any other job with --timeout=300 and they will finish though... There are no errors in the logs. I just see the Log::info() from the last line and that's it. I tried adding return; to the Job class but no luck.

I use the latest Homestead on a MacBook Pro

Any help is appreciated.

22 May
3 weeks ago

roemer started a new conversation Job Never Ends And Keeps Queue Worker Pinned At 100% CPU Even Though Last Line Of Handle() Is Reached

My application has several jobs to process uploaded CSV files. These files can be pretty big, so they are handled on a queue worker. All my jobs work fine, except for one, which never seems to finish. This job usually takes a little longer to process than the other ones, so I run the queue worker with php artisan queue:work --timeout=300 --sleep=3 so that the process does not automatically get killed. The job does not actually take 5 minutes, the max is about 1:30.

The weird thing though, is that it is not stuck on some infinite loop or something, the last line of the handle() method of the Job class is actually reached (it's a Log::info() which tells me that the job has finished). In the worker console Processed is never displayed and the thread is pinned at 100% CPU usage. Interestingly, the thread is at around 85% CPU while the job is running, and actually increases to 100% when it's finished. It won't actually run forever, when the --timeout which I supplied in the queue worker is reached, the process gets killed.

The job is initiated in the same way as any of the other jobs are (contextually):

// I use repository classes in my application, which are called from Controllers.
// In this case, the processFile method inside my ImportRepository dispatches the job that
// will process the file.
public function processFile(UploadedFile $file, string $type, $delimiter = ';') : Import
{
    // Each uploadable file has it's own class which defines the columns etc. This function
    // will initiate that class for the uploaded file. It also has information on which job
    // to call etc. which is used later
    $import = $this->getImportClassForType($file, $type);

    // Model is a Eloquent model to track the status, create it
    $model = $this->create([
        'type'      => $type,
        'started_on'    => Carbon::now(),
        'status'        => 'initiated',
        'line_count'    => $file->getLineCount(),
    ]);

    // Returns the specific job to dispatch to handle this type of file.
    $import::getValidationJobClass()::dispatch($import, $model);
}

The actual processing job is pretty simple, it has a foreach loop to iterate over the lines of the CSV file. I don't think the issue lies there, as this foreach loop is completed as expected and the final line of the processing Job is reached.

Could it have something to do with the fact that the job usually takes a little longer to process than any other? I had to use --timeout=300 because the queue process would get killed before. I can execute any other job with --timeout=300 and they will finish though...

I use the latest Homestead on a MacBook Pro

Any help is appreciated.

09 May
1 year ago

roemer started a new conversation Make:migration Uses Last Weeks Date! Throws Failed To Open Stream Error

Hi,

It seems like I've somehow messed up the migration naming system in a very odd way.

An hour ago, I created a new migration and noticed that it wasn't sorted properly in the migrations folder. I quickly noticed that the reason for this was that it used the date of 7 days ago, in this case may 2nd 2018. Since the last migration I created was on the same day, but slightly later in the day, my new migration would actually be executed before the one from last week.

Confused, I checked the system date of my Homestead instance and there it was, the date was a week behind! Somehow, the system date was still may 2nd. Easy fix I thought, I'll just update the system date (sudo date --set "9 MAY 2018 13:50:00" and sudo dpkg-reconfigure tzdata) and try creating the migration again! Weirdly enough, I got this error:

php artisan make:migration document_nr_and_addresses_table

In ClassLoader.php line 444:

  include(/home/vagrant/Code/Focus/vendor/composer/../../database/migrations/2018_05_02_033734_documen
  t_nr_and_addresses_table.php): failed to open stream: No such file or directory

It's still using last weeks date! Even though the output of date in the command line is now correct.

Things I've tried:

  • Rebooting
  • php artisan cache:clear
  • composer dump-autload
  • Running date('Y-m-d H:i:s') in a tinker session in the Homestead box. This outputs the correct date and time!

Unfortunately, nothing worked.

Any ideas?

05 Feb
1 year ago

roemer started a new conversation Security Concerns For REST Login

Hi,

I implemented a REST login system based on the default auth system (overwrote some of the functions in AuthenticatesUsers). This way, the consumer of my API can send usernames and passwords to /login and receive the user and an API token that can be used for new requests (this is why I'm not using Passport). I'm wondering if there are any security concerns that I have to look out for when doing this. I'm still throttling users since basically everything in AuthenticatesUsers still applies except for the authenticated function. I will be disabling CSRF validation for this endpoint as well, otherwise, it'll be hard to send requests to.

Thanks in advance.

P.S. I wrote this trait that I'm assigning to my User model instead of AuthenticatesUsers:

trait AuthenticatesUsersREST
{
    use AuthenticatesUsers {
        AuthenticatesUsers::authenticated as parentAuthenticated;
    }

    /**
     * Overwrites the authenticated method from AuthenticatesUsers and
     * returns the logged in users with it's API tokens.
     *
     * @param Request $request
     * @param $user
     * @return JsonResponse
     * @throws \Exception
     */
    public function authenticated(Request $request, $user)
    {
        $users = new UserRepository();
        return new JsonResponse($users->findWithRelations($user->id));
    }
}
03 Feb
1 year ago

roemer started a new conversation REST Response For LoginController

Hi,

I have a application that uses an external LDAP server for authentication, and is mostly a (GraphQL! :D) API. This application will basically just be an API, so I need API authentication. I tried using Passport, but unfortunately, it doesn't work in conjunction with the LDAP authentication driver I'm using. In the ideal world I'd use it, but there simply isn't enough time for this project to get the two to talk. The frontend developer on this project actually likes that we're not using Passport because that means he doesn't have to do a full OAuth integration. We're going to use a modified version of the TokenGuard from Laravel Spark (yes I have a license) for the authentication. This means it'll be like Passport, but simplified. The API doesn't have any clients except for the website we're building ourselves, so the fact that we're missing that aspect from OAuth is not an issue.

Anyway, the frontend still needs to be able to retreive tokens from the application so I want to RESTify the /login endpoint so that you can just sent a username and password to it, and if they're correct, it'll spit out a token for you to use. The problem is that I still want to use the AuthenticatesUsers trait, since it makes sure that the LDAP driver is automatically used, it'll throttle login requests etc etc.

How is it possible to keep using the AuthenticatesUsers trait but reply with a JSON response instead of redirecting the user to $redirectTo?

16 Jul
1 year ago

roemer left a reply on Installing MongoDb On Laravel Homestead And Php7

Thank you so much! Saved me a bunch of time.

27 Jan
2 years ago

roemer left a reply on Image Validation Fails With SVG

@Ramain Thanks for the suggestions! I checked online and the sample image I was trying had mime-type text/plain, I suppose that that's why it wasn't working. Did get recognized as a SVG image by OS X though..

Anyway, I seem to have a new problem. I tried with another file which is definitely SVG (https://commons.wikimedia.org/wiki/File:Example.svg checked with http://www.checkfiletype.com/upload-and-check) but now I'm getting this exception:

NotReadableException in Decoder.php line 20:
Unable to read image from file (/tmp/phpoRb7Og).
in Decoder.php line 20
at Decoder->initFromPath('/tmp/phpoRb7Og') in AbstractDecoder.php line 314
at AbstractDecoder->init('/tmp/phpoRb7Og') in AbstractDriver.php line 64
at AbstractDriver->init('/tmp/phpoRb7Og') in ImageManager.php line 50
at ImageManager->make('/tmp/phpoRb7Og') in RealestateAgencyRepository.php line 361

Seems like Decoder doesn't handle the file for some reason? It's not a permissions thing, every other type of image works.

P.S. Also tried your size, but that seems to validate for minimum (or exact, not sure) file size, so anything lower than 20MB get's declined.

roemer started a new conversation Image Validation Fails With SVG

Hi everyone,

A client of mine complained today that one of his customers can't upload their SVG logo into an App. I found this odd since I validate for image and the documentation clearly states:

The file under validation must be an image (jpeg, png, bmp, gif, or svg)

Still, the request was denied. The validation message for an invalid image shows up as the response for the request (REST API). In short, here's my code:

$validator = Validator::make($request->all(), [
    'logo' => 'required|image|max:20000'
]);

I've also tried it like this, but that doesn't work either, same message.

$validator = Validator::make($request->all(), [
    'logo' => 'required|mimes:jpg,jpeg,png,gif,svg|max:20000'
]);

Can anyone spot what's going wrong? Thanks!

13 Jan
2 years ago

roemer started a new conversation Collection SortBy Doesn't Actually Sort

Hi, I'm trying to sort some objects. These objects are realestate properties, and can be sorted in multiple ways. These are the options:

  • price_low
  • price_high
  • random
  • oldest
  • newest

When I want to order by price though (with Collection::sortBy()), it doesn't actually sort. Here's my code.

                switch($filter->order_by)
                {
                    case 'price_low':
                        $filter->properties = $filter->properties->sortBy(function($property)
                        {
                            return $property->price;
                        });
                        break;
                    case 'price_high':
                        $filter->properties = $filter->properties->sortByDesc(function($property)
                        {
                            return $property->price;
                        });
                        break;
                    case 'oldest':
                        $filter->properties = $filter->properties->sortBy(function($property)
                        {
                            return $property->created_at;
                        });
                        break;
                    case 'newest':
                        $filter->properties = $filter->properties->sortByDesc(function($property)
                        {
                            return $property->created_at;
                        });
                        break;
                    case 'random':
                        $filter->properties = $filter->properties->shuffle();
                        break;
                }

As you can see, a Filter has an order_by property, which sorts the properties in it's properties property. The sortBy method does run, but the properties still appear completely random, and not sorted by price. I'd give an example of this but it's a huge amount of (classified) content, but it's definitely random.

Any idea what's going wrong?

07 Jan
2 years ago

roemer started a new conversation Uploaded Video Is Saved In Directory With File Name Instead Of In Root Folder

Hi, my application contains a media upload feature where users can upload images and videos. I have no trouble saving the images, but I'm running into a problem when saving video. Images get resized using intervention/image, but video's do not. When I try to save a video, a new folder is created with the hashname of the file + the extension, and the video is saved in there, also as the hashname + the extension. An example of this would be as follows:

myproject/storage/app/public/media/{id}/b8e79fb3a719afc566f3cbe0ca47e47b.mp4/b8e79fb3a719afc566f3cbe0ca47e47b.mp4

It should be:

myproject/storage/app/public/media/{id}/b8e79fb3a719afc566f3cbe0ca47e47b.mp4

Here is my code for saving the media:

    protected function saveMedia(UploadedFile $media, int $mediaId)
    {


        $mimeType = $media->getMimeType();
        $mediaType = explode('/', $mimeType)[0];

        $path = $media->hashName('custom_slide_media/'.$mediaId);
        if ($mediaType == 'video')
        {
            Storage::disk('public')->put($path, $media);
        }
        else
        {

            $disk = Storage::disk('public');
            $disk->put($path, $this->formatImage($media));
        }

        return Storage::disk('public')->url($path);
    }

    protected function formatImage($file)
    {
        return (string) $this->imageManager->make($file->path())
            ->fit(900)->encode();
    }

Can anyone tell what's going wrong? Thanks

21 Dec
2 years ago

roemer left a reply on Adding New Routes To My Spark

Routes are evaluated in the order which they are listed. You can create a new route in your normal routes/web.php and it'll override the Spark route. Alternatively, you can edit the route in the spark/src/Http/routes.php file. These are the actual routes used by Spark, which you can edit without changing anything in vendor.

13 Dec
2 years ago

roemer started a new conversation Custom Validation Rule Not Working

Hi, I've written a custom validation rule that checks whether a field is larger than another field. So say, I want to filter by price, so I need price_to to be larger than price_from. The rule is as follows:

        Validator::extend('greater_than_field', function($attribute, $value, $parameters, $validator)
        {
            $minField = $parameters[0];
            $data = $validator->getData();
            $minValue = $data[$minField];
            Log::debug(sprintf('Checking if %d is larger than %d.', $value, $minValue));
            return $value > $minValue;
        });

However, when I try to implement it like so:

        $validator = Validator::make($request->all(), [
            'price_from' => 'required|integer',
            'price_to' => 'required|integer|greater_than_field:price_from',
            'percentage_from' => 'required|integer|min:0',
            'percentage_to' => 'required|integer|greater_than_field:percentage_from|max:100',
        ]);

        if ($validator->fails())
        {
            return response()->json($validator->messages());
        }

It still passes! And see that little Log::debug() in the custom validation? That doesn't work either. No logs are added to my storage/logs/laravel.log, hence why I'm posting here.

Any ideas? Thanks!

08 Dec
2 years ago

roemer left a reply on Routes Overlap

@tomi Thanks! Works like a charm

roemer started a new conversation Routes Overlap

Hi,

I have the following route group:

    Route::group([
        'prefix' => 'thing',
    ], function() {
        Route::get('all', 'API\[email protected]')->middleware('checkIfUserIsInThing');
        Route::post('create', 'API\[email protected]')->middleware('checkIfUserIsInThing');
        Route::post('update', 'API\[email protected]')->middleware('checkIfUserIsInThing');
        Route::delete('destroy/{id}', 'API\[email protected]')->middleware('checkIfUserIsInThing');
        Route::get('{id}', 'API\[email protected]')->middleware('checkIfUserIsInThing');
        Route::get('{id}/users', 'API\[email protected]')->middleware('checkIfUserIsInThing');
    });

I think it's pretty clear what these routes do. This causes an issue though. When I try to use the all route, it thinks 'all' is the {id} for the Route::get('{id}'). I assumed this would not happen if I define the all route first, but apparently it does. How do I resolve this?

20 Nov
2 years ago

roemer left a reply on 'Illegal Offset Type In Isset Or Empty' In Container For Service Provider

Nevermind, I made a typo in the singleton call. $this->app->singleton($contract, $services); should obviously be $this->app->singleton($contract, $service);

roemer started a new conversation 'Illegal Offset Type In Isset Or Empty' In Container For Service Provider

Hi,

I have a service provider which registers a bunch of singletons like so:

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $services = array(
            'App\Contracts\Repositories\RealworksRepository'    => 'App\Repositories\RealworksRepository',
            'App\Contracts\Repositories\PropertyRepository'     => 'App\Repositories\PropertyRepository',
            'App\Contracts\Repositories\SlideRepository'        => 'App\Repositories\SlideRepository'
        );

        foreach($services as $contract => $service)
        {
            $this->app->singleton($contract, $services);
        }
    }

But I'm getting the following error:

ErrorException in Container.php line 1093:
Illegal offset type in isset or empty
in Container.php line 1093
at HandleExceptions->handleError('2', 'Illegal offset type in isset or empty', '/home/vagrant/Code/makelaarstvcom/vendor/laravel/framework/src/Illuminate/Container/Container.php', '1093', array('abstract' => array('App\Contracts\Repositories\RealworksRepository' => 'App\Repositories\RealworksRepository', 'App\Contracts\Repositories\PropertyRepository' => 'App\Repositories\PropertyRepository', 'App\Contracts\Repositories\SlideRepository' => 'App\Repositories\SlideRepository'))) in Container.php line 1093
at Container->getAlias(array('App\Contracts\Repositories\RealworksRepository' => 'App\Repositories\RealworksRepository', 'App\Contracts\Repositories\PropertyRepository' => 'App\Repositories\PropertyRepository', 'App\Contracts\Repositories\SlideRepository' => 'App\Repositories\SlideRepository')) in Application.php line 703
at Application->make(array('App\Contracts\Repositories\RealworksRepository' => 'App\Repositories\RealworksRepository', 'App\Contracts\Repositories\PropertyRepository' => 'App\Repositories\PropertyRepository', 'App\Contracts\Repositories\SlideRepository' => 'App\Repositories\SlideRepository'), array()) in Container.php line 231

I have verified that all namespaces in the $services array are valid and all those classes exist. What am I doing wrong?

15 Nov
2 years ago

roemer started a new conversation Laravel 5.3 And Spark API, Routes Not Returning JSON

Hi, I'm using Spark and Laravel 5.3.19 to setup a JSON API. I can see that Spark does it like so:

Route

$router->get('/settings/api/tokens', 'Settings\API\[email protected]');

Controller

    public function all(Request $request)
    {
        return $this->tokens->all($request->user());
    }

And repo:

    public function all($user)
    {
        return $user->tokens()
                    ->where('transient', false)
                    ->orderBy('created_at', 'desc')
                    ->get();
    }

I like to do it similarly, where I can just do return $myRepo->all(); and it returns JSON to the client. I've had no problem setting up the repository and controller but now when I go to the route I've configured, it just redirects me back to my homepage without any errors or anything. My application does recognise the route because I don't get a NotFoundHttpException. I've placed my route in routes/api.php and tried it inside and outside of the 'middleware' => 'auth:api' block.

What confuses me is that the Spark route does not seem to have any further configuration that tells it to spit out JSON. Can anyone explain this to me?

31 Oct
2 years ago

roemer left a reply on Guidelines For Calling External API's

@jusahah87 Thank you for your suggestion. I think I'm gonna go with the service provider since similar integrations might be added in the future. Perhaps I'll wrap an artisan command around them.

roemer left a reply on Guidelines For Calling External API's

@jusahah87 Hi, thanks for your answer. So I should create a (composer) package that handles all communication and processing of the data and then make a service provider that binds it to the laravel framework?

roemer started a new conversation Guidelines For Calling External API's

Hi Ladies and Gents,

I have a question about coding guidelines. The application I'm building has an integration with a XML API which get's triggered every day at midnight. At that time, all new data from that system is imported into the application.

I was wondering, where should I put the code that calls the API and processes the data? I assume it shouldn't just be in app/Console/Kernel.php or in a Controller. Should it be a service provider or maybe a repository? I'm a little confused here. Can anyone give me advice?

Thanks in advance!

08 Oct
2 years ago

roemer started a new conversation Spark: Can't Create User Account. Brief Flash With Tons Of Errors

I've just created a new installation of Laravel Spark. Everything went fine but I can't create new user accounts. When I register, I see about 7 errors for like 0.2 seconds before I'm redirected back to /register. I made a screenrecording of Chrome to be able to see the errors. Here's a still from that clip:

errors still

All I did after installing was migrating the database. I'm running this installation on a Vagrant Homestead instance but I'm experiencing the same issue on a Linux staging server.

Any suggestions? Thanks in advance.