Member Since 5 Years Ago

Experience Points 20,875
Experience Level 5

4,125 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 385
Best Reply Awards 1
Best Reply
  • 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.


    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.


    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.

06 Oct
3 years ago

rleger left a reply on Model HasManyThroughMany Relationships

Thanks for your reply,

Yes, That's why I created a pivot table with 3 pivot keys



It's actually not a pb to do this manually, I added a "where" clause to the diagnostics method on patient that allows me to pass the patient id


(actually I've done a bit more, the diagnostic method on patient dispatches either to a diagnosticForPatient method if it detects a pivot property (meaning we called from intervention) or to the regular belongsToMany call if not).


$patient->diagnostics would differ to the standard way
$intervention->patients()->first()->diagnostics would hit "diagnosticForPatient" where there is a where('patient_id', $pid) clause. $pid coming from the pivot data

it's ugly but it works

my pb is that I would like to define that in a clean relationship to be able to use it with Fractal or Dingo (which uses Fractal) like so


And to my knowledge this can only be achieved by having the proper relationship in place. Right now it returns all the diagnostics of a patient on each of its interventions. Which makes sens...

rleger started a new conversation Model HasManyThroughMany Relationships

Hi everyone,

I'm trying to figure out a model relationship issue. I'm building an app that needs to record ambulance interventions.

An intervention hasMany Patients (and a patient can belong to many interventions) A patient hasMany Diagnostics (and a diagnostic can belong to many patients)

So a patient may be involved in different interventions, I must be able to retrieve patient diagnostics (all the diagnostics regardless of which intervention it happened in) but also - and that's my problem - only the diagnostics for that patient on that intervention.

My pivot table are defined as followed :




right now I have a many to many relationship between interventions <-> patients and between patients <-> diagnostics

I made it work this way : my patient model has a diagnostics method that checks wether I'm calling from the patient model (I want all diagnostics regardless of the intervention) or if I'm calling from an intervention in which case I should only get the diagnostics for that patient on that intervention by using an ugly where method. I do this by checking if the $this->pivot is set and retrieve the intervention_id from it... Hacky but it works except when I use it with Fractal/Dingo to get nested relationships. If I want to get the interventions and include patients and patients.diagnostics it will spit out all the diagnostics for a patient regardless of the current intervention. Basically when it hits my patient model it fails to see I'm calling 'from' my intervention model because there is no Pivot table.

I need to represent (InterventionPatient) as en entity, I event toyed around with defining it as a model but it created more problems than it solved.

I've been struggling with this for a bit but I can't find a way. I can't use hasManyThrough because they're both many to many relationships.

Basically I need hasManyThroughMany .. :)

I thought doctrine might have what I need... lets hope not, I really don't want to rewrite everything :)

Thanks for your inputs

22 Sep
3 years ago

rleger left a reply on Material Theme Edited For Facebook Color Scheme

Thanks for this.

I have a pb though some colors don't get updated from the original material theme : http://d.pr/i/3WtZ

Any idea ?? I'm using Colorsublime for the color theme and I've installed material theme in a "Packages/Material Theme" folder


07 Sep
3 years ago

rleger left a reply on UUID

I'm trying it now it seems to work well. I'm not storing the obfuscated id in the DB either, I simply use it to encode ids before the api responds and decode it before performing db queries. That way no one sees the real id, even via chrome inspector ;)

It lacks a bit of documentation on how to choose your settings on the config files ('salt', 'lenght', 'alphabet') although yo can guess what it does.

Seems like a good enough solution for my needs. Thanks for your feedback

rleger left a reply on UUID

Tiny is great but it lacks a laravel 5 service provider and facades for now.

This one looks great too : https://github.com/vinkla/hashids

Anyone has any thoughts on it ?


rleger left a reply on UUID

Thanks for your replies,

I'm not working across multiple servers, my app is basically a front-end javascript FW consuming a Laravel API.

What I need really is more to obfuscate ids. I'm handling sensitive data and even though I've implemented a permission system that prevents users to perform an action that's not allowed I think it'd be wise to obfuscate ids to prevent a "smart ass" changing ids to access something...

@ohfss : I've actually heard about tiny, that might be what I need.

@deringer : thanks for that I will check it out

