Buy your loved one the ultimate gift. Lifetime gift certificates are $100 off.

ohffs

Experience

252,790

314 Best Reply Awards

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

14th December, 2017

ohffs left a reply on Updating Data When Child Component Is Doing A SetTimeout() • 1 day ago

:: lonnnnnngggggg sigh ::

Ok, I'm an idiot. Having reversed the code a little to make the flow more clear, in the childs event listener I had code like :

        mounted() {
            self = this;
            Event.$on('copying', function(id, event) {
                if (self.entry.id == id) {
                    self.entry.copying = true;
                }
            });
        },

But, as I now see is obvious, self = this; should have been var self = this; otherwise 'self' was being reset to whatever semi-random value when a new child mounted - which is why it sometimes worked and sometimes didn't, pure chance.

Hey ho. I'm off to pour myself a stiff mulled wine :-)

ohffs left a reply on Updating Data When Child Component Is Doing A SetTimeout() • 1 day ago

@robrogers3 thanks for that :-) I was trying to keep my question brief so skipped quite a lot of detail, but that's always a double-edged sword ;-)

It's a little DIY 'live' web front end to a torrent daemon running on a raspberry pi. It shows all the downloaded torrents, their current status (ETA, size etc). You can select them to be copied to another machine. You can also do a global refresh of the list which picks up newly added torrents (this is quite an 'expensive' operation so I'm not making automatic - can be upto 20seconds to get the list from the daemon).

Each torrent entry is responsible for updating its own state if it's still downloading or is being copied. The parent handles the global refresh of the list and kicking off the copying.

There are several thousand child components on the page (it's kind of like a big directory listing), so when they are first created they check 'am I still actively doing something? If yes, then setTimeout() to refresh myself' - and that setTimeout re-checks and kicks off another setTimeout if needed. So children who are 'finished' don't do anything which keeps the amount of background 'stuff' down.

That's where I think the race is occurring. The child makes a setTimeout ajax request which is going to return that it no longer needs to update. While that is happening the parent sets the flag saying 'yes, you need to update as you're being copied' - which is immediately replaced with the ajax result saying 'ah, no you don't'.

I originally had the parent be in charge of all the state - but it got really messy keeping track of all the timeout's etc.

I'm now experimenting with making the parent emit an event which each child listens for - but I'm a little wary of having so many event listeners active on the page.

Anyway - thanks for your reply - it's given me things to think about :-) It's just a little 'xmas holiday project' which has gotten a bit out of hand - so if it isn't perfect it doesn't really matter. But I'll keep plugging away at it :-) Thanks again! :-)

13th December, 2017

ohffs started a new conversation Updating Data When Child Component Is Doing A SetTimeout() • 1 day ago

I've got a parent component which wraps a big v-for list of children. Each of the children can be refreshing itself via a setTimeout() to a back-end - all fine. The children can be checked and emit a 'selected' event which the parent uses to add them to a list which is in turn submitted as a bulk to the back-end - when that call is done it updates the status of a flag on the matching array elements that's used for the v-for.

All fine in theory and works most of the time. But I sometimes hit a problem where the child is updating itself just as the parent is doing the same thing and the flag the parent has set is cleared before it takes effect so the UI begins to get out of sync. Basically the if the flag the parent sets is cleared by the child refreshing at just the 'wrong' moment then the child doesn't realise it should keep asking the back-end for updates of itself.

I'm vaguely thinking vuex is supposed to solve this kind of thing, but I think I would just be moving the problem elsewhere.

Anyone have any ideas about keeping async children... in sync? :-)

12th December, 2017

ohffs left a reply on Adding 0.000005 To 0.000005? • 2 days ago

What isn't working? When you increment is it doing nothing? Have you tried setting the precision on the column to match what you need (eg, ->decimal('amount', 8, 10))

ohffs left a reply on Working Fine On Localhost But On Live (1/1) TokenMismatchException In VerifyCsrfToken.php (line 68) • 3 days ago

Not sure if this is related to other folk who are seeing this - but we had an app that behaving this way and it seemed to be that at one point it had been run with config:cache - then someone had manually edited the .env file and run config:clear but not then done a cache call again. Just running a final config:cache seemed to make the vast majority of the problem go away.

