hromby

hromby

Member Since 5 Years Ago

Rødovre

Consultant at eCapacity

Experience Points 24,800
Experience Level 5

200 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 433
Lessons
Completed
Best Reply Awards 8
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.

16 Nov
8 months ago

hromby left a reply on Horizon Metrics Empty

I figured it out actually, and just wanted to leave my solution here if anyone should have the same problem in the future:

Keyword here was that i was on my staging server, where the environment is defined as "staging". There was no staging entry in the environments array in the Horizon configuration. I added a copy of the default config to this array with the key "staging" and restarted Horizon on my staging server, and the metrics started to show :-)

hromby left a reply on Horizon Metrics Empty

Did you find any solution to this? I am having the same issue on my staging server -- my local environment displays the data correctly.

27 Oct
2 years ago

hromby started a new conversation Testing Artisan Input Prompts

Hello!

I have an artisan command that uses $this->ask to ask the user for some input:

    public function handle()
    {
        User::create(['email' => $this->ask('Initial user\'s email'), 'password' => bcrypt($password = str_random())]);

        $this->info('Initial user created. Password is: ' . $password);
    }

How can I supply the input to a test that runs this command like this?

    /** @test */
    public function it_bootstraps_the_application()
    {
        $this->artisan('bootstrap', ['-n' => true]);
    }
12 Jul
3 years ago

hromby left a reply on App_path() In A Package

Thanks for the answer! Which illuminate package is that function part of?

hromby started a new conversation App_path() In A Package

Hello! I am developing a small package which will need to write a file to the base directory of the laravel installation, in the same spot as the composer.json file, phpunit.xml and so on lives.

How can I reference that path from within the package code? Is there a guaranteed way of referencing the same spot as the composer.json is in?

16 Nov
3 years ago

hromby left a reply on Testing More Of The Same Method Call With PHPSpec

Yes, that's my strategy also.

The thing is, when the HTTP client throws an error, I want to be able to call the same method again with the exact same arguments and get a different result (no exception thrown, but actual results returned).

I can't test the exception path without also returning real data from the method afterwards. That's the problem as I see it.

hromby left a reply on Testing More Of The Same Method Call With PHPSpec

But does this work in PHPSpec? Because when I have both calls, it just passes, even though I have no handler in place for the exception thrown. Does the order of the calls to the mock matter?

hromby started a new conversation Testing More Of The Same Method Call With PHPSpec

Hello!

