bastiaan89

bastiaan89

Member Since 5 Years Ago

Experience Points 42,395
Experience Level 9

2,605 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 686
Lessons
Completed
Best Reply Awards 9
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.

22 Jan
2 years ago

bastiaan89 left a reply on Removing Conditionals

You could solve it by adding methods (to your controller, or another class if you were going to extract it away from the controller) with names corresponding to the type. These methods should accept a parameter $amount and then in the store or update method you can just do $this->$type($amount) or call_user_func if you prefer that. To make it more robust you should put that in a function_exists($this, $type) conditional. By doing it this way, you could support additional types in the future by just adding a method for them.

Jeffrey uses this technique in https://laracasts.com/series/eloquent-techniques/episodes/4. Hope this helps!

bastiaan89 started a new conversation AuthenticateSession Middleware

In the development branch of the laravel/laravel repository, I noticed that the AuthenticateSession middleware is added to the web stack (commented out). I've tried to understand what it's supposed to do, but the only thing I discovered is that the "remember me" checkbox no longer works when this middleware is enabled (done by ticking the checkbox, logging in, deleting the session cookie, and refreshing). Is that its intended purpose?

20 Jan
2 years ago

bastiaan89 left a reply on I CanĀ“t Install Laravel Mix

Just laravel-mix should be sufficient, because it has the webpack dependency itself. What does your package.json file look like?

19 Dec
3 years ago

bastiaan89 left a reply on Using Laravel Response Displays HTTP Header Code

The response() part is not needed. Does leaving that out help maybe?

bastiaan89 left a reply on Best Practices For Form Model Binding In Laravel 5.1

That other builder looks nice, although largely very similar to the collective version.

Regarding the ProjectFlyer and quickstart: neither of those have a form for editing a resource, just deleting. In the case of the quickstart, no values are remembered at all, so input would be lost on a failed form validation which is pretty bad in my opinion (it's just a quickstart but still I'd consider that to be an important aspect).

bastiaan89 left a reply on Best Way To Backup MySQL Database From Laravel Forge Production Server?

I have this set up using a cron job, somewhat like bashy has. If you want no hassle and scripting yourself, you could look at something like https://ottomatik.io, seems to be popular among laravel people.

bastiaan89 left a reply on Updating Password Error Method [validatePassword] Does Not Exist.

You're trying to use a password validation rule, but no such rule exists. Remove it from the password validation rules.

On a side note, you don't have to create the validator and stuff, there is a validate method on controllers that you can use like so:

$this->validate($request, $rules);

On failure this will do the redirection and stuff automatically.

bastiaan89 left a reply on Assign Variable Class To <body> With Blade?

Personally I would do that with a variable, a section may be a bit overkill.

...
<body class="{{$body_class}}">
...
@extends('templates.master', ['body_class' => 'body__home'])

bastiaan89 left a reply on Requesting Comments On This Solution For Localization