Anyway - might help someone :-)

11th December, 2017

ohffs left a reply on How To Separate Each Array Index Into New Arrays. (PHP Specific) • 4 days ago

Have a look at PHP's str_getcsv function - I think that's what you're after? Something like :

$splitArrays = [];
foreach ($originalArray as $line) {
  $splitArrays[] = str_getcsv($line);
}

8th December, 2017

ohffs left a reply on Pass Value To Array_first? How Can This Be Achieved? • 1 week ago

You could maybe do :

$i = 5;
$holding = array_first($array, function ($key, $value) use ($i) {
      return $key >= $i;
});

var_dump($holding);

5th December, 2017

ohffs left a reply on Testing Laravel Package With Multiple Providers • 1 week ago

@martinbean ah - it's so different apps can use it the way they need. Some use it just for an auth check, some do bulk LDAP directory look-ups of things, some apps are mix'n'match of internal & external users etc etc. So I tend to just want to do things like if (ldap::authenticate(...)) { $some_random_thing_per_app }

ohffs left a reply on How To Build Web Platform To Monitor/manage Assets At Different Sites? • 1 week ago

It sounds like you might be falling into the 'don't roll your own' security hole - but I can't really comment without knowing what it is you're doing. At the very least you seem to be doing 'rpc via chrome'? It seems a bit wasteful to have a copy of chrome running on every mini-pc though? I'm guessing you have to do it this way rather than using ssh or something else established like ssh/munin/zabbix etc?

ohffs started a new conversation Testing Laravel Package With Multiple Providers • 1 week ago

I'm writing a very simple package to wrap up some code I keep doing by the copy-from-old-project method just now. It's a simple wrapper around the php ldap extension to authenticate and look up users - really easy stuff.

It all works - but being a virtuous developer (ahem) I'm writing some tests for it. There are two service providers (one to do the actual connection to the LDAP server and one that consumes that to do the auth/lookups) and a facade. I can easily write a fake or mock the connection service and test that the code is roughly doing what it should.

But I'd quite like to be able to check the facade and 'wiring up' works too. Mostly just to check for typo's in the future. The problem seems to be that even if I over-write the container binding in the test, when the facade resolves it takes the value from the service provider rather than what's set in the test. Eg :

// ConnectionProvider:
        $this->app->bind(LdapConnectionInterface::class, function ($app) {
            return new LdapConnection(
                config('ldap.server'),
                config('ldap.ou')
            );
        });

// LdapProvider:
        $this->app->bind(LdapService::class, function ($app) {
            $connection = $app->make(LdapConnectionInterface::class);
            return new LdapService($connection);
        });

// test
        $this->app->bind(LdapConnectionInterface::class, function ($app) {
            return new FakeLdapConnection;
        });

        $this->assertTrue(\Ldap::authenticate('validuser', 'validpassword'));

When I make the call to the the \Ldap facade it always uses the 'real' LdapConnection in the provider. I'm using the orchestral testbench package to help build things, so it's possible that's contributing to my problem.

Anyway - if anyone has hit this before or can suggest anything let me know :-)

3rd December, 2017

ohffs left a reply on How To Build Web Platform To Monitor/manage Assets At Different Sites? • 1 week ago

Would the SSH component be any help? There's also the laravel envoyer package.

It might be worth looking into cockpit too - I think it works with Ubuntu these days as well as RH/Fedora.

1st December, 2017

ohffs left a reply on Aborting A Queued Notification • 2 weeks ago

Just to reply to myself if anyone else finds this question and is wondering how to do the same...

I eventually gave up and just made a queued job, which in turn sends the notification rather than sending a queued/delayed notification directly. So now the process is along the lines of :

MyJob::dispatch($whatever)->delay(now()->addMinutes(30));
...
class MyJob...

if ($whatever->hasBeenCancelled()) {
  return;
}
$someUser->notify(...);

Slightly annoying, but it works.

30th November, 2017

ohffs started a new conversation Aborting A Queued Notification • 2 weeks ago

