boneill81

boneill81

Member Since 3 Years Ago

Experience Points 4,110
Experience Level 1

890 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 21
Lessons
Completed
Best Reply Awards 1
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.

10 May
1 week ago

boneill81 started a new conversation FormRequest $validator->after() Times Out

Hi Guys, Can anyone point me in the right direction as to why I am witnessing the behaviour below? In my form request I want to execute a function to do some formatting of attributes once the request has passed. But I have run into unusual behaviour which I cannot seem to pin down. The below code is executed within the withValidator function on my FormRequest. I just can't see anything in the logs/docs that points me towards why this is happening and believe me I have searched extensively.

    ```PHP
//This works and logs 'Hello'
$validator->after(function ($validator) {
        Log::info('Hello');
    });

//This timeout, it seems the addition of the passes() function causes this
$validator->after(function ($validator) {
        Log::info($validator->passes());
    });
```

Thanks.

01 May
3 weeks ago

boneill81 started a new conversation $request->request->remove() Not Working Within FormRequest

Hi Guys, Perhaps I am missing something but I am stumbling upon something which on the face of it should be relatively trivial. If two conditions in the prepareForValidation() of my FormRequest are met then I want to remove a specific parameter from the request. Elsewhere in a controller I use $request->request->remove('parameter_name') and the parameter is removed without issue. However from within the FormRequest if I execute $this->request->remove('parameter_name'), it executes without issue but a Log::info($this) run immediately after still shows the parameter. Any ideas on what I am missing here? Thanks.

05 Feb
3 months ago

boneill81 left a reply on Access Auth::user() Anywhere In App Once Authenticated/optional Authentication

Some further information for all in case anyone would like to chime in with a similar experience. I mamnaged to track this down to an issue specific to FireFox. The same urls from Chrome work just fine. I restarted the Firefox browser in safe mode and it worked. The weird thing is I don't have anything strange installed which would interfere with the sessions in theory. I checked the cookie data and the laravel session is being stored but crucially the login_web_### entry is lost in normal firefox and thus the user() methods return empty.

04 Feb
3 months ago

boneill81 left a reply on Access Auth::user() Anywhere In App Once Authenticated/optional Authentication

OK, I restarted all again and am stumped. I have now been able to reproduce this on both dev and production. If I log in and then access the route with the auth middleware specified the route without the auth can Log the user.

But If I send the exact same request direct to the search route, which is the same code, same method, same everything, Auth::user() returns empty.

No idea what's going on, I will have to try and keep digging deeper.

boneill81 left a reply on Access Auth::user() Anywhere In App Once Authenticated/optional Authentication

@REALRANDYALLEN - No not in the constructor, in the search() method itself. Tis a strange one to be sure. I just ran loads of tests on my dev environment which is a 1:1 mirror of production and it works fine. The only thing I can think of is some sessions left hanging around or something. I was just after upgrading to Laravel 5.7 from 5.6 without issue. Had cleared all cache, restarted apache and cleared opcache. But no way would it show me the user from the direct call to search route. But when accessed via the browser route it was working fine. On the dev environment both work just fine. I will try again in the morning and will perhaps restart all again later to see whats amiss. I will report back tomorrow. Thanks again to you all for the help.

boneill81 left a reply on Access Auth::user() Anywhere In App Once Authenticated/optional Authentication

Sure thanks for the help.

The routes are as follows:

Route::name('record.search')->match(['get', 'post'], 'record/search', '[email protected]');

Route::name('stats.browser')->get('stats/browser', '[email protected]')->middleware('auth');

The controller snippet from record.search is as follows:

        if(Auth::check()){
            if(!Auth::user()->isAdmin()){
                $request->merge(['email' => Auth::user()->email]);
            }
        }else{
            $request->request->remove('email');
        }

If I access the search route directly then none of the AUTH code works and if Iog the user it returns empty.

However If I access stats.browser which calls record.search using AJAX then the AUTH code works and the user is logged correctly. I have given an hour trying to track down where things are going wrong but cannot see it.

Thanks.

boneill81 started a new conversation Access Auth::user() Anywhere In App Once Authenticated/optional Authentication

Hi Guys,

