ohffs

Experience

241,240

312 Best Reply Awards

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

5th August, 2017

ohffs left a reply on False || True Equals False, How That? • 1 week 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 ! • 1 week 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 • 3 weeks 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 • 1 month 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? • 1 month 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 • 1 month ago

What database are you using?

ohffs started a new conversation Global Scopes Or Different DB's? • 1 month 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 • 1 month ago

Pikaday is a nice small option too.

ohffs left a reply on HOWTO: Homestead On Libvirt (kvm) • 1 month 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? • 1 month 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...

<?php

// traditional

function register()
{
    session_start();

    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");
    }

    require_once('./lib/database.php');
    $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>
<table>
@foreach ($user->availableVideos as $video)
  <tr>
    <td>{{ $video->title }}</td>
    <td>{{ $video->category }}</td>
  </tr>
@endforeach
</table>

1st July, 2017

ohffs started a new conversation Notification Icon • 1 month 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.

http://imgur.com/a/3vLHl

22nd June, 2017

ohffs left a reply on Folder Picker • 1 month 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 • 2 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->assertStatus(200);
$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 • 2 months ago

https://github.com/ecrmnn/collect.js

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 • 2 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 • 2 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
$model->format()->price();

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

31st May, 2017

ohffs left a reply on Multiple Dependent Jobs In Laravel 5.4 • 2 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 • 2 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 • 2 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 • 2 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 • 2 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 • 2 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? • 2 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')) {
  dd('hello');
}

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? • 2 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' => [
    'App\Listeners\Saml2LoginListener',
  ]
];

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 :) • 2 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 :

https://www.youtube.com/watch?v=crSUWtRYw-M

18th May, 2017

ohffs left a reply on How To Know The Laravel Php Base? • 2 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 • 2 months ago

You could also try kint instead.

17th May, 2017

ohffs left a reply on Announcement: Laravel Sketchpad 1.2 Is Out • 3 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 • 3 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() • 3 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();
$model->save();
dd($changes);
// $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)
{
  $this->fill($data);
  $changes = $model->getDirty();
  $this->save();
  if (count($changes) == 0) {
    return false;
  }
  return $changes;
}

ohffs left a reply on Testing After A Command Completes • 3 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 • 3 months ago

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

12th May, 2017

ohffs left a reply on Laravel Frustration • 3 months ago

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

ohffs left a reply on Laravel Frustration • 3 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 • 3 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? • 3 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 • 3 months ago

Or maybe use something like hashids.

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

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

https://laravel.com/docs/5.4/releases#laravel-5.4.22

ohffs left a reply on Looking For Best Admin-panel Theme For School Management System • 3 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 • 3 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".

6th May, 2017

ohffs left a reply on Reasons Why We Need Repositories Even If We Have The Model Eloquent • 3 months ago

@JeffreyWay I wonder if you'd consider re-visiting the repository video(s) sometime? They come up a lot on the forum and generate 'a bit' of debate.

Other than annoying Jeffrey though... I think repositories have their place - but there seems to be some kind of 'mantra' floating about that if you're not using them then in some way your project is doomed - or "you're not doing it right". It quite often seems to be the 'go-to pattern' that people implement to solve a problem they don't have.

Say I have a controller like :

class MyController {
  public function __construct(MyEloquentModel $model)
  {
    $this->repository = $model;
  }

  public function index()
  {
    $items = $this->repository->all();
    return view('mymodel.index', ['items' => $items]);
  }

  public function show($id)
  {
    $item = $this->repository->find($id);
    return view(...);
}

Am I now 'using the repository pattern'? If not and I create a 'repository' like :

class MyModelRepository
{
  public function all()
  {
    return MyModel::all();
  }

  public function find($id)
  {
    return MyModel::find($id);
  }
}

I'm surely now using the repository pattern, right? Bonus reddit points all round! :-)

I think the repository pattern gets thrown around as a panacea for 'what if I (change framework|change ORM|word ends)' or as a 'fancy' way of describing a wrapper around something you don't have 100% control over.

I think the 'Active Record Pattern' (or 'anti-pattern' for more reddit bonus points) is so close to being 'a repository' in practical terms that it's not worth giving a lot of thought to unless you're in a strong position to know that you're likely to change framework/ORM/whatever a lot. But what if you change from PHP to Ruby or Node? Your repository is toast anyway.

Making a 'repository' for something like a 3rd-party HTTP API still makes good sense as they are kind of in the place the DB layer was when people started to fret about 'the repository pattern' to begin with. I also tend to 'collapse' long eloquent/ORM calls down to a method as they make me a bit twitchy ;-)

I do think the repository pattern has places it's the right thing to use. I just think for 99% of cases in a PHP web app, it's not needed and just adds a layer of abstraction over the layer of abstraction we're already using.

Anyway - sorry for the long rant!

ohffs left a reply on Testing File Uploads Fails At Validation • 3 months ago

Not sure - I've seen file upload/validation stuff fail in weird ways if the file is bigger than php is configured for. Try uploading a tiny file maybe just in case?

Other than that - maybe before the validation try storing the file somewhere on disk and seeing what it contains - just to make sure it's actually being passed through?

ohffs left a reply on How Far Do You Take Testing? • 3 months ago

Crud stuff can be quite tedious to test. In this kind of case (assuming a contact is something a user is adding) if it really mattered (ie, do you care if they type in garbage contact data) I'd probably end up with tests along the lines of :

a_user_can_add_a_valid_contact()

a_user_cant_add_an_invalid_contact()
// which pretty much checks for a redirect/session error

a_user_can_delete_a_contact()

a_user_can_update_a_contact_with_valid_data()

a_user_cant_update_a_contact_with_invalid_data()

// and assuming your twitter validation was extending the laravel validation

a_valid_twitter_username_passes

an_invalid_twitter_username_fails

For things like a phone or email I generally just trust laravel's built-in validation - I just care it's 'phone-like' or 'email-like' - same for a twitter handle. If it's vital that those are 'real' then I'd bother.

Maybe I'm lazy, but if a user types in the wrong twitter handle or phone number then I'm not that fussed - they'll figure it out themselves ;-)

I've also been bitten down the years by adding too much validation. A project I worked on a while back gave me a load of sample data - the title of the items were all (like 1000's of them) of the format 'XXX9999', so I had a little bit of validation to check that. First day it was rolled out I got complaints because they wanted to add 'XXX_9999 (XX)'. So quickly changed to just a 'required' check rather than any kind of 'validation'.

ohffs left a reply on Testing File Uploads Fails At Validation • 3 months ago

Have you tried dd'ing the $request in the controller before the validation call? Just to see what's in it?

ohffs left a reply on Testing File Uploads Fails At Validation • 3 months ago

...What is actually going wrong?

5th May, 2017

ohffs left a reply on Useful Option "Import Class" In SublimeText • 3 months ago

Give this a try : https://github.com/erichard/SublimePHPCompanion . You need to add your own keymappings for it - but other than that it works fine :-)

ohffs left a reply on Prevent Changes To Form Action By Use Of Developer Tools • 3 months ago

I don't think I'd worry about it :-)

Edit Your Profile
Update

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