I've got a situation where someone can click a button, which creates a queued job which is delayed by 30 minutes. In that time the user can change their mind and cancel the action. So the notification checks if the db has changed the state before sending and if it's been cancelled it should just silently quit.

But - I can't seem to make that happen. I've tried putting the logic in the via() method but that seems only to be called when the notification is first queued. If I put some sort of abort/return in the toMail() function the job fails as laravel is expecting a mailable back.

Does anyone have any ideas how to 'self abort' a queued notification?

27th November, 2017

ohffs left a reply on 60 Seconds Local Vs 2 Seconds On Production • 2 weeks ago

But what are you doing? Updating millions of small records, converting/importing data from a spreadsheet, creating 100's of new records in the test, or....? It's going to be hard for anyone to suggest anything without any idea what you're doing :-)

ohffs left a reply on 60 Seconds Local Vs 2 Seconds On Production • 2 weeks ago

Mmm.. maybe let us know what it is that's going slowly?

25th November, 2017

ohffs started a new conversation Cache/save Docker Image For Laravel CI • 2 weeks ago

I've got a CI setup (via gitlab) which runs inside a docker container - it works fine. But it's a bit slow to build the docker image each time the tests run (by 'slow' I mean 'a couple of minutes', so not exactly the end of the world but just enough to be a bit annoying).

Almost all the stuff I can find online is either 'pull down the base image then run apt-get...' or is an image geared to local dev rather than CI - but what I'd like to do is make my own image which had all of the php extensions, composer etc already installed. Where-as at the moment it pulls down the base image, then runs various commands to build the extensions, add things etc every time the CI is triggered.

Is that kind of thing possible? Basically build the image up until the point it'd be doing the git/composer/phpunit then save it as my own image? It feels like I'm just missing the right keyword in my google searches and all would be revealed... ;-)

20th November, 2017

ohffs left a reply on Using Redis On Shared Server With Multiple Laravel Application • 3 weeks ago

Maybe try setting different 'database' numbers for each app in config/database.php. The default is to use '0' so all your apps will be sharing the same redis 'database'. I think you can go from 0 to 15.

12th November, 2017

ohffs left a reply on One App Or Auth To Rule Them All? • 1 month ago

@neilherbertuk yeah - uk university, for my sins ;-) The jisc stuff is only partly helpful as we've entered the 'exciting challenge' of having campuses in other countries. Some of the apps have no connection to the wider internet either so I'm wary of adding another 'all the apps use auth-X, oh - except those two. And that one over there' ;-)

That's kind of the reason I was thinking of an internal oauth system which I at least have some control over. It at least means users only have to enter their username & password once - which covers most of the grumbling ;-) It's also easier to invalidate external users in one place than have to keep track of a dozen different local settings.

Thanks again for your replies - it's made me think a bit more about the problems and edge cases :-) Cheers :-)

ohffs left a reply on One App Or Auth To Rule Them All? • 1 month ago

Hi @neilherbertuk - thanks for the detailed reply :-)

Everyone currently logs in with their AD/LDAP username & password - but sadly I don't have any control over it so can't really use it for roles/permissions. We've also got external users from other org/institutions so some apps have to deal with that too. At the moment I'm doing much as you describe - a user logs in using their central credentials, then each app does what logic it needs to in terms of creating (or denying) an account etc.

We've got quite a large group of people using shibboleth already as part of the grid - I'll maybe have a dig at that.

I guess my question is more one of 'centralised vs distributed' - the pro's and con's of each in practice. That's kind of where I'm torn.

11th November, 2017

ohffs started a new conversation One App Or Auth To Rule Them All? • 1 month ago

A bit of a general question. We've got, say, a dozen internal laravel applications which have appeared over the years and a few more coming down the line. It's getting to the stage where enough people are using different applications that we're getting low-level complaints about having to log into the different apps all the time.

So.... I have two broad choices:

  • Make one 'mega-app' in which all the other apps are merged (even if they are really more like modules/packages installed in a wrapper).
  • Set up some kind of local oauth-esque system where users can just log in once and then they're automagically logged in to all the others.

However, in almost every application the given user will have a different role, permissions (or may not be entitled to access at all). So in both cases I end up with a somewhat tricky role management situation.