Perhaps I am misunderstanding something here but one aspect f Auth's behaviour is confusing me. I had expected to be able to user Auth::check() anywhere in my app once the user is authenticated much like in plain php where once a user is logged in then you can access their details via the session.

The reason I would like to do this, is that my app contains pages which will show some additional information if an authenticated user hits them but if not they will still load just without the extra information. Basically authentication is not required for these pages and just adds a little bit to them if the user is logged in.

However I noitice that Auth::user() returns null from these pages even though the user is logged in. Auth::user() works just fine if called from a page covered by the Auth middleware.

Is the Auth middleware required on a route even if all you want to do is use Auth::check() or Auth::user().

If that is the case then presumably the way to go it a custom middleware to handle optional authentication. Although this would seem to be rather unwieldy for something which should already exist in the session to begin with. Any advice or info appreciated.

Thanks.

25 Jan
3 months ago

boneill81 left a reply on Retrieve All Items Using Pagination

@SNAPEY - That's an interesting approach and one which I will use in another are of the app, thanks for the info.

boneill81 left a reply on Retrieve All Items Using Pagination

@S4MUEL - Zero did not work but this got me to thinking and I stumbled upon something which does and which I do not see in the documentation or in any of my searches. If you append page=0 to your request then it returns all items. Thanks for your help.

boneill81 started a new conversation Retrieve All Items Using Pagination

Hi Guys, I have a useful and clean search method which builds up an eloquent query based on attributes that are sent to it. At the minute it uses get() and works fine. I now want to add in pagination which again works. However at the minute I am doing the following:

if (!empty($parameters['page'])) {
    $results = $query->with('customAttributes')->orderBy('created_at', 'desc')->paginate();
}else{
    $results = $query->with('customAttributes')->orderBy('created_at', 'desc')->get();
}

I was wondering if there is not perhaps a nicer built in way to do this. For example pass false to paginate in which case it returns all records as per a normal get() which it executes internally anyway.

Thanks

14 Aug
9 months ago

boneill81 left a reply on Can't Access Laravel Facades/Classes In Custom Class

For anyone else who encounters this issue, I got to the bottom of it. In actual fact I was on the right track yesterday but had omitted a required line. Include the following at the top of your custom file and Laravel will bootstrap it and the autoloader will work. I had initially tried this before posting but had left out the response line which is what caused the issue. Thanks for the help guys.

require_once(__DIR__ . "[YourPath]/bootstrap/autoload.php");
$app = require_once(__DIR__ . "[YourPath]/bootstrap/app.php");
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
$response = $kernel->handle(
    $request = Illuminate\Http\Request::capture()
);
13 Aug
9 months ago

boneill81 left a reply on Can't Access Laravel Facades/Classes In Custom Class

One final question on this. The non-laravel script which is importing my laravel custom class from the CustomScripts folder is located in the public folder. It is not a core part of the application. But I was wondering should Laravel auto-loading not also work in the public folder since it is in the Laravel framework. The auto loading is working in my CustomScripts folder but does not work once I require that custom class in the script located in the public folder. Thanks.

boneill81 left a reply on Can't Access Laravel Facades/Classes In Custom Class

@Cronix Thanks for the help, I think this was perhaps a case of too long looking at things with tired eyes. I see now that this probably won't work since the Log dependency won't exist in the target non-laravel script anyway. I will come at it in a different manner. While we are on the topic is there perhaps any neat way to use Laravels caching engine in a non-laravel script as a once off? Thanks.

boneill81 left a reply on Can't Access Laravel Facades/Classes In Custom Class

@Cronix No, I am including it using a regular php require. I was just about to ask actually, I wonder if this is anything to do with the fact that the class is being called from within a regular non-namespaced script? I can access the custom class itself just fine, but not the Log/cache etc.

Basically, I need to use Laravels caching/logging engine in a separate script for a short term use case. I was trying to go about this in the best manner and had read about approaches where custom scripts located in a folder in the App directory would be auto-loaded and usable via require in other scripts.

Thanks.

boneill81 left a reply on Can't Access Laravel Facades/Classes In Custom Class

@jlrdw Yeah I have done that also if I use this the same thing happens when I call the method it tells me that Log is not found.

