314 Best Reply Awards

  • Member Since 2 Years Ago
  • 773 Lessons Completed
  • 2 Favorites

5th October, 2017

ohffs left a reply on Caching (OPCache And Redis Question) A 3rd Party API • 2 weeks ago

'better' is always a loaded term ;-) But in general, then I'd say 'yes' for this kind of thing. It's pretty rare you find yourself using this kind of thing less than you originally thought - and it'd be annoying to then have to change all your controller code :-)

Even if you decide to do 'fancy' things like have the cache expire automatically, or transform the data inside the Cache:: call so you don't have to process it each time - having to do that over and over would bug me anyway... :-)

ohffs left a reply on Caching (OPCache And Redis Question) A 3rd Party API • 2 weeks ago

The OP Cache is really just for PHP code itself (ie, PHP doesn't have to re-compile your script from scratch every time).

Without knowing more - something along the lines of this might be what you're after?

class MyApiWrapper {
  public function get($whatever)
    Cache::get($whatever, function () use ($whatever) {
      // return $whatever_your_api_call_does

  public function refresh($whatever)
    return $this->get($whatever);

(it's a while since I did anything with the cache, so that's just a very, very rough 'off the top of the head' idea!)

4th October, 2017

ohffs left a reply on Testing Queued Code Vs Inline • 2 weeks ago

Ahhh - figured it out. Even though I'm not 100% sure what's going on. In the test I had :

$result = CopyFile::dispatch('file1');

If I change that to ignore the return value, then the test passes and everything seems to be ok :

// no $result - this version works fine

Which is a little peculiar. I haven't dug in, but I'm guessing it's that the job is only actually fired when the CopyFile class is 'destroyed' by PHP - and when I keep the $result then the garbage collector still has it marked in use, so the job doesn't get 'fired' until the test finishes and it's garbage-collected.

Anyway - live and learn! Thanks @Drfraker for taking an interest :-)

3rd October, 2017

ohffs started a new conversation Testing Queued Code Vs Inline • 2 weeks ago

A slightly odd thing, to me at least. I have a bit of test code like :

// ... more setup

//        Storage::disk('destination')->put('file1', 'hello');


I've set the code in the CopyFile job to be exactly the same as the Storage::disk line below it.

If I run the version with ::dispatch'ing the job, the assertExists fails, but the in-line version passes. The queue driver is set to 'sync' for the tests so should (as far as I remember) be run before the assertion.

To add to the mystery, the 'file1' is created in the fake storage directory if I check after the test has run.

Am I doing something really dim?

19th September, 2017

ohffs left a reply on How Can I Build This Package? • 1 month ago

@JoeDawson yay - glad it helped :-)

15th September, 2017

ohffs left a reply on How Can I Build This Package? • 1 month ago

Jeffrey has touched on this in a few videos (one quite recently which I can't find now, annoyingly). This one has some stuff that might help though : https://laracasts.com/series/whip-monstrous-code-into-shape/episodes/9

But basically, you could do something like the (entirely untested!) code below (and apologies if I'm mis-understanding the question!) :


namespace Searchers;

class MovieSearch
    protected $searchService;
    protected $results;

    protected function __construct($name)
        $providerName = 'Search' . ucfirst($name);
        $this->searchService = new $providerName;
        return $this;


    public static function provider($name)
        return new self($name);

    public function search($term)
        $this->results = $this->searchService->search($term);
        return $this;

    public function get()
        return $this->results;

// file: SearchImdb.php
class SearchImdb
    public function search($term)
        // do whatever
        return $results;

Hopefully that gives you some ideas at least :-)

8th September, 2017

ohffs left a reply on Dusk Tests On Upgraded L5.5 App Report Readonly Database • 1 month ago

Ok - sort of solved. I had code in my AppServiceProvider as follows :

if (DB::connection() instanceof \Illuminate\Database\SQLiteConnection) {
    DB::statement(DB::raw('PRAGMA foreign_keys=1'));

Which enforces 'proper' SQL foreign key constraints for sqlite (eg, triggers properly for onDelete()). But that seems to break dusk 2.x with the unhelpful 'readonly' error above. So commenting that out lets dusk work ok, but then phpunit fails because the tests assume proper onDelete() functionality.

Replacing the above code with :

if ($this->app->environment('testing')) {
    DB::statement(DB::raw('PRAGMA foreign_keys=1'));

Then both dusk and phpunit run ok (my .env/dusk setting for APP_ENV is 'local', for plain phpunit it's 'testing').

Bit of a hack, but it'll do for now...

ohffs started a new conversation Dusk Tests On Upgraded L5.5 App Report Readonly Database • 1 month ago

I've been stuck on this for a while so finally giving in and asking...

I've updated an app from 5.4 -> 5.5 and all is good. Reguar phpunit tests all pass. But the dusk tests fail whenever I'm using the database migrations trait with :

PDOException: SQLSTATE[HY000]: General error: 8 attempt to write a readonly database

I've got dusk 2.x, pulled in the current dusk test case, re-installed the vendor/ folder etc - to no avail. If I change the database config to a non-existant sqlite file I get a proper 'does not exist' error - but no matter what valid, writeable sqlite file I set the config too I get the 'readonly' error. When I run the tests the timestamp on the sqlite file is updated so it's clearly doing something, but the file remains at zero bytes and the readonly error is thrown.

I've tried a fresh install of L5.5 and don't get the same error - so "something" is wrong. Has anyone else hit this?

5th August, 2017

ohffs left a reply on False || True Equals False, How That? • 2 months ago

Operator precedence? Try dump( ($validator->errors()->any() || $validator->fails()) ); and see what you get?

4th August, 2017

ohffs left a reply on Please Help ! • 2 months ago

In the olden days I did this by using a bit of javascript which looped over the table (it was a huge report) then sending it to the back-end to re-export as Excel.

Is your controller taking lots of filters or something? Can you make the export button have a copy of the query/filters (ie, you end up with a button that points to /export?filter1=red&filter2=large"?

Or if your data is being displayed in a table maybe look at using the jquery datatables excel/csv exporting.

24th July, 2017

ohffs left a reply on Sending Requests Into Services Or Models • 2 months ago

I try to avoid passing the request object deeper into the system - but find myself doing it sometimes where it would be a bit of a pain otherwise - usually just limited to named constructors though.

Say I have a form that has a lot of optional fields, fields which need transformed based on other fields etc. Being able to use the $request->has / $request->whatever helpers can be a lot more readable than lots of isset($data['key']) calls etc.

But I do feel a little guilty about it all the same... :-/

9th July, 2017

ohffs left a reply on I Hate Webpack • 3 months ago

Somewhere out there there's someone giving themselves a lot of future job security by making JS & CSS as complex as possible ;-)

ohffs left a reply on Global Scopes Or Different DB's? • 3 months ago

@jlrdw yeah - it's more of a 'both choices are valid - has anyone been bitten by one or the other' kind of dilemma. I'll probably just do some exploratory coding and see which one feels like it's working out, but I'm leaning towards one big db with multiple sessions. We'll see how it goes! Thanks for the reply! :-)

8th July, 2017

ohffs left a reply on Runs Very Slow If There Is An Error And Says Memory Exhausted • 3 months ago

What database are you using?

ohffs started a new conversation Global Scopes Or Different DB's? • 3 months ago

I've got an old project which I'm looking to migrate to Laravel. It has lots of different inter-related models - all of which have a 'session' (basically a tax-year) attached to them. Users of the system can swap between different sessions to see old data and there is a large reporting section that shows data that compared against different sessions. Each year the data is 'copied forward' into a new session and the old session becomes effectively read-only.

My initial thought was to have a global scope on each laravel model that would limit the results to the current session. That covers the regular use-case where they're interacting with the system - but is a bit of a pain when it comes to the reporting layer and they're comparing different sessions (and I'm actually not sure what happens with relations if you disable a scope on a parent model - but I can dig into that).

My other thought was instead of 'copying forward' the data I would just duplicate all the data into a new database and then pick the database based on the users selected session. That makes the models/relations stuff a lot easier and reduces the amount of data that's in any given table as there's only ever one session's worth so speeds up a lot of queries. But again it makes the reporting layer trickier as you're having to compare data in different DB's.

Anyway - just wondering if anyone had done anything like this, or had any thoughts?

6th July, 2017

ohffs left a reply on Laravel Calendar • 3 months ago

Pikaday is a nice small option too.

ohffs left a reply on HOWTO: Homestead On Libvirt (kvm) • 3 months ago

It might be worth posting this to their github issues and see if it can be taken into the project as an 'official' branch of some kind?

3rd July, 2017

ohffs left a reply on Struggling To Understand The Concepts Of Laravel And Frameworks, Can You Help? • 3 months ago

I've been programming PHP since the 90s - PHPv3 ftw! (and programming in general since the 70s). I've only started using PHP frameworks in the past few years. Some of the quick gains for me were :

  • A lot of the boring boilerplate "I've written this 1000 times" code is taken care of. Stuff like validation, escaping user input, session/cookie handing, caching.

  • Community. There are a lot of people using frameworks. There's a good chance if I am trying to figure something out there's a blog post or a package on packagist.org that will at least point me in the right direction.

  • Convention. When someone else is looking at my code then they don't need to figure out my framework. As long as they know (or can do a quick google search) they'll be able to figure out where the config files are, how the database is managed, where the template files will be etc.

There's a lot more than that of course, especially for 'full-fat' frameworks like symfony and laravel. But if none of that appeals - then carry on of course :-) A quick very contrived example might be...


// traditional

function register()

    if (empty($_POST['username']) or empty($_POST['password'])) {
        $_SESSION['error'] = 'Username or password missing';
        return header("Location: http://www.example.com/login");

    if (!preg_match('/\@/', $_POST['email'])) {
        $_SESSION['error'] = 'Invalid email';
        return header("Location: http://www.example.com/login");

    if (strlen($_POST['password'] < 8)) {
        $_SESSION['error'] = 'Password too short';
        return header("Location: http://www.example.com/login");

    $user = $db->createUser($_POST['username'], $_POST['email'], $_POST['password']);
    if (!$user) {
        $_SESSION['error'] = 'Failed to create your account';
        return header("Location: http://www.example.com/login");

    print '<h1>Hello ' . htmlentities($user['username']) . '</h1>';
    print '<table>';
    foreach ($user->getAvailableVideos() as $video) {
        print '<tr>';
        print '  <td>' . htmlentities($video['title']) . '</td>';
        print '  <td>' . htmlentities($video['category']) . '</td>';
        print '</tr>';
    print '</table>';
    // etc etc

// framework

function register(Request $request)
    $this->validate($request, [
        'username' => 'required',
        'email' => 'required|email',
        'password' => 'required|min:8'
    $user = User::create($request->all());
    return view('home', ['user' => $user]);

// view 'home.blade.php'
<h1>{{ $user->username }}</h1>
@foreach ($user->availableVideos as $video)
    <td>{{ $video->title }}</td>
    <td>{{ $video->category }}</td>

1st July, 2017

ohffs started a new conversation Notification Icon • 3 months ago

Sorry to be a pest, but the notification icon to see mentions has become a bit unusable for me. It's not possible for me to click the little 'bell' icon any more - it just pulls down the 'my laracasts' menu when I try. I've attached a little gif with the developer tools open in case it helps. Using Firefox 53 on macos.


22nd June, 2017

ohffs left a reply on Folder Picker • 4 months ago

I don't think you can do that without using a browser plugin. You could add the 'multiple' option to the input to allow them to do a 'select all' of the files in the folder though, eg

<input type="file" name="import_file" multiple />

16th June, 2017

ohffs left a reply on Testing File Download With Dusk • 4 months ago

You might be better using the 'basic' http tests for downloads. You can do things like :

$response = $this->actingAs($user)->get(route('export.report'));

$response->assertHeader('content-disposition', 'attachment; filename="report.csv"');
$file = $response->getFile();
$filename = $file->getPathname();
// do whatever you need with the filename/file

ohffs started a new conversation JS Laravel-like Collections Library • 4 months ago


Seems quite nice - even if it will make me make even more -> vs . mistakes when switching between PHP and JS... ;-)

5th June, 2017

ohffs left a reply on Wow, PHP Reddit Really Is Full Of Jerks • 4 months ago

Wow, Reddit really is full of jerks

ftfy ;-)

I occasionally look at it for links to new projects/stuff (much like I use Hacker News) or to find documentaries I'd never come across myself (see /r/Documentaries) - but yeah, never read the comments ;-)

I guess the only up-side is that it makes twitter seem (marginally) more reasonable ;-)

2nd June, 2017

ohffs left a reply on Call Custom Class Inside Eloquent • 4 months ago

I guess you could do :

public function getFormattedPriceAttribute($value)
  return (new Format)->price($value);

If you're going to have maybe other format methods though you might want to do something like :

class Format
  public function __construct($model)
    $this->model = $model;

  public function price()
    return $this->model->price . '$'; // whatever

// Model
public function format()
  return new Format($this));

// Elsewhere

There's a lesson on here that might help :-)

31st May, 2017

ohffs left a reply on Multiple Dependent Jobs In Laravel 5.4 • 4 months ago

If it's any use, Laravel 5.5 should come with 'chainable jobs' which I think covers your needs - do job A, if that works, do job B etc? Not much detailed docs yet (obviously) but mentioned in the changelog.

It might save you a bit of work if you can hold off a little and work on another part of the code? Or pull in the 5.5 dev code to try?

27th May, 2017

ohffs left a reply on Code Quality Check • 4 months ago

I've run phpmetrics (or an article about using it in the past - it's free/open source so you could give it a try.

Other than that I just run phpcs/phpmd myself or as part of my gitlab CI runs. Sometimes I have to disable phpmd though as I'm way too lazy to try and figure out how to configure all it's rules :-/

I've never even looked into the JS side of 'code quality' - my JS use is pretty minimal and I know it'd just give a report back with a kind of look of pity ;-)

ohffs left a reply on Difference Array_filter With & Without Laravel • 4 months ago

I think the error just comes from how the PHP error levels are set by the framework - you could alter it to make the error (in a PHP kind of way) not be an error... ;-)

But you're probably better making your code do something safer like (in php7) :

return $acsv['MYKEY'] ?? false;

26th May, 2017

ohffs left a reply on Url In Email Includes An Ending Curly Bracket %7D • 4 months ago

Maybe try using

{!! $url !!}

If that doesn't help, try dd'ing the $this->url inside the mailable before sending it just to check what it looks like outside of the view itself. If that still looks fine, maybe add a @php dd($url) @endphp block into the view itself and see.

25th May, 2017

ohffs left a reply on Create A Form To Be Filled By Steps • 4 months ago

If you're ok with going down a more javascript route, you could use something like uikits tabs or a vue tabs component. Just make step 2, step 3 disabled until step 1 was valid and so on?

24th May, 2017

ohffs left a reply on Testing Validation • 4 months ago

It depends how bad it would be for your application if, for instance, you comment one of them out while debugging then forget to put it back.

If you're on 5.4 you should be able to do a one-liner something like (if I remember correctly!) :

$response->assertSessionHasErrors(['field1', 'field2', 'field3', ...]);

which would at least cover that the validation was picking up 'something' was going wrong.

23rd May, 2017

ohffs left a reply on Is This How To Register An Event In A Package? • 4 months ago

Ahh - got you. I'm assuming when you fire the event the listener isn't being triggered? If you set them up then do :

if (Event::hasListeners('Aacotroneo\Saml2\Events\Saml2LoginEvent')) {

that should (ha) at least tell you if the system has registered the event. Other than that - I'm not much help I'm afraid :-/

ohffs left a reply on Is This How To Register An Event In A Package? • 4 months ago

I think (and might well be wrong!) that using the facade you can only register callback listeners, and not class-based ones. So you can do :

\Illuminate\Support\Facades\Event::listen('Aacotroneo\Saml2\Events\Saml2LoginEvent', function($whatever) {
  // do something

To use class-based ones you have to shove them into the protected $listen array on the EventServiceProvider like :

protected $listen = [
  'Aacotroneo\Saml2\Events\Saml2LoginEvent' => [

I might well be wrong about the facade though - I don't really use the event stuff much and when I do it's via the $listen style.

19th May, 2017

ohffs left a reply on Collection Methods Series, Please :) • 5 months ago

Thirded, on the Refactoring to Collections series - it's really good stuff. There's also a video of Adam's conference talk on using collections on youtube too if you want an intro to the kind of things he goes through in the ..Collections series too :


18th May, 2017

ohffs left a reply on How To Know The Laravel Php Base? • 5 months ago

There's also version_compare() if you need to do something, e.g. :

if (version_compare(phpversion(), '7.0.0', '>=')) {
    require 'iknow/iknow/mysql_shim.php';

ohffs left a reply on Get Laravel 5 DD In Laravel 4 • 5 months ago

You could also try kint instead.

17th May, 2017

ohffs left a reply on Announcement: Laravel Sketchpad 1.2 Is Out • 5 months ago

Goodness - that's really pretty slick :-) Have you done any kind of write-up about it? Be a nice read :-)

ohffs left a reply on Best Performance Stucture • 5 months ago

If that's the main feature of your application and performance is key, then I'd probably stick with one table. If there's going to be a lot of data then maybe think about something like hbase instead of a regular sql db.

16th May, 2017

ohffs left a reply on Can We Get Exact Updated Field From The Update() • 5 months ago

I don't think you can do it directly, but a slightly more verbose way is :

$model = Model::find($id);
$model->fill(['email' => '[email protected]']);
$changes = $model->getDirty();
// $changes is an array of changed fields ('email' in this case)

You could always write a helper method on the model if you need to do it a lot, something along the lines of :

public function change($data)
  $changes = $model->getDirty();
  if (count($changes) == 0) {
    return false;
  return $changes;

ohffs left a reply on Testing After A Command Completes • 5 months ago

Is it because your command is doing something similar to the factory like Carbon::now()->subDays(1) and it's running so fast it's not seeing the record as being different than the overdue_at field? Try something like this and see if it helps :

factory(Record::class)->create(['overdue_at' => Carbon::now()->subDays(1)->subHours(1)]);

(or addHours() if that's the condition you're checking)

15th May, 2017

ohffs left a reply on White Background In Editor • 5 months ago

I've taken to wearing sunglasses... ;-)

12th May, 2017

ohffs left a reply on Laravel Frustration • 5 months ago

@ZetecVan we were all kidding - you're totally old! ;-p

ohffs left a reply on Laravel Frustration • 5 months ago

Good luck @muuucho :-). I wrote my first program in the late 1970's - so I guess this thread is full of the forum oldies ;-)

11th May, 2017

ohffs left a reply on Laravel Frustration • 5 months ago

If it's any help, a lot of the code for the lessons is available to download on github.

If you're willing to pay a little money, then Matt Stauffers book might be helpful - maybe easier to read the lessons at your own pace than listen if English isn't your first language?

ohffs left a reply on Is Hopping To Latest Version Of Laravel A Pain? • 5 months ago

Mostly minor versions (i.e., 5.2 -> 5.3) are fairly straightforward. Sometimes there's a bit of hassle, but it's mostly ok.

The last big change in directory structure was from 4.x -> 5.x - hence the major version bump.

You can also save a lot of the basic 'grunt work' of upgrading by using something like shift.

9th May, 2017

ohffs left a reply on What Is The Best Way To Achieve Unique Urls For Each Item • 5 months ago

Or maybe use something like hashids.

ohffs started a new conversation L5.4.22 Security Update • 5 months ago

Sounds like it's worth investigating if your code uses the built-in password reset code :


ohffs left a reply on Looking For Best Admin-panel Theme For School Management System • 5 months ago

Is there anything else you'd like it to do?

8th May, 2017

ohffs left a reply on Slow Excel Report With MySQL Queries Inside Nested Foreach Loops • 5 months ago

Ontop of eager loading as @jbloomstrom suggests, you could also look into spout - I use it a lot instead of the phpexcel-derived libraries. It's a lot faster and lower memory overhead. Doesn't do everything that phpexcel can - but for most cases it's fine.

You could also try just building an array of data rather than building the spreadsheet. Then dump it out as one big "set".

Edit Your Profile

Want to change your profile photo? We pull from gravatar.com.