Once again - I could have a single shared mega-roles-table which had the permissions-per-app-per-user, or a per-app table - both seem to have pro's and con's in terms of ease-of-coding/ease-of-administration.

Anyway - just wondering if anyone else has dealt with this kind of thing or has any thoughts? Any input would be much appreciated - I'm kind of stuck in a 'well, on the one hand....' loop :-/

6th November, 2017

ohffs left a reply on Laravel - Like \ Dislike System • 1 month ago

Maybe have a look at polymorphic relations. You can have a relation/table which is associated with different models. So in your case you'd have something like :

// Used by model App\Like

Schema::create('likes', function (Blueprint $table) {
    $table->increments('id');
    $table->unsignedInteger('likeable_id);
    $table->string('likeable_type');
    $table->unsignedInteger('user_id');
    $table->timestamps();
});


// Post & Comment model

public function likes()
{
    return $this->morphMany('App\Like', 'likeable');
}

// Then you can do something like 
<p>
  This post has {{ $posts->likes()->count() }} likes
</p>

28th October, 2017

ohffs left a reply on Checkbox's • 1 month ago

Don't know about jsfiddle - but the code works ok when I put it in a proper .html file in my browser.

ohffs left a reply on Checkbox's • 1 month ago

This might do it in a fairly clumsy vanilla javascript way I guess :

<div id="section1">
    <input type="checkbox" name="thing1" value="1" onClick="clearAll('section2')">One
    <input type="checkbox" name="thing2" value="2" onClick="clearAll('section2')">Two
    <input type="checkbox" name="thing3" value="3" onClick="clearAll('section2')">Three
</div>

<hr>

<div id="section2">
    <input type="checkbox" name="other1" value="1" onClick="clearAll('section1')">One
    <input type="checkbox" name="other2" value="2" onClick="clearAll('section1')">Two
    <input type="checkbox" name="other3" value="3" onClick="clearAll('section1')">Three
</div>

<script>
    function clearAll(sectionName) {
        section = document.getElementById(sectionName);
        checkboxes = section.querySelectorAll('input[type=checkbox]');
        for (i = 0; i < checkboxes.length; i++) {
            checkboxes[i].checked = false;
        }
    }
</script>

23rd October, 2017

ohffs left a reply on The Visual Studio Code Thread • 1 month ago

@neovive yeah, the zen mode thing is a bit of a niggle. But they seem very active in addressing user requests so fingers crossed. I've tried various things to toggle files - it's purely that my muscle-memory hits cmd-p-return so in vscode I spend the day doing 'cmd-p-return :: argh! :: cmd-p-cursor-down-return' ;-)

ohffs left a reply on The Visual Studio Code Thread • 1 month ago

I've been trying it out a bit - really the one thing that's stopping me using it full-time is the muscle-memory I have for sublime's cmd-p to toggle between two open files. I must do it 100's of times a day. Even with the sublime keymap install in vscode it doesn't do quite the same thing.

Another minor nag is I haven't found a way to make the text in the 'zen' editor window (aka 'distraction free mode') be a bit more centred. On a large monitor it's left-aligned which is a bit annoying to look at.

The 'laravel goto view' extension is great - can't find anything quite like it for sublime.

5th October, 2017

ohffs left a reply on Caching (OPCache And Redis Question) A 3rd Party API • 2 months 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 months 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)
  {
    Cache::forget($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 months 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
CopyFile::dispatch('file1');

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 months ago

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

        Storage::fake('source');
        Storage::fake('destination');
// ... more setup

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

        Storage::disk('destination')->assertExists('file1');

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? • 2 months ago

@JoeDawson yay - glad it helped :-)

15th September, 2017

ohffs left a reply on How Can I Build This Package? • 2 months 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!) :

<?php

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 • 3 months 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 • 3 months 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? • 4 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 ! • 4 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 • 4 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 • 5 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? • 5 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 • 5 months ago

What database are you using?

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

Pikaday is a nice small option too.

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

<?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 • 5 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.

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

22nd June, 2017

ohffs left a reply on Folder Picker • 5 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 • 5 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 • 5 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 • 6 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 • 6 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 • 6 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?

Edit Your Profile
Update

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