use Illuminate\Support\Facades\Log;

boneill81 started a new conversation Can't Access Laravel Facades/Classes In Custom Class

Hi Guys, I'm scratching my head on this one. I have a simple test custom class as follows:

namespace App\Libraries\CustomScripts;

use Log;

class TestHal {

    public static function test(){

        Log::info("I'm sorry Dave, I can't do that...");

    }

}

I can include this object in a non-laravel script and call it successfully using:

App\Libraries\CustomScripts\TestHal::test();

However it keeps throwing with the following error:

PHP Fatal error: Uncaught Error: Class 'Log' not found

The same thing happens if I full reference the Facade path or use \Log. But if I use an echo command instead of the Log it works just fine. Obviously something is not right with the auto-loading but I am unsure as to what. Any help would be appreciated.

23 Jul
9 months ago

boneill81 started a new conversation Request Merge Operation Has No Effect When Executed From Within ServiceProvider

Hi Guys, No doubt I am missing something easyhere but I cannot seem to see what it is.

I have a custom validation rule which checks geo-spatial references against various rules. It works fine when defined and run from the prepareForValidation() function of my Custom Request.

//Validate a spatial reference string and merge the returned spatial references array with the current request for persisting.
        Validator::extend(
              'spatial_reference',
              function ($attribute, $value, $params, $validator) {
                  $spatialReferences = calculateSpatialReferences($value);
                  if ($spatialReferences == false) {
                      return false;
                  }
                  $this->merge($spatialReferences);
                  return true;
              },
          'The :attribute is not in a valid format.'
          );

However today I was doing some housekeeping and decided to move the custom validation rule along with a few others to my new CustomValidationServiceProvider.

Obviously the $this->merge won't work right away since $this has no meaning in that context so I instead used the helper request()->merge($spatialReferences).

This is the strange thing, I can see that the $spatialReferences array was successfully created but the request()->merge($spatialReferences) had no effect. The array does not merge to the request from the provider whereas it merges just fine from the custom request.

I would appreciate a pointer in the right direction as to why this happens. I have it working fine again from the custom request but I would still like to know why. It was an unusual one.

Thanks in advance.

31 Aug
1 year ago

boneill81 left a reply on Dynamic Content For Download (Content-Disposition The Laravel Way...)

@dylanh Absolute legend, this is exactly 100% what I needed to solve my issue today. A+

02 May
2 years ago

boneill81 left a reply on Passing Hrefs In Blade Template

@pritam1605 Not at all, been there many times mate, long hours in front of code and your eyes see what your mind knows should be there rather than what is there. Glad you got sorted.

boneill81 left a reply on On Delete Cascade On Single Table With Parent-child Relation

@mevlutozdemir Perhaps you have already done this, but cascading should really be set up in your DB itself in my view. I see this frequently on various forums and it has often occurred to me as to whether people are only setting up these rules in their migrations. Being a DBA also I always fully model my databases and then write my models around them. But if you correctly model your table then you won't need to worry about cascades in your code, once you drop the parent then the children will be deleted/set to null or updated also depending on the rules in your foreign key. My advice would be to do this at the database level.

boneill81 left a reply on Passing Hrefs In Blade Template

@pritam1605 Spelling error perhaps @yield would the correct spelling? Does that fix it. Easy mistake to make and can't beat a fresh set of eyes.

boneill81 left a reply on Custom Authentication With Third Party Authentication API

@martinbean Thanks for your reply and apologies about the latesness in getting back to you. I ended up implmenting passwordless authentication on the project similar to the Laracasts video on the topic and it works great.

All the best.

boneill81 started a new conversation Regarding Routing, Web.php Vs Api.php

Hi Guys, Having initially began a project when routes.php was the thing and then with the move to web/api.php I wanted to ask what approaches you take.

My project has rest aspects to it for certain elements but for instance for general web services that return datatables json etc. do you use web or api.php. I realise it works in both and the difference is in the middleware that is applies and the addition of the api prefix. But I was curious do you use the api.php or do any of you recreate routes.php.

Thanks!

01 May
2 years ago

boneill81 left a reply on Serious Issue Where Save() Returns True But Record Is Not Persisted To The Database