Well yeah if the site is restricted to registered users, just retrieving their setting from the database would work fine. However, it also needs to be available for guests, as most of the site is publicly visible. The registered users can just create content, and view some pages that are private to groups they can be in. I know that still doesn't mean that the URL needs to have the locale code, but I think it's better that way for SEO, to prevent duplicate pages (I'm also setting the link element with rel=alternate) and to have the correct language appearing in search results, if available.

bastiaan89 left a reply on Requesting Comments On This Solution For Localization

Anyone? Surely I can't be the only one who struggled with this.

18 Dec
3 years ago

bastiaan89 left a reply on Faceing An Issue With Authorization

I'm doing it like this:

foreach (Permission::all() as $permission)
        {
            $gate->define($permission->name, function (User $user) use ($permission)
            {
                return $user->hasPermission($permission);
            });
        }

And it works fine. Have you tried calling Gate::check() instead?

bastiaan89 left a reply on Best Practices For Form Model Binding In Laravel 5.1

Just out of curiosity, why wouldn't you want to use the collective HTML package?

bastiaan89 left a reply on Weird Problem With Relations

What I meant that you set a HasManyThrough relationship on the company. That'll look something like this:

public function contacts()
    {
        return $this->hasManyThrough('App\Contact', 'App\Client');
    }

Then you can do $company->contacts which will return all contacts belonging to a client that belongs to the company.

bastiaan89 left a reply on Weird Problem With Relations

A company's clients are represented as a Collection, on which you can't query. Take a look at hasManyThrough.

bastiaan89 left a reply on Create Login Expiration Realtime Countdown

Use vue with something like this:

new Vue({
  el: '#app',
  data: {
    time: ''
  },
  ready: function() {
    var vue = this;
    setInterval(function() {
      vue.time = (new Date).toLocaleTimeString(); //set this to the proper time span
    }, 1000);
  }
});

See here for the date methods. Play around with it.

bastiaan89 started a new conversation Requesting Comments On This Solution For Localization

A project of mine required localization, and I figured that wouldn't be much of an issue. After looking around for a bit though, I realized there's more to it than meets the eye. In this thread I'd like to post the solution that I eventually came up with, and hope to hear on which points it can yet be improved.

The way of localizing would be to have the locale code as first URI segment. For this, I found 2 different solutions:

  1. Make the locale a route parameter using a group prefix of {locale}, and remove it from the route in middleware, as described here.
  2. Detect the locale from the first segment, and set the group prefix to this locale, described here.

I went for the first solution, because the second doesn't allow for route caching; the cache will contain a static locale. I've implemented it as follows:

Using the prefix parameter

In the RouteServiceProvider's map method, I added a prefix of {locale}. Now the locale is added as a route parameter. Based on this, we can set the application language, using route middleware 'localized', which is also added to this route group:

public function handle($request, Closure $next)
    {
        $locale = $request->route()->parameter('locale');
        App::setLocale($locale);
        return $next($request);
    }

Dealing with the extra parameter

We have localization functioning as long as the URI starts with a valid locale code. However, as it stands, every controller method needs to accept an additional parameter which it won't be using. Therefore, we remove this parameter in the middleware:

$request->route()->forgetParameter('locale');

Ensuring locale in the URI

Right now, if the locale is not specified, two things go wrong: first the locale is set to an invalid value, and second the controller method is receiving incorrect arguments (all shifted to the left, and missing the last). To ensure the locale will be there, we add an additional middleware PrefixLocaleToUri, but this time to the global stack rather than making it a route middleware:

public function handle($request, Closure $next)
    {
        $locale = $request->segment(1);

        if (!in_array($locale, config('app.supported_locales'))) {
            $segments = $request->segments();
            $locale = $this->getLocale();
            return redirect("$locale/" . implode('/', $segments), Response::HTTP_MOVED_PERMANENTLY);
        }

        return $next($request);
    }

What happens here is that we check if the first segment is a valid locale. If it isn't, we obtain a valid locale, then redirect to the same URI with the locale prefixed. Here is how we get this locale:

protected function getLocale()
    {
        $fallback = Lang::getFallback();

        if (Auth::check()) {
            return Auth::user()->locale ?: $fallback;
        }

        return session('locale', $fallback);
    }

So if the user is logged in, we get their personal locale setting (a column in the users table). For guests, we try to read the locale from the session, and use the default locale if nothing was saved yet.

This middleware has to be placed after the session middleware on the global stack to get the logged in user and session variables:

protected $middleware = [
        CheckForMaintenanceMode::class,
        EncryptCookies::class,
        AddQueuedCookiesToResponse::class,
        StartSession::class,
        PrefixLocaleToUri::class,
       ...,
]

Now we have a mechanism in place to ensure properly formatted URI's, and the locale is set automatically while controller methods don't need to worry about it.

Route names

There are still some issues to work out. When setting a prefix on a route group, all routes in that group will have that prefix prepended to their name. This is undesirable, especially if you have an existing application where the old route names are already used everywhere. To fix this, we're going to extend the ResourceRegistrar core class (which, among others, generates the route names) to remove the {locale}. prefix from all route names. This is done by overriding the getGroupResourceName method:

protected function getGroupResourceName($prefix, $resource, $method)
    {
        $name = parent::getGroupResourceName($prefix, $resource, $method);

        return $this->removeParameterPrefixesFromName($name);
    }
    protected function removeParameterPrefixesFromName($name)
    {
        // does the string contain {id}?
        if (preg_match('#\.?{[\w]+}\.?#', $name)) {
            // remove route prefix parameters e.g. {id}
            $name = preg_replace('#{[\w]+}\.#', '', $name);
        }

        return trim($name, '.');
    }

Using a regular expression, all parts in braces are removed from the route name. Register this class in a service provider like so:

$this->app->singleton(ResourceRegistrar::class, NoPrefixResourceRegistrar::class);

Generating url's

We're almost there, but there is one problem left. Routes still need a locale parameter, we just removed it from the current route, so their URI's look like {locale}/foo/{bar}. When generating a url using the route function, we'd have to supply the current locale every time in the parameter list, and that's not something we want. Instead, let's go back to the route middleware and set the locale in each route directly (below the line where you forget the locale for the current route):

foreach (app('routes')->getRoutes() as $route) {
        $route->setUri(str_replace('{locale}', config('app.locale'), $route->getUri()));
}

Now the route will be like en/foo/{bar}.

Storing the selected locale

Everything works now, and you are ready to refactor all your hardcoded strings into trans calls. However, since we are checking the user and session for a stored locale, we should also be able to set those. This can be done in a controller method:

public function setLocale($locale)
    {
        $currentLocale = App::getLocale();

        if (Auth::check()) {
            Auth::user()->setAttribute('locale', $locale)->save();
        } else {
            Session::put('locale', $locale);
        }

        $previous = URL::previous();

        return Redirect::to(str_replace("/$currentLocale/", "/$locale/", $previous));
    }

This is what your language flag links should point to. The string replacement is done so that you're redirected to the newly selected language (the previous url has the old setting).

And there we have it! The locale is set in the background, without anything having to know about it. Unlike the two linked articles, all route names are kept intact and URL generation still works like it did before. There is just one last thing: since the route URI's are rewritten in route middleware, we first need to hit a route to make the rewrite happen. In Laravel's test cases, you may use route names to visit pages (I have a visitRoute method on my base test class) before any route is actually called. This breaks your tests, but can easily be fixed by adding $this->visit('/'); to the setUp method of your base test class.

Please let me know your thoughts on this approach, as well as any improvements you can come up with.

21 Nov
3 years ago

bastiaan89 left a reply on Cannot Find Module 'vueify'

Hmm, what if you try adding vueify to your own dependencies directly? Does that change anything? If not, I also don't really know, maybe you should raise an issue on the github repository?

bastiaan89 left a reply on Cannot Find Module 'vueify'

Did you also run npm install? Make sure the vueify folder is installed in the node_modules folder.

bastiaan89 left a reply on Cannot Find Module 'vueify'

Did you require laravel-elixir-vueify in your gulpfile? Can you show your gulpfile?

19 Sep
3 years ago

bastiaan89 left a reply on Use Arguments In Query

You should just pass the $args parameter directly to the select method, as it accepts an array or multiple arguments, but not a single string containing all the columns.

30 Jun
4 years ago

bastiaan89 left a reply on Using Eloquent Decorators Over Services

The second sample isn't really a decorator pattern though? The idea would be that you have several classes implementing the same interface, which take another object implementing that interface, and add their own logic in the method that the interface requires.

08 May
4 years ago

bastiaan89 left a reply on Not Sure Of Correct Way To Access Relationships

See "Eager load constraints" here. To combine results, you can merge the collections like

$combined = $department->employees->merge($department->contractors)
07 May
4 years ago

bastiaan89 left a reply on How To Split Line Of Texts(two Or More (using End By Dot In The Same Line)) And View As A List Item In Template Laravel 4.2

In your code, $m is the eloquent model, not the text you need. That would be $m->materials judging by your database example.

bastiaan89 started a new conversation Generated URLs In Queued Emails

Today, I came across a rather nasty side effect of using a queue to send email. A while ago, I changed my email system to use a queued command instead of Mail::queue() because the latter doesn't properly serialize models. However, as I found out today, wherever link_to() is used within a view, the result is a localhost link being sent out to users of the live website, because the view isn't rendered until the job is processed on the queue, which happens on the console, and the base url becomes localhost.

For now, I've taken all link_to() calls out of the views and pass those as variables to the view, so that the links are generated with the proper base URL. Is there a cleaner way to go about this?

bastiaan89 left a reply on Not Sure Of Correct Way To Access Relationships

Why would you need a polymorphic relation? That's used if one entity can be owned by different other entities, but in this case it's the other way around. I would just add a department_id to both contractor and employee.

03 Apr
4 years ago
01 Apr
4 years ago

bastiaan89 left a reply on What Are Services?

The best way to go is to develop a pattern you'll follow in the life-time of the project ans stick with it.

Definitely this. What I often see (and also sometimes catch myself doing) is people trying too hard to adhere to all kinds of patterns and practices, and not seeing a better/simpler way because of this.

bastiaan89 left a reply on How To Execute Laravel 4.2 SQS Queue From Code?

First, you should set up the failed jobs table, or else your log files will grow to gigabytes if jobs fail (I've been there :p).

Now, for the queue, you should have the artisan queue:listen command running constantly (and use something like Supervisor to keep it running). In Laravel 4, you also have to manually delete the job from the queue using $job->delete() at the last line of your closure. Are you sure that part is being run?

bastiaan89 left a reply on What Are Services?

If you prefer doing it in the repository itself, by all means, do just that. Isn't that the entire purpose of the repository, to have a way to store data in a format of your choice?

bastiaan89 left a reply on How Can I Achieve A Effect Like This On Bootstrap 3?

Doesn't Bootstrap have that out of the box? (the main navigation thing)

bastiaan89 left a reply on What Are Services?

I may be wrong on this, but I consider Commands to be services as well. Also, if you want to use Events instead, that's perfectly fine. I personally put what I consider to be a core part of the operation (registering in this case) in the command, and side effects in event handlers.

@pmall Yeah of course, I didn't mean to correct you, but ironically I also found it a good example of when a separate service class would be overdoing it :p

bastiaan89 left a reply on What Are Services?

One side note though, don't take these patterns and best practices too far. In some cases, it's no big deal to have some extra logic in one place if there's likely not gonna be another place where you need it. An example would actually be the above post, if you're gonna have separate classes for every bit of logic in your application, it'll become a mess as well. Others may disagree, but I find m1.multiply(m2) to be more readable than MatrixOps::multiply(m1, m2). It also depends on whether you think the logic is gonna change at some point (your user registration process just might, but matrix multiplication will be the same forever).

bastiaan89 left a reply on What Are Services?

You could implement the registration in the repository if all you're doing is simply creating the new user with the request data. However, you'll often have more stuff going on when registering, such as sending a welcome email, or setting up billing. The repository should only be responsible for storing the user, not the other things, so that's where the registrar would come in.

A typical workflow would be to have the Registrar depend on several other services (Mailer, Repository, etc), then call those from within the Registrar::create method (referring to the interface here). The idea is that the Registrar knows what should be done to register a user (store in database, send mail, bill credit card), however it shouldn't know how. That's the responsibility of the other services. Likewise, the controller doesn't (and shouldn't) know how to register the user, but just pass data to the Registrar and tell it to register.

bastiaan89 left a reply on Authentication Using Email/psswd If Email Field Encrypted In Database?

Encrypted values can be decrypted if you have the key used for the encryption. Hashed values cannot be decrypted, the only way to figure out what the original was would be to try all possible combinations (with a good hashing algorithm, that is).

The reason that hashing the same value twice will yield different results, is that the hashing function will generate a random string, used as the 'salt'. The input value is combined with the salt, then hashed together for the output. The output will then contain information about the hashing algorithm used, as well as the salt, so that if you want to check whether a password is correct, you use the salt from the database instead of a random string, and the result will be the same.

bastiaan89 left a reply on What Are Services?

A service is basically just a class that handles one thing (single responsibility), so that the functionality that the class provides, can be reused in multiple other parts of the application. The Registrar service included with Laravel is responsible for registering new users, for example.

There is no need to extend any core classes, you can just create one and type hint it in controllers for example, so that it'll be resolved out of the service container.

bastiaan89 left a reply on Authentication Using Email/psswd If Email Field Encrypted In Database?

['email' => Crypt::encrypt(Request::get('email')] in your Auth::attempt() array?

bastiaan89 left a reply on Get Table Values Using Eloquent Model In Laravel5

The PostTag class should have the method like so:

 public function posts() {
       return $this->belongsToMany('App\Post');
 }

For a many to many relationship, use $this->belongsToMany() in both models.

bastiaan89 left a reply on Fatal Error: Class 'Illuminate\Foundation\Application' Not Found In /path/to/project/bootstrap/app.php On Line 14

That shouldn't impact your development environment, because with APP_DEBUG=true, you're not using the compiled file anyway. Have you tried running composer dumpauto?

bastiaan89 left a reply on Eloquent Repository

That's the underlying Monolog\Logger class only accepting an array. If you're always returning a Collection, then it'll work just fine to call the toArray() method on it as described by @rodrigo.pedra.

31 Mar
4 years ago

bastiaan89 left a reply on Is It Possible To Push Application Direct To Server Without Creating Repo On Github ?

If this is about GH not having free private repositories, try BitBucket (free private repos for up to 5 users).

bastiaan89 left a reply on How Should I Write This Test

What kind of input field does tier_list have?

30 Mar
4 years ago

bastiaan89 left a reply on Thoughts On DB Schema For A Discussion / Question-Answer Forum

Well you can use 2 migrations, but don't set the foreign key constraint on threads before creating posts. In the same up method for the posts table, do a Schema::table to add the foreign key to threads.

bastiaan89 left a reply on Thoughts On DB Schema For A Discussion / Question-Answer Forum

I think you should use set null on delete instead of cascade? Like this, if the answer post gets deleted, the entire thread will be deleted as well. Not sure if that's the problem though, try running show engine innodb status\g in mysql. In there, there's a section "Latest foreign key error" with more details about the issue. Also, make sure you have created the posts table first. If the tables have foreign keys of each other, you'll have to drop one of those and make it a regular integer.

bastiaan89 left a reply on How Should I Write This Test

So it is a single text field where you can either enter an existing ID or a new name? Could you share the back end code that handles this form?

Also, I see you're creating a new item with TestDummy but then creating another item with the same name through that form? If you just need dummy attributes use TestDummy::attributesFor().

bastiaan89 left a reply on How Should I Write This Test

The tier_list input field is probably a select. Your text input field probably has a different name?

bastiaan89 left a reply on Thoughts On DB Schema For A Discussion / Question-Answer Forum

Well there's a slight difference in that I wouldn't store the body on the Post model, but instead have an opening_post_id field and create an accompanying Reply (which is the first post). That way it's easier to grab the collection of all posts. However it is a bit more hassle, so go with whatever feels best to you.

bastiaan89 left a reply on Adding A Subquery To An Eloquent Query

So if I understand correctly, an item has many places, and a place has many participants. For this, you can use a HasManyThrough relation on the Item model: http://laravel.com/docs/5.0/eloquent#has-many-through

bastiaan89 left a reply on Thoughts On DB Schema For A Discussion / Question-Answer Forum

@mstnorris Why separate tables for the posts and replies? Another way you could do this is to have threads and posts tables, where the thread contains the title, type and answer id, and post just the body and thread id.

bastiaan89 left a reply on Thoughts On DB Schema For A Discussion / Question-Answer Forum

You're probably best off keeping a single table for both kinds of posts, then a nullable 'accepted answer' column. Here on LC, there's no distinction between regular posts and questions, but if you want that, I'd go for either a boolean column (is_question) or, if you want more types in the future, an additional post_types table.

Regarding the likes, I implemented this myself with a pivot table (user/post), so you can keep track of who liked what.

29 Mar
4 years ago

bastiaan89 started a new conversation Global Scopes On Polymorphic Relations

Hey there,

Most of my models have an "approved" boolean property. Using a global scope, only rows with approved=true are retrieved. However, I'm currently refactoring the approval process to use a single table where unapproved items are referenced by their class and ID, using a polymorphic relation. This table is represented by the Approvable model.

Now, a problem arises when I want to grab all unapproved items. What I currently have is

$unapproved = Approvable::all()->map(function(Approvable $approvable) {
        return $approvable->subject()->unapproved()->first();
});

The Approvables' subjects are all null because they aren't approved (well duh). Here I use map to override this behavior for each subject. But I have a feeling there should be a better way (for example, there's a query for each row now)?

Edit: I've decided to skip Eloquent relations, and build an associative array with the model class as key, and an array of id's as value. Then, looping over that array, fetch the items for each model and merge them all in a Collection. If there's a better way, I'd still love to hear it though!