I am trying to test a function that talks to an API. This method should be able to handle errors thrown by the HTTP client (like API throttling etc.) and act appropriately (for example by waiting a bit and then sending the request again.

I am trying to test this with PHPSpec, but it seems that it doesn't pick up on the fact that I want to have two different results from the same method call (the first one should throw an Exception telling my client to wait, while the second one should return the actual data). Does anyone know of a way to handle this?

Here's an example of a method on my class that respects a 400 error sent by the API:

    private function getReport($id)
    {
        try {
            return $this->http->postJson($this->baseUrl, [
                'query' => ['object' => $id]
            ]);
        } catch (HttpException $exception) {
            if ($exception->getCode() == 400) {
                sleep($this->waitTime);

                $this->waitTime += 2;

                return $this->getReport($id);
            }

            throw $exception;
        }
19 Sep
3 years ago

hromby left a reply on Multi File Upload Testing With Symfony Dom Crawler

Does the attach method expect a CSS identifier as the second argument?

hromby left a reply on Search Laravel Table Column With Minimum And Maxium Value

Are you aware that your condition reads $price_min && $price_min instead of $price_min && $price_max? :-)

hromby left a reply on Testing Delete Links

@hameed thanks for that link -- I already have something similar in place, but that won't be testable with the normal Laravel test functions because of the use of JavaScript, right?

@ian_h thanks for the explanation -- but you don't really click a link here, I think. Maybe I shouldn't worry and just hit the route directly like you do.

hromby left a reply on Testing Delete Links

Thanks for the answers! I think I missed a point in my original post: I use both a resourceful CompaniesController and a resource route (like Route::resource('companies', 'CompaniesController')).

So when I have a delete-link: ```Delete````

And use the following test code:

$this->visit('/companies')->click('Delete');

I trigger a GET to /companies/ instead of a DELETE, thus giving me the wrong controller action. I've inserted a form instead (with a hidden _method input), but that doesn't really look good if I want to have something like a button group or similar.

How can I go about implementing the delete link in a RESTful way, and be able to test it at the same time?

18 Sep
3 years ago

hromby started a new conversation Testing Delete Links

Hello!

I have a simple problem: I have a CompanyController (resource controller) and a list of companies. On that list, I have a delete link for each company.

How can I test that delete link with the testing facilities in Laravel (the stuff that previously was the Integrated package)?

I simply want to create a company with a factory, click a delete link and make sure that I have one less company in the database :-)

15 May
4 years ago

hromby left a reply on Form Components As View Partials

Thanks! I'll give it a try myself and see how I like it :-)

14 May
4 years ago

hromby started a new conversation Form Components As View Partials

Hello everyone!

A while back, Jeffrey showed how to extend the form builder and implement extra methods, specifically for making form components that wrapped input fields in Bootstrap-markup. Has worked fine for me, although the limited flexibility has been a problem sometimes.

Recently, I thought of creating small view partials that include the wrapped input fields instead of extending the form builder class. I would then include the view partials where appropriate, and feed in the field names and labels through parameters.

Are there any drawbacks to this approach that I haven't spotted? I don't think I've seen it used before, so I am curious if I am missing some obstacle that would render it impossible and/or stupid :-).

Thanks!

01 May
4 years ago

hromby left a reply on Maximum Function Nesting Level Reached

The standard Laravel nesting level actually is 250 -- take a look in the homestead provisioning source:

https://github.com/laravel/settler/blob/master/scripts/provision.sh#L122

29 Apr
4 years ago

hromby left a reply on Laravel 5 How To Make A Queue With A Finish Message Popup

You could use something like pusher.com and send a message when the job is done, and the user who requested the job would listen to that channel in the browser.

https://laracasts.com/lessons/pusher-awesomeness

... and, in Laravel 5.1:

https://laracasts.com/lessons/broadcasting-events-in-laravel-5-1

28 Apr
4 years ago

hromby left a reply on Command-Line App

Laracasts actually has a whole series on command-line apps right here: https://laracasts.com/series/how-to-build-command-line-apps-in-php/episodes/1 :-)

hromby left a reply on How To Log Undefined Translation Keys?

How about extending the Translator class, overwriting the get() method by basically copying it but adding a log call when returning the translation key?

You would then register your own implementation in the IoC and I think you should be good to go.

hromby left a reply on Authentication Fails No Matter What

Make sure that you hash the password using Hash::make($password) before storing it in the database. The Auth::attempt relies on a hashed password.

11 Feb
4 years ago

hromby left a reply on Elixir Concatenation

Ah, that's cool. Thanks! Skipped happily along to the scripts part of the doc and completely missed that note.

Thanks again for your help!

hromby left a reply on Elixir Concatenation

Thanks, it works! I don't see the third argument in the docs though -- but great that it works, I am still very much in a learning phase with Elixir :-)

hromby left a reply on Composer Error On Installing DOM PDF On Laravel 4.1

Yeah okay, so I'm not really sure why that would throw an error as Composer should just give you a new vendor directory with updated dependencies. Maybe someone with Windows experience could give an answer here?

hromby left a reply on Elixir Concatenation

Hi guys, thanks for the answers! I thought I had the argument order right. If you have the time, would you mind giving me an example of what my gulpfile should look like?

Thanks again!

hromby left a reply on Composer Error On Installing DOM PDF On Laravel 4.1

Try removing the vendor dir and composer.lock (notice: .lock) and try composer update again.

hromby left a reply on Composer Error On Installing DOM PDF On Laravel 4.1

Hard to say without a stack trace of som sorts :-)

hromby left a reply on Composer Error On Installing DOM PDF On Laravel 4.1

The problem is your requirement for "barryvdh/laravel-debugbar" : "dev-master". It's for Laravel 5, and you require "laravel/framework" : "4.1.". Use "barryvdh/laravel-debugbar" : "~1.8" :-)

hromby started a new conversation Elixir Concatenation

Hi! I have this Elixir script:

var elixir = require('laravel-elixir');

/*
 |--------------------------------------------------------------------------
 | Elixir Asset Management
 |--------------------------------------------------------------------------
 |
 | Elixir provides a clean, fluent API for defining some basic Gulp tasks
 | for your Laravel application. By default, we are compiling the Less
 | file for our application, as well as publishing vendor resources.
 |
 */

elixir(function(mix) {
    mix.copy('vendor/bower_components/jquery.uniform/jquery.uniform.js', 'public/js/vendor/uniform.js')
        .copy('vendor/bower_components/jquery-migrate/jquery-migrate.js', 'public/js/vendor/migrate.js')
        .copy('vendor/bower_components/excanvas/excanvas.js', 'public/js/vendor/excanvas.js')
        .copy('vendor/bower_components/respond/src/respond.js', 'public/js/vendor/respond.js')
        .copy('vendor/bower_components/jquery.slimscroll/jquery.slimscroll.js', 'public/js/vendor/slimscroll.js')
        .scripts(['public/js/vendor/excanvas.js', 'public/js/vendor/respond.js'], 'public/js/ie9.js')
        .scripts(['public/js/vendor/uniform.js', 'public/js/vendor/migrate.js', 'public/js/vendor/slimscroll.js', 'public/js/metronic.js', 'public/js/layout.js'], 'public/js/all.js')
});
  • but it doesn't output any scripts called ie9.js or all.js. I have previously used .scriptsIn('public/js/vendor', /public/js/all.js') without problems. What am I doing wrong?
27 Jan
4 years ago

hromby started a new conversation Laravel 5 Default Application Structure

I've just checked out a fresh Laravel 5 installation, and at the moment, this is the default app structure (the domain code):

├── Commands
│   └── Command.php
├── Console
│   ├── Commands
│   │   └── Inspire.php
│   └── Kernel.php
├── Events
│   └── Event.php
├── Exceptions
│   └── Handler.php
├── Handlers
│   ├── Commands
│   └── Events
├── Http
│   ├── Controllers
│   │   ├── Auth
│   │   │   ├── AuthController.php
│   │   │   └── PasswordController.php
│   │   ├── Controller.php
│   │   ├── HomeController.php
│   │   └── WelcomeController.php
│   ├── Kernel.php
│   ├── Middleware
│   │   ├── Authenticate.php
│   │   ├── RedirectIfAuthenticated.php
│   │   └── VerifyCsrfToken.php
│   ├── Requests
│   │   └── Request.php
│   └── routes.php
├── Providers
│   ├── AppServiceProvider.php
│   ├── BusServiceProvider.php
│   ├── ConfigServiceProvider.php
│   ├── EventServiceProvider.php
│   └── RouteServiceProvider.php
├── Services
│   └── Registrar.php
└── User.php

Is this the recommended way of structuring your app now? What happens when our app scales -- surely our Events and Commands directories would become very large and hard to maintain.

Currently (Laravel 4), I structure the app namespace into "sub-parts" of my app like Users, Posts, Articles and so on, much of the time structured around a group of models in each sub-part. Does this fit at all with the new structure, or should I adapt to a new way of structuring it?

12 Jan
4 years ago

hromby left a reply on Migrate Foreign / References

$table->foreign('user_id')->references('id')->on('users'); sets up a foreign key in MySQL, ensuring that a user matching the user_id exists in the users table.

Eloquent relations are somewhat related but it's not the same. You can set up a relation in your models like so:

public function user()
{
    return $this->belongsTo('User');
}

This will find the related User model given the user_id (it figures this out itself) and returns the user. So, if the relation is on a country, you could do $country->user->user_name;

hromby left a reply on Unit Testing A Command Handler

Thanks for your answers :-)

06 Jan
4 years ago

hromby left a reply on Using Knp-Snappy With Laravel Homested -- Css File Not Working?

Here's the code I'm using to refer to the paths. I got tired of switching them around when testing in the browser vs. rendering as PDF. It does look a lot like what you've already got though.

    /**
     * Handle the given report from an internal request by running the data and rendering it as HTML.
     *
     * @param   Report  $report  the report to handle.
     * @return  string           the HTML.
     */
    public function handleFromInternal(Report $report)
    {
        $company = strtolower(str_replace(
            [' ', ',', 'æ', 'ø', 'å'],
            ['', '', 'a', 'o', 'a'],
            $report->company->name
        ));

        $paths = [
            'bootstrap' => public_path('reporting/css/bootstrap.css'),
            'style' => public_path('reporting/companies/' . $company . '/style.css'),
            'background' => public_path('reporting/companies/' . $company . '/background.jpg'),
            'logo' => public_path('reporting/companies/' . $company . '/logo.png'),
            'positive_arrow' => public_path('reporting/img/arrow-pos.svg'),
            'negative_arrow' => public_path('reporting/img/arrow-neg.svg'),
            'root' => public_path().'/',
            'company' => $company,
            'base_style' => public_path('reporting/css/base.css'),
        ];

        $pages = $this->getPages($report, $paths);

        return $this->view->make('reporting.base', compact('report', 'pages', 'paths'))->render();
    }

    /**
     * Handle the given report from an external (web) request by running the data and rendering it as HTML.
     *
     * @param   Report  $report  the report to handle.
     * @return  string           the HTML.
     */
    public function handleFromExternal(Report $report)
    {
        $company = strtolower(str_replace([' ', ','], '', $report->company->name));

        $paths = [
            'bootstrap' => asset('reporting/css/bootstrap.css'),
            'style' => asset('reporting/companies/' . $company . '/style.css'),
            'background' => asset('reporting/companies/' . $company . '/background.jpg'),
            'logo' => asset('reporting/companies/' . $company . '/logo.png'),
            'positive_arrow' => asset('reporting/img/arrow-pos.svg'),
            'negative_arrow' => asset('reporting/img/arrow-neg.svg'),
            'root' => asset(''),
            'company' => $company,
            'base_style' => asset('reporting/css/base.css'),
        ];

        $pages = $this->getPages($report, $paths);

        return $this->view->make('reporting.base', compact('report', 'pages', 'paths'))->render();
    }
05 Jan
4 years ago

hromby left a reply on Using Knp-Snappy With Laravel Homested -- Css File Not Working?

Hey :-) Make sure that you reference the full filesystem path to the CSS and not the full path on the webserver.

02 Jan
4 years ago

hromby left a reply on Unit Testing A Command Handler

Does nobody have an answer for this? It seems like such a common pattern to me.

31 Dec
4 years ago

hromby left a reply on Behat Giving Error - Call To Undefined Method FeatureContext:

Could you post your feature and feature context?

hromby left a reply on When Do I Use Commander For A Command Vs Helper, Provider, Etc?

My answer would be something like: pass everything to the command bus, except maybe reads from the database. If you are relying on different services, providers and helpers in your controllers, they quickly accumulate a lot of dependencies which may each only be used once. With a command bus, you are pushing those dependencies down to only the handler class that needs them.

And besides that, the command bus gives you the whole pipeline structure that you may utilize for many cool things in your project. By being consequent, you are making the project more maintainable :-)

hromby started a new conversation Unit Testing A Command Handler!

Hello!

A simple command handler might look like the following (I think this is also a pattern for command handlers that has been used on this site):

class StoreObjectCommandHandler {

    protected $objects;

    public function __construct(ObjectRepository $objects)
    {
        $this->objects = $objects;
    }

    public function handle($command)
    {
        $object = MyObject::instantiate($command->name, $command->age);

        $this->objects->store($object);
    }
}

How can we unit test this, given that static method call? I know we can assert that the object repository receives a store call with some MyObject, but is that really good enough?

28 Dec
4 years ago

hromby left a reply on Multiple BelongsTo Without Polymorphic Relations

@jamesaps Then I would recommend the answer that I have already given:

´´´ * users * id

  • albums

    • id
  • images

    • id
  • album_image

    • album_id
    • image_id
  • image_user

    • image_id
    • user_id ´´´

hromby left a reply on Multiple BelongsTo Without Polymorphic Relations

@jamesaps yes. But this is only applicable if an Image can belong to many Albums and many Users. If it can belong to only one, refer to my original answer.

hromby left a reply on Multiple BelongsTo Without Polymorphic Relations

Apparently, my latest reply wasn't posted. But when you say that an Image can belong to multiple Albums and/or Users, you should go for two pivot tables:

* users
    * id

* albums
    * id
    * user_id

* images
    * id

* image_user
    * image_id
    * user_id

* album_image
    * album_id
    * image_id

-- and add belongsToMany relations on the proper models.

hromby left a reply on Multiple BelongsTo Without Polymorphic Relations

Then you could go for the following, using belongsToMany relationships:

* users
    * id

* albums
    * id

* images
    * id

* album_image
    * album_id
    * image_id

* image_user
    * image_id
    * user_id

hromby left a reply on Multiple BelongsTo Without Polymorphic Relations

How about:

* Users
    * id

* Albums
    * id
    * user_id references Users

* Images
    * id
    * user_id references Users
    * album_id references Albums

But can the Image belong to at User without an album? Can an Image belong to an Album but a different User than the Albums owner?

23 Dec
4 years ago

hromby started a new conversation Eloquent And Parent-child Relations

Hello!

In my current project, I have three models: Vehicle, Car and Truck. In a traditional OO approach, the Car and Truck classes would extend Vehicle, which would be an abstract base class. My problem is: how do I structure that with Eloquent?

One approach might be to have three tables; one for each model. The vehicles table could have a polymorphic relation which points to the right child object in either cars or trucks. These tables would then correspond to a model each, with Vehicle having a morphTo relation to the subclass, and the subclasses would have a morphOne back to the base class, so no real abstract class and subclasses here -- but I think it could be done in a cleaner way -- but I dont know how :-)

How would you structure it? Preferably, I'd like to be able to add a whole new subtype of vehicles without tinkering too much with the existing setup. Also, I would like to have a simple way of listing all vehicles regardless of subtype in a single list.

22 Dec
4 years ago

hromby left a reply on PDF's And Laravel

I'm using Snappy PDF with the Laravel wrapper, and it's pretty neat. It has its limitations, but it's superior to the other alternatives I've used because it allows you to use a Bootstrap grid, which was a requirement for the project I've used it in :-)

16 Dec
4 years ago

hromby left a reply on Form Model Binding - Best Practice?

You are doing all your logic in the controller, which is perfectly fine for smaller projects. However, if you are planning a larger app -- or want to play around with the concepts -- you should defer the filling and saving of models to a repository or something similar.

You could also utilize a command bus, which I am a big fan of. I don't know how Laracasts Commander works with L5 (maybe someone else can enlighten me), but you could check that out.

Also, a smaller thing: you can extend the form builder class to include functions for Bootstrap fields, making your code that much more readable in the views. For example, Form::text('email', null, ['class' => 'form-control']) would become Form::bootstrapText('email'), which in my opinion is a lot more readable. There is a lesson on this site on the exact subject.

hromby left a reply on Change DB For Model On The Run

You can change the database you are using with DB::connection('foo')->select(...);

26 Nov
4 years ago

hromby left a reply on Unit Testing An Object As The Return Value

This works, however -- is that the way to go? Simply test that all the content in the objects match?

class Container {

    protected $items;

    public function __construct($items)
    {
        $this->items = $items;
    }

    public function getItems()
    {
         return $this->items;
    }

}

class Connection
{
    public function getData($array)
    {
        return new Container($array);
    }
}

class ConnectionSpec extends ObjectBehavior
{
    function it_converts_arrays_to_containers()
    {
        $array = ['foo', 'bar'];

        $container = new Container($array);

        $this->getData($array)->getItems()->shouldReturn($container->getItems());
    }
}

hromby left a reply on Unit Testing An Object As The Return Value

I don't think I understand. I've written some sample code -- how can I make the test pass?

``` class Container {

protected $items;

public function __construct($items)
{
    $this->items = $items;
}

}

class Connection { public function getData($array) { return new Container($array); } }

class ConnectionSpec extends ObjectBehavior { function it_converts_arrays_to_containers() { $array = ['foo', 'bar'];

    $container = new Container($array);

    $this->getData($array)->shouldReturn($container);
}

} ``

hromby started a new conversation Unit Testing An Object As The Return Value

Hello!

I have a system in which pass data around between data getters, mailers, transformations, presenters and so on and so on. I've created an object to hold the data in order to ensure that the data is always consistent with the expected format (I could simply have used an array to hold the data, but it would be much harder to enforce the format in that case).

So, for example, I query a data connection in order to get some data from it, which is returned as an array. Now I want to convert it into my object.

For example, the code might look like this:

´´´ public function getConvertedData($someArgument) { $data = $this->connection->getData($someArgument); // returns array

$container = new DataContainer($data);

return $container;

} ´´´

How can I unit test the getConvertedData method? Testing the getData method seems trivial as I can just match the returned array with some expectation. But how can I do the same when the return value is a new'ed up object?

27 Oct
4 years ago

hromby left a reply on Graph Library

So, I just found out I can use Javascript. No problem!