I got to the bottom of this today. This was a bug with MariaDB which has been fixed in 10.1.22. See here for details https://jira.mariadb.org/browse/MDEV-11842.

Basically HeidiSQL could see that the row had not been added and threw its own error but MariaDB did not throw an actual error which is why save() could not ascertain that anything was amiss. Hopefully it will help someone else.

Thanks.

26 Apr
2 years ago

boneill81 left a reply on Serious Issue Where Save() Returns True But Record Is Not Persisted To The Database

I know what you mean but in this case MariaDB did actually throw an error but Laravel seems to have ignored it and carried on. It seems odd to me. Perhaps I am missing something?

boneill81 started a new conversation Serious Issue Where Save() Returns True But Record Is Not Persisted To The Database

Hi All, I have come across and tested a serious issue where save() returns true but does not persist the record to the database. I had some questions on this.

The error in question happened because a new field added to the data model had erroneously not been assigned a default value.

However with this in mind, the expected behaviour of the save() method would be to return false in this case. But it returned true. The same behaviour was observered using firstOrCreate() and firstOrNew() also which in I realise are essentially just convenience wrappers for save() so it makes sense that they returned the same value.

I see this as an extremely serious error. This was being run within a transaction. Had it not been for me subsequently trying to attach some relations to the created model, then no exception would have been thrown and the transaction would have committed and returned true while it had silently failed.

 DB::beginTransaction();
    try{
        $taxonRecord = new TaxonRecord($attributes);
        $recordSource = $taxonRecord->recordSource;
        $taxonRecord->record_source_name = $recordSource->name;
        DB::enableQueryLog();
        if(!$taxonRecord->save()){//I specifically put in this if statement to try and make it catch the error but it still does not
            Log::error($taxonRecord);
            throw new \Exception('Taxon record was not saved.');
        }
        Log::info(DB::getQueryLog());//Query log shows the query and bindings. When run in heidiSql I discovered the miss

        //Now we make sure that only those attributes allowed for the taxon record are saved so as to prevent anyone from adding malicious attributes to the request.
        //This fails since there is now an integrity constraint since the TaxonRecord was not actually perisited. We should not have reached this point!!
        $customAttributes = $recordSource->customAttributes;
        foreach($customAttributes as $customAttribute){
            $customAttributeValue = array_get($attributes, $customAttribute->name, null);//Find the attribute in the array, set to null if it does not exist.
            if( !empty($customAttributeValue) ){
                $taxonRecord->customAttributes()->attach([ $customAttribute->custom_attribute_id => ['value' => $customAttributeValue] ]);
            }
        }
        DB::commit();
        return $taxonRecord;
    } catch (\Exception $e){
        DB::rollBack();
        Log::error($e);
        return false;
    }

Your thought's please gentlemen.

25 Apr
2 years ago

boneill81 left a reply on Where Are You All From?

Tipperary, Ireland.

boneill81 started a new conversation Custom Authentication With Third Party Authentication API

Hi Guys, I'd appreciate it if someone could point me in the right direction on this one.

I have almost completed a largish app in Laravel. It's all working very well. As a last component I need to add authentication to the system.

In the app's predecessor which is not using Laravel the authentication works fine with the third party authentication API. The methods use CURL to log in and retrieve details.

I realise that I will need to create a custom Auth for this and have given most of yesterday evening googling and reading all I could find. The problem is the documentation on adding custom authentication is light compared to other functionality and I am a little unsure as to where and how to add my existing methods for validation to my custom Auth .

I don't need to worry about registering etc. right now, I can build that up later but at present I just want to authenticate users. However rather than just patching a middleware I would like to do it in a clean and elegant manner like everything else in the new project.

I am using Laravel 5.4 and have been using the links in the following answer and also the answer itself. But I stopped until I could get some clear info on this.

http://stackoverflow.com/questions/32243363/how-to-create-laravel-5-1-custom-authentication-driver

Thanks in advance, I appreciate the help.

20 Apr
2 years ago

boneill81 started a new conversation Added Request Parameters Disappear When Request Is Sent Via JSON But Work From Form

Hi All, A strange one here.