I'm really concerned about the performance hit. I might choose to implement it only on selected sensitive tables. I have a lot of relationships between my models and using an id obfuscator on all will probably slow things down a lot.

Thanks @Ruffles I've read that post from @philsturgeon as well as his book "Building API you won't hate" and it's kind of the reason why I though it might be wise to do something about it.

On the other hand, I've noticed that Taylor himself is not obfuscating id in envoyer.. Am I overthinking this..?

In the end, my app (medical app) is for professionals only, it will only run internally inside a LAN. So not the biggest exposure ever.

Thanks for your inputs, I'll let you know if I come across something interesting on the matter.

06 Sep
3 years ago

rleger started a new conversation UUID


I would very much like to see a series on using UUIDs. I've been on edge of starting to use it on a particular project but it seems a bit scary to make such a big change.


30 Jul
4 years ago

rleger started a new conversation Add Custom Section To A Resource


I'm using Fractal for my api. I'm trying to include a custom section on my response that would be appended to my collection and give me some stats about the response.

An example : If I'm getting messages, I currently get a response with messages and pagination, great... But I can't figure out is how to append a customized section that would give stats about my messages (read, latest...).

To get something like that :

"messages" : [ {...}, {...}, ....],
"pagination": {...},
"stats": {
        "unread" : 3,
        "whatever": 5,

Do you have any idea on how to handle that ??

Thanks !

22 Jul
4 years ago

rleger left a reply on [L5.1] Model Factories And Relationships

Same here, can't find a proper solution.

Did anyone come up with something ?

22 Jun
4 years ago

rleger left a reply on VueJs And Browserify With Elixir

Great !! thanks for that, updating elixir solved it. Its not the best workflow I could have imagine but at least each page only loads what it need. Thanks !

21 Jun
4 years ago

rleger left a reply on VueJs And Browserify With Elixir

Yes I think I'll do that. Can't find a nice way to organize all this nicely. Thanks for your help anyway

rleger left a reply on VueJs And Browserify With Elixir

It does but it seems the latest call takes precedent. with

mix.browserify('vue-interventions.js', 'public/js/vue-interventions.js');
mix.browserify('vue-users.js', 'public/js/vue-users.js');

I only get a vue-users.js file

while with :

mix.browserify('vue-users.js', 'public/js/vue-users.js');
mix.browserify('vue-interventions.js', 'public/js/vue-interventions.js');

I only get a vue-interventions.js file

rleger started a new conversation VueJs And Browserify With Elixir

Hi everyone,

I'm building a project with vuejs that consumes a laravel API. I use laravel for routing and stuff.

I'm trying to figure out the best workflow with elixir and browserify to load all that.

Right now the best I could come up with it this :

my master.blade.php loads the bundle.js file made by browserify

Elixir processes a vue-app.js file that contains the following :

var Vue = require('vue');
var vueResource = require('vue-resource');

Vue.http.headers.common['X-Requested-With'] = 'XMLHttpRequest';

if(document.getElementById("v-users")) {
    var vue_users = require('./vue-users.js');
    new Vue(vue_users());

if(document.getElementById("v-interventions")) {
    var vue_interventions = require('./vue-interventions.js');
    new Vue(vue_interventions());

Then on each page I want to use vue with I have a main div with #v-users and so on.

It works fine, is kind of modular BUT as you've seen every page loads a handful of javascript it doesn't need.. the v-user.blade page will load v-interventions and such... I guess in the long run this could lead up to a pretty big bundle.js file.

I thought about having a script tag at the end of every page that includes just the necessary file it needs but elixir compiles everything to bundle.js ...

otherwise I would have done :


How do you handle that??


06 Jun
4 years ago

rleger left a reply on Vue Js


 this.$http.headers.common['X-Requested-With'] = 'XMLHttpRequest';

inside the Vue object before the ajax call seems to do it

rleger started a new conversation Vue Js

Hi everyone,

I'm using vue-resource to handle loading data from a laravel api. I'm trying to handle the case when the user is not logged in. The trouble is : it redirects to the login page rather than send a 402 response I could deal with from the js.

Laravel does not pick up the fact that the request was made from ajax, I guess its a header problem. The header X-Requested-With should be set to XMLHttpRequest but its not. I hunted that down from the auth middleware.

Does anyone know how to do so with vue-resource ? The documentation is very poor and I couldn't find the answer elsewhere.


31 May
4 years ago

rleger left a reply on Nb Of SQL Queries When Running Tests

OK this will do for now

$n = 0;
Event::listen('illuminate.query', function($sql) use(&$n) {
    if($n > 10 && config('app.debug')) {
        session(["test_warning" => "High number of SQL queries ($n)"]);

And testing :

$this->assertFalse(session()->has('test_warning'), "There is a warning [" . session()->get('test_warning') . "]");

And you know what, I just caught another one :) Thanks for your help !

rleger left a reply on Nb Of SQL Queries When Running Tests

Yes I was aware, that's what I used to do until I found out about debug bar.

ok don't throw rocks at me it's as ugly as it can be, but you get the idea .... on top of the routes file

$n = 0;
Event::listen('illuminate.query', function($sql) use(&$n) {
    if($n > 20 && config('app.debug')) {
        var_dump("High number of queries");

At least you get an alert on the views with high queries.. Then I can write a test that I don't see "High number of queries"

rleger left a reply on Nb Of SQL Queries When Running Tests

Not especially with the N+1 issue.

For instance I've created a class that handles user permissions. When I display an index view of the users I want to display an update and delete buttons only if the logged in user has permissions to perform the action on each particular user.

The rules are complex (they need to have a users.update.all permission or have user.update.self and be that user.. and so on, I'm using $user->role->permission->shortname for that. They also need to have a permission 'level' stored on $users->role->level higher than the one of the target user.

Anyway, the system is working well and giving me the flexibility I need, but it uses many relationships and can create N+1 issues if I'm not careful.

What I just found out is that I was passing $user->id from my view to test if the particular user should have update/delete buttons for that logged in user. The method receiving this detects it as an id and fetches the user with that id. It can also simply receive the user instead (I want to have some flexibility) and since it is properly eagerloaded .. no N+1 issue.

But all that is beside the point, I would like some tool to be able to automate that and make sure I don't overlook some massive query load (easily fixable by the way).

rleger left a reply on Nb Of SQL Queries When Running Tests

Debugbar does the same thing in that regard. I ended up removing clockwork as it created 700Mb+ of data in my storage dir. I prefer debugbar anyway. Anyway, those are great tools but they don't offer automation. You have to manually visit every route to check ou the number of queries run. I would have liked to have that in my PHPUnit tests for instance.

rleger started a new conversation Nb Of SQL Queries When Running Tests

Hello everyone,

Do you know any way to monitor the number of sql queries when running tests.

I discovered (via debugbar) a very high number of queries where run on a specific route due to a bad strategy (taking 300+ queries down to 6 just by passing $user instead of $user->id..).

Point is, I would have liked my tests to pick up on that and alert me...

Thanks !!

23 May
4 years ago

rleger left a reply on Modifying The Http Request For Checkboxes

Thanks for your replies, we're obviously in different timezones ;)

@sitesense good idea to put it in the view, you could imagine a small JS to dynamically update the hidden field. Although it would start to feel a bit like a house of cards. Defaulting to zero is only good enough for creation of a record but not if you want to be able to update it.

@jekinney so your doing the "checkbox" check logic in the repository using the request. But, you still need to know which checkbox fields to check against, so I guess you put that in your repo. And personally I'd rather have the repository receive an array which is more agnostic. I feel the handling of the Http Request should stay in the controller. Still $request->has does nothing more - in this context - than the little helper function we talked about earlier.

What troubles me is that it seems like request would be a good place to put the logic of checking whether the box was selected or not. Putting it in controllers or repositories doesn't feel quite as right to me.

Wondering why there isn't an 'official' way to do it, after all it is rather trivial to be able to update a form after unchecking a box.

22 May
4 years ago

rleger left a reply on Modifying The Http Request For Checkboxes

Thanks @bashy. I actually would like to be able to do this inside the Request child class (like CreateUserFormRequest) and remove it from the controller. I can't do ($this->merge([..])) it in the Request constructor because I guess it's not initialized yet. I could use the authorize method, but it's not really the right place to put it... any thoughts

rleger started a new conversation Modifying The Http Request For Checkboxes

Hello everyone,

I'm trying to find a simple way to update a form with checkboxes. The problem is that as you know unchecked checkboxes will not be sent in the request. I've seen some people approaching the problem with hidden fields but I don't like it.

What I'm doing is checking if the request contains a checkbox field, if so, set it to true, otherwise to false.

For now I'm doing this in my controller. I have a checkbox property that contains every checkboxes in the form

protected $checkbox = ['checkbox_field']

I've created a method in my Controller class (extended by every controllers) :

 protected function prepareFormInput(array $input)
        // Process checkboxes
        foreach ($this->checkbox as $field) {
            $input[$field] = array_key_exists($field, $input) ? 1 : 0;

        return $input;

So before I pass the inputs to my repository for creating or updating I do this and pass in $input :

$input = $this->prepareFormInput($request->all())

BUT... to the point : I'd like to be able to do this from the request object directly !

I thought about having the method in App\Http\Requests. Then it could be fired automatically if a $checkbox property is set on the specific child request like CreateUserFormRequest.

BUT.. I can't find out how to modify the request attributes... I've looked around but couldn't find an answer..

Any thoughts ? how are you handling unchecked checkboxes.

15 May
4 years ago

rleger left a reply on Testdummy Multiple Records With Times

just found out that putting the factory in a closure solves it...

$factory('StatSMUR\Diagnostics\Diagnostic', function() use($faker) {
    return [
        'shortname'   => $faker->unique()->word,
        'name'        => $faker->word(2),
        'description' => $faker->sentence(8),

so I guess it has to do with the $faker instance ?

rleger started a new conversation Testdummy Multiple Records With Times

I can't figure out how to get a number of different records with Testdummy :

I'm doing this :


I get 3 identical records when I actually would like to get three different ones. This is my factory :

$factory('Model', [
    'shortname'   => $faker->unique()->word,
    'name'        => $faker->word(2),
    'description' => $faker->sentence(8),

Any idea how to achieve that (without using an external for loop). ?

Thanks for your help

12 May
4 years ago

rleger left a reply on Sublime Text Sidebar Styling

There you go : I found this : https://github.com/markhuot/sp... which has everything bundled but doesn't quite work as expected (weird folder icons). Couldn't find the issue.

So what I did is (quick and dirty) :

I installed Spacegray from the untouched repo : https://github.com/kkga/spaceg.... I copied everything from here https://github.com/markhuot/sp... in the folder

Worked like a charm.

I zipped it in case anyone is interested : http://cl.ly/1Y271T2r1B2k

(copy from my answer here there) : https://laracasts.com/series/intermediate-laravel/episodes/1#comment-2007131465

05 May
4 years ago

rleger left a reply on Important Elixir Folder Change

I always found the old structure a bit inconsistent in that regard. Nice update, thanks.

02 May
4 years ago

rleger left a reply on [Not Laravel Specific] Should I Restrict Gallery Images To A Certain Size.

+1 for glide, great package. Handles image caching so they don't need to be generated over and over again.

Personally this is how I do it : I store the images that are uploaded to an originals folder. I allow a fairly large picture to be uploaded. When the image is uploaded it gets resized to a standard size and format to a "processed" folder.

The rest of the application uses images from the processed folder that I know won't be too large. I use glide to make the final size, format, quality.. adjustments at the last minute. But now, if apple ever comes up with 10K screens :) I can "reprocess" the images from the originals folder with maximum quality.

Definitely not perfect but that's the best compromise I could come up with.

01 May
4 years ago

rleger started a new conversation Where To Store App Data Using Envoyer

Hi everyone,

I'm using envoyer with a L5 application. The application allows users to upload images and files (amongst other things). I currently store the uploaded resources in public/resources/directoryStructure

I've excluded the folder from git.

But as expected when I push a new version, envoyer removes the folder and sets up a clean clone of the git repo.

Question is : where should I store those application resources. I thought about the storage directory which is left untouched by envoyer, but then I will run into trouble accessing the images from the application to display them for instance. I try to respect the fact that anything public should be in the public directory.

Anyway this seems like a rather trivial situation, how do you handle it ?

Thanks a lot !

29 Apr
4 years ago

rleger left a reply on Eager Loading Sorting By Linked Column

@pmall Thanks ! works great, I was hopping to be able to do this on the model though, maybe even with some eloquent magic. Since I always want this collection sorted that way and with that linked model, I thought it made sense to define it once and for all in the model. I'm using repositories so I guess I'll throw it in there... Could you elaborate on why 'with' is bad on the model ? I'm doing this "a lot" since I wanted to avoid defining relationships on the repository or in the controller...

I used to do this :


but I thought it had nothing to do there... and the syntax gets really ugly if you throw on pagination.. I've been struggling to find a good place to define where to eagerload relationships.

@JarekTkaczyk thanks, will definitely check out your extension.

rleger started a new conversation Eager Loading Sorting By Linked Column

Hi everyone,

I'm trying to figure out how to eager load data and sort them at the same time. Using Laravel 5.

I have a model A which belongs to many B which belongs to C.

A - B - C (sort_index)
    B - C (sort_index)
    B - C (sort_index)

A - B - C (sort_index)
    B - C (sort_index)
    B - C (sort_index)   


I'm trying to retrieve A with B and C eagerloaded, easy so far. But I'd like to get B sorted by a column sort_index found on C.

I'm getting the collection like so :


in the A model I have :

return $this->belongsToMany('B')->with('C');

in the B model I have :

return $this->belongsTo('C')->orderBy('sort_index', 'ASC');

Just to be explicit, what I want it to get the B records to be sorted by the C.sort_index

I've tried a couple different solution but none of them work. I guess I could sort the collection afterwards using sortBy and a callback but it's not very elegant. I'd rather define the sorting order in the model.

I get why it doesn't work, and that orderBy('sort_index') is actually not helpful on model B. But I can't figure out how to make it work

Thanks a lot for your help !


21 Apr
4 years ago

rleger left a reply on How To Customize The Elixir TDD Monitor Path?

phpSpec does have a src argument optional but my problem is that the watcher doesn't pick up on that new path.

I use phpspec and my spec are in tests/spec/

I'm using :


which works fine for the classes under test but when I change a spec test class the tests don't run.

I thought something like

mix.registerWatcher("phpSpec", "tests/spec/**/**");

might work but it doesn't.

any thoughts ? Thanks !

04 Feb
4 years ago

rleger left a reply on Homestead MySQL Connection Error: SQLSTATE[HY000] [2002]

I don't understand what I could possibly have done wrong. The hosts file is rather simple to get right.. I've followed homestead install steps.. weird.

I had a similar problem at some point with an earlier version of L5 but it was gone...

Thanks for your help anyway

rleger left a reply on Homestead MySQL Connection Error: SQLSTATE[HY000] [2002]

Yes I've used "telnet ip_address port" on the terminal

rleger left a reply on Homestead MySQL Connection Error: SQLSTATE[HY000] [2002]

I tested the addresses and port. Only and localhost:33060 worked

don't know what to make of it though Just for info I do use to "map" the domains in my hosts file.

Thanks !

02 Feb
4 years ago

rleger left a reply on Homestead MySQL Connection Error: SQLSTATE[HY000] [2002]

I like to run things outside the vm as its much faster (beaht, migrations...) I'm trying to be able to run commands using the db inside and outside the vm without changing host every time I go from one to the other.

I'm pulling my hairs out with this..

DB_HOST=  works outside the vm (and not in !)
DB_HOST=localhost works inside the vm (and not out !)

I've also added DB_PORT=33060 and defaulted to 3306 on database config file

'port'      => env('DB_PORT', 3306),

Does anyone has a clue on how to work around that ? It seems like a recurring problem, I found many topics on the subject but no solution.

rleger left a reply on PDO Connection Refused With Laravel, But Not With $con = New PDO()

Yes but it will break on production you might want to have the port set on the .env file



'port' =>  env('DB_PORT')

on the config file

actually you might want to default to mysql standard port

'port' =>  env('DB_PORT', 3306)
24 Jan
4 years ago

rleger left a reply on Use Homstead When Using A Proxy

Thanks for your reply TerrePorter, unfortunately I've already done that. This is where I've put : .local, 169.254/16, 172.16.,, .app, 10.0., 192.168.*, localhost

thanks anyway.


23 Jan
4 years ago

rleger started a new conversation Use Homstead When Using A Proxy


I have a problem accessing my local sites on Vagrant Homestead when I'm at work (behind a proxy).

I'm on mac. When I'm using a network setting with no proxy everything works very well. When I switch to a network setting that has http and https proxy set up it doesn't work (the page loading stalls).

I have set the following exclusion list on my network settings : .local, 169.254/16, 172.16.,, .app, 10.0., 192.168.*, localhost

... but it doesn't change a thing.

My Homestead.yaml file is rather standard, so as my Vagrantfile. I have set hosts in /etc/hosts to

ip: ""
memory: 2048
cpus: 1

authorize: /Users/me/.ssh/id_rsa.pub

    - /Users/me/.ssh/id_rsa

    - map: /Users/me/Sites/mysite/
      to: /home/vagrant/Sites/mysite/

I've looked around but couldn't find a solution. It's quite annoying having to back to a network setting that doesn't use a proxy whenever I need to access my local sites.

Any idea ??

Thanks a lot for the help


28 Nov
4 years ago

rleger left a reply on Custom Laravel 5 Validation Rules

Ok. If I get it right extendImplicit will run even if no inputs are provided for the field when extend will only run if one is.


rleger left a reply on Custom Laravel 5 Validation Rules

it works when using the extendImplicit method although I don't really understand the difference

  $factory->extendImplicit('test', function ($attribute, $value, $parameters)
                // return logic test
            'Bad number format'

rleger left a reply on Custom Laravel 5 Validation Rules

Thanks!!! I missed it.

Still I can't get any one working, extending from the FormRequest Constructor or creating a separate file that will be loaded through a service provider.. am I missing something or did it change since that commit..

Starting to pull my hair on this.

Pretty straight forward though ...

use Illuminate\Validation\Factory; class AnswersFormRequest extends Request { public function __construct(Factory $factory) { $factory->extend('test', function ($attribute, $value, $parameters) { return false; }, 'Bad number format' ); } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ "ville" => "test",

The validation passes !!

rleger started a new conversation Custom Laravel 5 Validation Rules

Hi everyone,

I'm looking to create a custom validation rules with larvel 5 to use within my FormRequest. Specifically a require_if_not rule.

to do something like :

public function rules () {
return [
"aField" => "require_if_not:someOtherField,hasSomeValue",

I've looked at a few options and none does the job how I want it to.

This thread comes close but it actually performs some more checks after the validation passes and I'd like to implement a rule rather than hardcoding checks afterwards. https://laracasts.com/discuss/channels/general-discussion/custom-validation-function-in-laravel-5

Of course larvel 4 validation extension would do the job exactly as I would like, but I can't seem to translate it for L5. (http://culttt.com/2014/01/20/extending-laravel-4-validator/)

Any thoughts ?

Thanks !

05 Oct
4 years ago

rleger left a reply on Validator Custom Rule (laravel 5)

like so :

class ValidatorExtender {

    private $validatorPrefix = 'Validator';

    public function __construct()
        foreach(get_class_methods($this) as $method) {
            if(substr($method, 0, strlen($this->validatorPrefix)) === $this->validatorPrefix) {
                call_user_func([$this, $method]);

    public function ValidatorPassCheck()
       // ...

ugly but you get the idea

rleger left a reply on Validator Custom Rule (laravel 5)

Ok, I thought I'd create a ValidatorExtenderServiceProvider that would instanciate a ValidatorExtender class.

    public function boot()
        new ValidatorExtender();

On the ValidatorExtender class, the constructor would execute any method beginning with 'Validator', so you could easily add a new extension rule.


protected function ValidatorPassCheck() {

  // Validation extension code for passcheck

Sounds good ??

rleger started a new conversation Validator Custom Rule (laravel 5)

Wondering where is the best place to put my validator custom rules... as it currently shamelessly sits on top of my routes file :)

ServiceProvider ?, app/Validator.php loaded via composer ??

Any thoughts ?

Validator::extend('passcheck', function ($attribute, $value, $parameters)

rleger left a reply on Implicit Controllers And Laravel 5

So there is no shorter way than this for now right ?

get('/auth/login', ['as' => 'login', 'uses' => 'Auth\AuthController@getLogin']);
post('/auth/login', 'Auth\AuthController@postLogin');

get('/auth/logout', ['as' => 'logout', 'uses' => 'Auth\AuthController@getLogout']);

(not using get and postRegister methods)