I have a form request with a custom validator. Upon successful validation I add some items to the request as follows:

  public function __construct(ValidationFactory $validationFactory) {

    $validationFactory->extend('spatial_reference', function ($attribute, $value, $params, $validator) {
      $spatialReferences = calculateSpatialReferences($value);\\ returns an array with the various spatial references
      if( $spatialReferences == false ){
        return false;
      }
      $this->request->add($spatialReferences);
      $this->request->remove('spatial_reference');
      //for some reason the above is lost when using a json request
      return true;
    },
    'Spatial reference is not in a valid format.');
  }
    public function store(SomeRequest $request)
    {
        dd($request->all()); \\ contains the spatial references but not if the request was sent via json
}
    

However here is the strange part. When post is sent from a web form request->all() the store method in my controller shows the correctly added parameters in the request after successful validation. But if the exact same method is hit from a json request, request->all() does not contain the added parameters.

I have verified that the parameters are being added correctly in the form request but they are being lost as soon as I enter the store method when using a json request.

Any ideas?

Thanks.

18 Apr
2 years ago

boneill81 left a reply on Can't Access Collection Property Directly Without Using Get()

OK never mind, I will leave this here in case it helps anyone. Of course I can't access it since the recreated element is a simple collection and not a Request object. Thanks.

boneill81 started a new conversation Can't Access Collection Property Directly Without Using Get()

Hi All, So I have hit a strange snag just this past half hour. I have some middleware to perform backwards compatibility on an old mobile app version so that it works with the new version of the main system.

So the request comes in, if the token matches a specific token then it then request->all() is sent to a method which creates the new request.

if($request->has('some_token')){
    Log::info($request->all()); //Works fine as you would expect
    if($request->some_token == '12345'){ // I can access some_token as a property as per normal here.
        $request = $this->upgradeRequest($request->all()); //request is changed to the new version
    }
    Log::info($request->all()); // Similar output to the above. Just with the names of some of the properties changed.
    Log::info($request->some_token); // Error throws "Property [some_token] does not exist on this collection instance"
    Log::info($request->get('some_token')); // Works but why can't I access it in the same manner as before?
    return $next($request);
}

    
public function upgradeRequest( $oldRequest ){
    $newRequest = [];
    $newRequest['some_name']  = $oldRequest['some_name'];
    $newRequest['some_token'] = '56789';
    return collect($newRequest);
}

I realise I can get this to work using get() but why does it work and why can't the properties be accessed in the same manner as the initial request when $request->all() shows the some_token property as existing in both requests??

Thanks.

17 Apr
2 years ago

boneill81 left a reply on Include A Custom Error Message With A Custom Validation Rule

Ah super thanks a million. There are so many approaches to extending the Validators, I had missed the fact that the extend function took the third parameter. This is ideal. Thanks again.

boneill81 started a new conversation Include A Custom Error Message With A Custom Validation Rule

Hi, I have a custom validation rule as follows which for validating and image. I have this included in the constructor of my Form Request.

$validationFactory->extend('is_image', function ($attribute, $value, $params, $validator) {
      try {
        $image = Image::make($value)->encode('jpg');
        if( $image->filesize() > 500000 ){
          return false;
        }
        return true;
      } catch (\Exception $e) {
        return false;
      }
    });

Ideally I would like to actually return the relevant error message with the Validator rather than adding it to the language file or in the messages() function in the Form Request. This seems a more elegant way to do this to me. If in time I end up with multiple custom Validation functions I can extract them to their own class. But for now its not necessary and would be overkill.

Is this possible? I have looked but cannot see anything regarding this.

Thanks.

06 Apr
2 years ago

boneill81 started a new conversation Uploading Images Via Browser Form Or JSON Request

Hi Guys, In an app which I have been working on for some time and which I am now getting close to completion, I can create a record either via a form or via json as per normal in Laravel.

One thing though, while Laravel takes both requests perfectly it does not seem to do so when images are brought into the equation.

I have a validation rule in my FormRequest as follows:


This works fine and enforces a maximum image file upload of 500KB when used in the browser form. 

However if I pass the image base64 encoded in a JSON request, it fails, presumably because it is now a string rather than image.

I have checked the documentation but cannot seem to see a specific reference to Laravel handling the file uploads in both browser and JSON.

Is there some elegant/Eloquent(pun intended) way that Laravel handles this which I am missing.

Thanks,
Barry.
21 Feb
2 years ago

boneill81 started a new conversation Passing Parameters To Eloquent Relation Method, Possible?

I am working on a project which has some many to many relations. For the purposes of efficiency and clarity I don't always require all the relations using eager loading.

I came up with the following idea but I am not sure if it will work since I can't seem to find detail on how one would actually pass through the parameter from the eloquent query.

    /**
     * The custom attributes that belong to the taxon record.
     */
    public function customAttributes( $attributes = [] )
    {
        $results = $this->belongsToMany('App\Models\CustomAttribute', 'record_custom_attributes', 'record_id', 'custom_attribute_id')
                    ->withPivot('value');

        if( !empty($attributes) ){
            $results->whereIn('custom_attributes.name', $attributes);
        }
     
        return $results;
    }

The above code works if I pass in say ['hair_colour'], it will only retrieve those relations but, how would one go about passing it. Can you explicitly call the customAttributes method on the record model when querying rather than supplying it using with().

Has anyone got any ideas on this?

Thanks.

27 Apr
3 years ago

boneill81 left a reply on Access Request Parent Methods From Within Form Request Constructor

Just in case it helps anyone Thomas on stackoverflow showed me why the issue was happening.

http://stackoverflow.com/a/36896983/965276

boneill81 left a reply on Access Request Parent Methods From Within Form Request Constructor

@martinbean To be honest martin it sounds like you should re-read my question before making broad sweeping statements on my architecture based on three lines of code which are clearly being used to describe the issue I am experiencing in only one small fragment of code. Also what cross-class communication would you be referring to. If you are talking about my repository then that is of no concern since it works just fine. Also as per Laravel and also Laracasts in their videos "For more complex validation scenarios, you may wish to create a "form request". " Containing the repository call which returns validation specific rules here makes perfect sense in my domain and is efficient. Also if its such a bad thing to use a repository or class then how are we supposed to write applications at all.

My question if you read it, is related as to why I cannot access the methods in the request class when my form request extends it. According to the principles of inheritance and also many of my peers I would have thought they would be accessible. There probably is a simple explanation and if you know it, I would also be grateful if you showed me why they cannot be accessed in the constructor.

Thanks for your reply.

Finally if your cross class dependency comment is related to the request methods then that makes no sense, if you cannot communicate with the class that you extend then whats the point.

boneill81 left a reply on Access Request Parent Methods From Within Form Request Constructor

Yeah I thought so too, but that won't work for me inside the constructor. It keeps throwing "Fatal error: Call to a member function get() on null in vendor\laravel\framework\src\Illuminate\Http\Request.php:601". The same code works in the rules method but not in the constructors. I can't see why at all.

boneill81 started a new conversation Access Request Parent Methods From Within Form Request Constructor

Hi, I was wondering how would one go about accessing the parent request methods from within an form request. My form request contructor looks like the following. But I get a call to a member function error when I try to access the parent from within the child constructor.

Accessing the parent below triggers "Fatal error: Call to a member function get() on null in vendor\laravel\framework\src\Illuminate\Http\Request.php:601"

    protected $test= ['rules' => [], 'messages' => []];

    public function __construct(myRepositoryInterface $myRepository) {

        $this->myRepository= $myRepository;
        if( parent::has('someName') ){
           $this->test= $myRepository->someMethod(parent::input('someName'));
       }
   }

boneill81 started a new conversation Field Added To Request In Middleware Not Reaching FormRequest

I have a curious one here. This morning I was attempting to add a uuid field to my request in my middleware. If I log request->all() just prior to next($request) then I can see that it is indeed added. However once the request hits the form request the validation fails and I have verified that the new field is missing. Any ideas on why this is the case. Thanks.

This works and I can see the transactionId.

        if ($request->isMethod('post')) {
            $request->merge(['transactionId' => Uuid::uuid4()->toString()]);
        }
    Log::debug($request->all());

But once I reach my form request it fires an error stating that the transactionId is missing.

17 Apr
3 years ago

boneill81 left a reply on Dynamically Pass Rules To Form Request

In case it helps anyone, I came up with a solution to this, I use middle-ware to push the config onto the session and then use array_merge to join the custom validation rules with the default ones in my form request. It works a treat. I would be interested though to hear how others have done something similar. Thanks.

boneill81 started a new conversation Dynamically Pass Rules To Form Request

Perhaps a little unusual use case here but a helpful one nonetheless I believe.

My system builds up custom HTML forms based on JSON configurations. There is a subset of core attributes that all forms will have but then each has some arbitrary attribution which will vary based on the config for that form.

I am using form requests and it all works beautifully. However I have one extra requirement which is causing me some troubles. I would like to be able to dynamically pass/inject rules into the array returned by rules() in my form request.

I could store the rules in the session and access them there from within the form request itself. But I was wondering if there is some nicer way. Perhaps middle-ware or some such. Or perhaps override the form request constructor to accept a rules array but if I did this I would not then be able to simply type hint the request in the controller as I would need to pass the rules array.

Perhaps this is simply no there and the session will be required but any ideas or previous experience would be appreciated.

26 Jan
3 years ago

boneill81 started a new conversation Pass Variable From Route To Middleware??

I have two middleware classes set-up in my application to cache the output of my views. Its all working a treat but I wanted to know how would you go about passing a custom variable with the route to the middleware.

My thought process is this, at present I have the middlewares listed in my $routeMiddleware in kernel.php.

However rather than call ->middleware() on each route, I would prefer to activate the middleware for all routes in $middlewareGroups and then just pass a custom "noCache" variable on the routes that I do not want cached. I can then include a check for this in the middleware.

So something like the following.

Route::get('contact-us', ['as' => 'contactUs', 'uses' => 'PagesController@contactUs'])->with('noCache' => true);

Is this a possibility in Laravel(I'm on 5.2).

Thanks.

25 Jan
3 years ago

boneill81 left a reply on View Partial Within View Partial

ARGGHHHHH!!!! god such a simple mistake. Thanks a million, time for a break obviously, my eyes are beginning to see what should be there as opposed to what is. I had checked literally everything aside from that. First time I forgot the blade part. Sorry for the trouble over such a mundane error and thanks to ye all for the help.

boneill81 left a reply on View Partial Within View Partial

First up is the navList partial.

<li><a href="{{ route('home') }}" id="current">Home</a></li>
@include('partials.latestUpdatesNav')
<li><a href="{{ route('about') }}">About</a></li>
<li><a href="{{ route('links') }}">Links</a></li>
<li><a href="{{ route('contactUs') }}">Contact Us</a></li>

Now the latestUpdates partial which just loads the list item into the current list. The blade syntax is just printing as text in this one, the variables or calls like dd() are not working and are being treated as plain text in the nested partial.

<li><a href="{{ route('latestUpdates') }}">Latest Updates {{ $latestUpdatesCount }}</a></li>

Thanks for your help.

boneill81 started a new conversation View Partial Within View Partial

I have encountered what to me is an unusual issue. IN my setup I have my nav menu as a view partial.

Today I wanted to add a new link to the navmenu which receives a number for display. There fore I created a view partial and composer to set it all up since I will be using the link in multiple places.

It all works fine and I have var_dumped the variable to make sure its there and it is. However once the partial for the button is included in the nav menu partial, none of the blade syntax takes effect.

So instead of loading the variable from {{ $mycount }}, it simply outputs {{ $mycount }}.

Any ideas on why this might be??

22 Jan
3 years ago

boneill81 left a reply on Laravel 5.2: Form Not Being Repopulated After Validation Fails

OK thanks for clearing that up for me. Its funny it must have been the browser cache that confused me earlier, I had thought it was doing it automatically. Thanks for the help.

boneill81 started a new conversation Laravel 5.2: Form Not Being Repopulated After Validation Fails

Hi Guys,

I have a contact form in Laravel 5.2. All was working fine earlier. The only change that has been made is to install the laracasts\flash package. That package is working fine but I notice that when the formRequest fails the input is not being repopulated automatically like it was earlier in the day.

Now unless I am mistaken in 5.2 you do not need to call old() everywhere to repopulate the fields, it happens automatically. Am I mistaken on that point?

Thanks, Barry.