alexleonard

Experience

15,640

0 Best Reply Awards

  • Member Since 3 Years Ago
  • 155 Lessons Completed
  • 4 Favorites

18th January, 2018

alexleonard left a reply on Local Filesystem On Load Balanced Servers • 11 hours ago

Brillo, thanks for the pointers!

alexleonard left a reply on Local Filesystem On Load Balanced Servers • 12 hours ago

Ah, a bit like https://serverfault.com/a/410599 ?

I'll go investigating on my local machines

alexleonard started a new conversation Local Filesystem On Load Balanced Servers • 12 hours ago

I have load balancing set up to split a Laravel site between multiple servers and have been running into issues using local file storage.

For compliance reasons we can't use a remote Flysystem adapter (eg AWS), and I haven't worked out the best way to handle user uploads (eg image uploaded to Server A, but not available Server B). At the moment we just have a scheduled rsync to keep Server A and B public disks in sync, but it's not instant.

I believe we could set up some form of folder watching to trigger sync between the servers but I was wondering is there an easy way to set up the local flysystem adapter/public disk to actually store files on a single server shared between load balanced web server? Thus Server Z would be just Laravel 'local' storage, and Server A and B would read/write to Server Z?

DevOps is not entirely my forte... ;)

21st November, 2017

alexleonard left a reply on Codecept, Guzzle And Mocking Responses • 1 month ago

Well that's a blast from the past! Thanks for putting in the time to respond though.

I haven't actually used Codeception in ages and am now just using vanilla laravel phpunit.

This could still, as a result, be very helpful. I was being lazy and just hitting our clients API and testing the results. Now just need to slowly phase out the old real API hits with mock hits/responses.

Thanks!

15th May, 2017

alexleonard left a reply on Need Help On Passport::routes() • 8 months ago

Plus it should be pointed out that you can also easily specify which route types you want to load.

For example we have a use-case where we are only using the client credentials grant type and don't want to offer other grant types.

    public function boot()
    {
        $this->registerPolicies();
        
        Passport::routes(
            function ($router) {
                $router->forClients();
            }
        );

You can specify any of the methods available in: /vendor/laravel/passport/src/RouteRegistrar.php

11th May, 2017

alexleonard left a reply on Laravel /passport And Postman Gets All The Time ⌚ Unauthorised • 8 months ago

Thanks @llamorin.jason the new .htaccess rule sorted me out.

Weirdly I had previously implemented exactly the same approach on another site on my development environment, all the apache settings are the same, and it worked on the first site without any .htaccess modification, but not on the second.

27th August, 2016

alexleonard started a new conversation Reverse Lookup In Polymorphic Relations • 1 year ago

I just wanted to clear something up which I'm not 100% sure on. So I had a simple App\Report which hasMany App\Note but then it became clear that my notes needed to be related to multiple different models, so I've changed it out to be polymorphic.

//App\Report
    public function notes()
    {
        return $this->morphMany('App\Note', 'noteable');
    }

// App\Investigation
    public function notes()
    {
        return $this->morphMany('App\Note', 'noteable');
    }
// App\Note
    public function noteable()
    {
        return $this->morphTo();
    }

This works great. But I'm not 100% sure how to get all notes that 'have' a report (eg I want to see an index of notes belonging to reports but not to Investigations).

When it was a normal one-to-many relation I was just running.

        $notes = $note->whereHas('report', function ($q) use ($reportHashid) {
                                $q->visible()->whereHashid($reportHashid);
                            })->get()

Now I know I could do this the other way around, find report by hashid and then $report->notes, but I'm curious about how to constrain a general notes query by noteable_type.

Do I just change my queries to

$notes = $note->whereNoteableType('App\Report')->noteable()->get();

or is there another way to approach it?

I did notice I could sort of fudge it by adding this extra relation to App\Note:

    public function report()
    {
        return $this->belongsTo('App\Report', 'noteable_id');
    }

14th April, 2016

alexleonard left a reply on Testing API - $request->get() Returns Null • 1 year ago

A bit late on my response.

$request->all() works, but in my controller I need to $request->get() a specific item. It's just weird that using tests' $this->json() method suddenly stops $request->get() from working.

So I have to modify my FormRequest/Controller to use $request->parameter just to ensure my tests are passing.

4th April, 2016

alexleonard started a new conversation Testing API - $request->get() Returns Null • 1 year ago

So I'm building up a small internal API for an app which will be used by Angular and am trying to write tests for it.

Previously I had setup a normal, non-api version of a simple user create/store, and everything works as normal there, and I can use $request->get() without issue.

public function store(UserRequest $request, User $user) { dd($request->get('status')); } With an associated test using $this->call() I get the string dumped out as normal

but in my api, test, if I do $this->json(), suddenly $request->get() just returns null. eg

$this->json( 'POST', route('api.user.store'), [ 'status' => 'active', 'first_name' => 'FirstName', 'last_name' => 'LastName', ] )

I can still access the parameter by doing say $request->status instead of $request->get('status'), but feels a bit weird.

I had read somewhere that I was going to need to set my enctype on ajax POSTs to multipart/form-data but doing that caused other weird issues.

4th March, 2016

alexleonard started a new conversation Laravel Cashier: Multiple Credit Cards • 1 year ago

I'm guessing the answer to this is going to be: bypass Cashier - but I thought I'd check in case anyone had worked on this before.

Planning to build a site where a user can add credits to their account. They can have multiple cards added to their account and switch and choose which card to charge before adding credit.

I don't think this is possible with Cashier out of the box, but anyone done this before? Can it be done using Cashier as a base and overwriting some of the core methods? Or better to roll our own approach?

13th January, 2016

alexleonard left a reply on Query Where Has Related Record That The Second Item Matches • 2 years ago

This is what I've gone for in the end. This in in a scope, so ultimately it's restricting the overall query if there are any matches, it will return only those that match, but if there are no matches no results will be returned. Sadly it does require both a second query to be made and a PHP loop, but I'm failing to see another way to go about it.

I did also try restricting the ->with() callback function to ->skip(1)->take(1), but this seemed to only work for the first deal's activities, and further deal activities were returning no results. So as a result I used ->pull(1) to grab the penultimate activity out of the relation and compare it against my queries $lastAssignedId

If anyone can think of a more graceful way to do it, I'm all ears :)

$deals = app('App\Deal')->visible()->has('activities', '>', 1)->with(
    [
        'activities' => function ($q) {
            $q->whereAction('Assigned the deal')
              ->whereNotNull('new_salesperson_id')
              ->orderBy('created_at', 'desc');
        }
    ]
)->get();

$dealIds = [];

foreach ($deals as $deal) {
    $activity = $deal->activities->pull(1);

    if (isset($activity['new_salesperson_id']) && $activity['new_salesperson_id'] == $lastAssignedId) {
        $dealIds[] = $deal->id;
    }
}

$dealIds = empty($dealIds) ? [0] : $dealIds;

$query = $query->whereIn('id', $dealIds);

alexleonard left a reply on Query Where Has Related Record That The Second Item Matches • 2 years ago

Hey Jekinney,

Thanks for the reply. Not sure if the contains method will do it, but I think you're probably right about grabbing all the data and then cycling through it in PHP to get the correct results.

Thanks!

alexleonard started a new conversation Query Where Has Related Record That The Second Item Matches • 2 years ago

I'm trying to work out if there's an eloquent way to run the following query.

I have a deals table and a deal_activities table. Deals are assigned to a user. Each time a deal is assigned, or reassigned to a user, a record is made in the deal_activities table recording the new user assignment.

This way I can show the assignee history by doing

$deal->activities()->whereKey('assigned')->orderBy('created_at', 'desc')->get()

However I also need to be able to query deals where the penultimate user was a specific user.

In psuedo code: Get deals where has activities where the second most recent record = $userId

However using things like skip() and take() in the relationship query don't seem to be the way to go about it.

eg

        $deals = $deal->whereHas(
            'activities',
            function ($q) use ($lastAssignedId) {
                $q->skip(1)->whereAssigneeId($lastAssignedId)->take(1);
            }
        );

As soon as I wrote that, I realised that wasn't the way to go about it at all. Plus we can't match assignees earlier than the penultimate either:

  1. Deal 1 was assigned to User X, then User Y then User Z.
  2. A search for deals last assigned to User X would not return Deal 1, but a search for deals last assigned to User Y would return Deal 1

Any ideas?

15th December, 2015

alexleonard left a reply on Laravel, Sessions, And IOS 'full Screen Web Apps' • 2 years ago

Also, is there a more laravelly way to get around this? :)

alexleonard started a new conversation Laravel, Sessions, And IOS 'full Screen Web Apps' • 2 years ago

I've come across a potential issue which is a little hard for me to test as I don't have an iOS device, but my client is reporting that using their L5 powered web app, if they enter it through iOS's 'full screen web app' mode, any time they close it and reopen it they have to log in again.

I actually have the app set up with a hardcoded 'remember me' boolean during the auth process, and I separately auto log out users after 4 hours. config.session.expire_on_close is set to false.

Any browser I've tried works as expected.

I found this thread about iOS full-screen web apps on StackOverflow: http://stackoverflow.com/questions/7077518/ios-full-screen-web-app-drops-cookies which seems to suggest that for some reason you have to rewrite the session cookie to make it stick with this iOS mode.

setcookie(session_name(),session_id(),time()+$lifetime);

Anyone come across this before?

13th August, 2015

alexleonard started a new conversation Firing A Command When A Queue Is Finished? • 2 years ago

Every night I'm going to be importing a large dataset into my application and we're doing a certain amount of pre-caching of different search queries on the dataset.

Each dataset record import is queued and when the queue is finished I need to clear a certain set of cache tags. I was searching through the queue/event/scheduling docs for 5.1 but wasn't seeing any obvious way to trigger something when a specific queue is emptied.

I could pass a 'last-record' => true flag into the queued record creation which triggers the cache tag clearing, but thought I'd check if there was some inbuilt thing I was missing :)

30th July, 2015

alexleonard started a new conversation Sessions No Longer Persisting When Using Array Driver In Codeception Tests • 2 years ago

I have a new 5.1 project and set up the Codeception testing end of things pretty much the same as my last 5.0 project. I have a .env.testing file which codeception references and that has a SESSION_DRIVER set to array.

However for some reason now, sessions are not persisting.

For example if I do this in a functional test:

session(['test' => true]);
$I->submitForm('.test', ['title' => '']);
dd(session('test'));
$I->seeFormErrorMessages(['title' => 'The title field is required.']);

and run the test, the die and dump outputs 'null'.

If I remove the dd() then the expected formErrorMessage is non existent, but testing it manually in the browser the error message appears as expected.

Interestingly, if I tail the logs I can see that a TokenMismatchException is being thrown.

For interests sake I overrode the handle() method in App\Http\Middleware\VerifyCsrfToken to always return $next($request); and that correctly stops the TokenMismatchException being thrown, but the dd() still returns null, or with the dd() removed from above the test still fails.

If I change my SESSION_DRIVER in .env to file, then the test passes correctly with no errors, but if I try to run more than one test using the file driver, then the first test passes but after that codeception gets stuck on the second test, reporting nothing. I tried using database as a driver as well (I have the relevant session tables setup) and the same thing happened - runs fine with only one test, gets stuck on second test if there are more than one test.

.env.testing relevant variables

APP_ENV=testing
APP_DEBUG=true

DB_HOST=localhost
DB_DATABASE=l5_tests
DB_USERNAME=test
DB_PASSWORD=test
    
CACHE_DRIVER=array
SESSION_DRIVER=array
QUEUE_DRIVER=sync

Codeception version:

% vendor/bin/codecept
Codeception version 2.1.1

Codeception.yml

actor: Tester
paths:
    tests: tests
    log: tests/_output
    data: tests/_data
    helpers: tests/_support
settings:
    bootstrap: _bootstrap.php
    colors: true
    memory_limit: 1024M
modules:
    config:
        Db:
            dsn: 'mysql:host=localhost;dbname=l5_tests'
            user: 'test'
            password: 'test'
            dump: tests/_data/dump.sql

I'll do a clean install of L5 && Codeception in the morning and see if I can continue to replicate the issue, but thought I'd post this here in case anyone else is having the same issue.

25th May, 2015

alexleonard started a new conversation Running Homestead In Host And Accessing It From Another Guest • 2 years ago

I have a Windows laptop (for running my music production software), but for my day job I boot up a VM running Lubuntu.

I can't run vagrant/homestead inside the VM, but I'm wondering whether I could setup vagrant/homestead to run as one VM in Windows, but then access it from my Lubuntu VM?

Has anyone tried this sort of setup before?

Cheers, Alex

8th April, 2015

alexleonard left a reply on Compiling LESS On The Fly • 2 years ago

Thanks again for the guidance.

In the end I used a slightly different package: https://github.com/oyejorge/less.php as it had it's own bundled caching.

<?php namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Less_Cache;
use App\Company;

class CssController extends Controller {

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function render($id, Less_Cache $less, Company $company)
    {
        $company = $company->findOrFail($id);

        $less_files = [base_path() . '/resources/assets/less/app.less' => '../'];
        $options = ['cache_dir' => storage_path() . '/app'];
        $css_file_name = Less_Cache::Get($less_files, $options, $company->cssColourVariables);

        // Get the compiled version and return it
        $compiled = file_get_contents( storage_path() . '/app/' . $css_file_name );
                return response($compiled, 200)
                        ->header('Content-Type', 'text/css');
    }
}

It's working great!

19th March, 2015

alexleonard left a reply on Compiling LESS On The Fly • 2 years ago

Sweet. Thanks for the responses. I think that's set me on the right path now :)

I'll have a play with this tomorrow and see if I can get it up and running. I'll post my results.

alexleonard started a new conversation Compiling LESS On The Fly • 2 years ago

I'm building an application where multiple companies can be added to the system. Each company can, optionally, modify some of the colour elements on the site.

I was looking at this package: https://github.com/hellogerard/less-slim-middleware as perhaps being something that could be used to generate and cache the LESS on the fly but am not really sure how it would work - I'd need to get HEX colour codes from the database and into some LESS variables in a LESS file for dynamic generation.

Perhaps that's not an option. I thought it might be best to ping here to see if anyone's done this before and had any advice.

I'm assuming I'd need something whereby I have my default-variables.less file, and then say default-rules.less which imports all my standard rules. Then a default.less file which imports default-variables.less and default-rules.less.

For each company I'd need to have a company-name.less file which imports default-variables.less, overrules the specific colour variables, then imports default-rules.less. But I'm not really sure how to do this dynamically, with caching..!

Any suggestions?

2nd March, 2015

alexleonard left a reply on Codeception New Laravel5 Module Throwing Fatal Error • 2 years ago

Changes proposed in the pull request sort it out :)

https://github.com/Codeception/Codeception/pull/1750

26th February, 2015

alexleonard left a reply on Codeception New Laravel5 Module Throwing Fatal Error • 2 years ago

I should also point out that the site is running fine when browsing normally and not throwing any errors. A bit baffled.

alexleonard started a new conversation Codeception New Laravel5 Module Throwing Fatal Error • 2 years ago

I just ran a composer update on a project and previously my tests were running and passing fine, but now I get:

PHP Fatal error:  Call to undefined method Symfony\Component\HttpFoundation\Request::route() in /path/to/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php on line 146
                                                                              
  [Symfony\Component\Debug\Exception\FatalErrorException]                     
  Call to undefined method Symfony\Component\HttpFoundation\Request::route()  
                                                                              
  [Symfony\Component\Debug\Exception\FatalErrorException]                     
  Call to undefined method Symfony\Component\HttpFoundation\Request::route()  

FATAL ERROR. TESTS NOT FINISHED.
Call to undefined method Symfony\Component\HttpFoundation\Request::route() 
in /path/to/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php:146

Then I noticed that the L5 module by @JanHenkG has been pulled into the main Codeception package so I removed "janhenkgerritsen/codeception-laravel5": "dev-master" from composer (leaving "codeception/codeception": "~2.0" as was) and updated again, and made sure to run codecept build again, but still the fatal error kicks in whenever I try to run any of my functional tests (don't currently have unit/acceptance tests on this project).

I checked through the sample project and I'm pretty sure the various yml files are configured correctly:

codeception.yml

actor: Tester
paths:
    tests: tests
    log: tests/_output
    data: tests/_data
    helpers: tests/_support
settings:
    bootstrap: _bootstrap.php
    colors: true
    memory_limit: 1024M
modules:
    config:
        Db:
            dsn: 'mysql:host=localhost;dbname=l5_site_testing'
            user: 'root'
            password: ''
            dump: tests/_data/dump.sql

functional.suite.yml

class_name: FunctionalTester
modules:
    enabled: [Filesystem, Laravel5, Db]
    config:
        Laravel5:
            environment_file: .env.testing

.env.testing

APP_ENV=testing
APP_DEBUG=true
APP_KEY=32charstringhere

DB_HOST=localhost
DB_DATABASE=l5_site_testing
DB_USERNAME=root
DB_PASSWORD=

CACHE_DRIVER=file
SESSION_DRIVER=native
QUEUE_DRIVER=beanstalkd

Anyone else come across this error?

3rd February, 2015

alexleonard left a reply on [L5] Any Image Size Validator Packages For L5? • 2 years ago

Cool. Fingers crossed. That's a handy wee package. Be great to have it ported to L5 :)

alexleonard started a new conversation [L5] Any Image Size Validator Packages For L5? • 2 years ago

I've used https://github.com/cviebrock/image-validator for L4, but it hasn't been updated for use in L5 yet.

Anyone know of a image validator that would work for L5? For validating things like image filesize, min/max width/height and so on.

alexleonard left a reply on How To Best Approach User Controlled Ordering And Visibility • 2 years ago

Nice! I didn't know that was an option. Lovely :)

alexleonard left a reply on How To Best Approach User Controlled Ordering And Visibility • 2 years ago

Hey guys,

I've momentarily abandoned my database queries efficiency (although potentially a raw query like @JarekTkaczyk has pointed out will work very nicely!).

So I have re-added a sort_order column (tinyInteger) to my Portfolio table. It occurred to me that I don't need to worry about a 'visible' column, as the visible items will just be the ones that have a sort_order value.

So for displaying on the front end I just use:

$portfolio->orderBy('sort_order', 'asc')->take(4)->get();

And that works fine.

On the back end, I still have a form with 4 select elements, each select has a full list of all Portfolio records (eg {client name}

When that form is submitted I do

$portfolios = Portfolio::all();

// Reset sort_order on all portfolio records
foreach ($portfolios as $portfolio) {
    $portfolio->sort_order = null;
    $portfolio->save();
}

$i = 1;

foreach ($request->get('sort_order', []) as $portfolioId) {
    $portfolioRecord = $portfolio->find($portfolioId);
    $portfolioRecord->sort_order = $i++;
    $portfolioRecord->save();
}

return back()->withNotification('Portfolio order has been updated');

Whilst not query efficient in the admin area, it does mean only one query on the front end. And in theory I should be able to adapt it to be more efficient on the back end when POSTing the sort_order form.

alexleonard left a reply on How To Best Approach User Controlled Ordering And Visibility • 2 years ago

@pmall Ah, I was just assuming that I was missing something obvious :) It seemed inefficient to have to query all Portfolio records and update each one just to change the sort order (especially given that I only actually need to specify 4 records at any one time). Whilst another table might also seem excessive to handle it, I figured it might result in a lot less DB querying?

alexleonard left a reply on How To Best Approach User Controlled Ordering And Visibility • 2 years ago

@martinbean But if I have a 'sort_order' column, do I not have to update every record in the table every time the sort_order is changed?

@JarekTkaczyk Looks like I wasn't clear enough again :)

So my Portfolio model/table has:

id
client
description
tags
photo_id (eg featured photo)
url

Additionally the Portfolio hasMany photos (for its gallery). However I'm not concerned about the 'sort order' of the gallery. Just the portfolio records.

On the front end, the Portfolio is only ever going to show 4 records, and the user must have the ability to decide which records appear and in what order. I was planning on having a single view in the back end where the admin user selected the 4 portfolio records which would be shown on the front end. But I was struggling to work out the most efficient way to do that, such that it didn't require multiple queries either when saving or when displaying.

2nd February, 2015

alexleonard left a reply on How To Best Approach User Controlled Ordering And Visibility • 2 years ago

I was vaguely thinking a one-to-many type approach where there was an order table with

id
portfolio_id

I could seed this table with 4 records and never increase that amount (only edit each of the 4 records)

Then in theory I could do something like

Model: Order

protected $with = ['portfolio'];

Front end portfolio controller

$orders = Order::all();

View

@foreach($orders as $order)
    {{$order->portfolio->name}}
    // etc
@endforeach

That would be efficient on the front end, but it would require 4 separate record updates each time the back end ordering form is updated.

alexleonard started a new conversation How To Best Approach User Controlled Ordering And Visibility • 2 years ago

I've been having a bit of trouble trying to work out the best approach to this and thought I might be able to get some advice here.

The requirement

I'm building a portfolio. The portfolio needs to be set up such that the admin user can decide which portfolio items are visible on the front end, and in what order they appear.

The portfolio will have items added to it over time, but the front end will only display up to 4 items at once.

What I've been trying

At first I was thinking I'd have a few extra columns on my portfolio table, such as

boolean('visible')->default(0);
tinyInteger('order')->nullable();

I then looked at creating a single view which would contain 4 select inputs (name="order[]"), each select containing a list of all the portfolio records. They could select them in the order they wanted and then I would take the POSTed array and loop through them, setting the ids posted to be visible and incrementing the order.

But then I realised that I'd need to reset older visible/order records before doing that, and suddenly I realised I'd be getting into a whole chunk of database queries.

So then I thought, well what if I just have a 'portfolio_ordering' table. That could just have one column which stored a serialised array of the preferred ordering. In fact it could just be one record which got overwritten any time the order/visibility was changed.

This sort of works, and when displaying on the front end I have to get the ordering/visibility record first before I can get the portfolio records. I was thinking I could just use whereIn, but then my ordering isn't carried through. So I'd need to approach that slightly differently.

But then I stopped

Am I missing something very obvious? Is there a better way to do this? The first approach seems most logical for queries. It would allow something like

Porfolio::whereVisible(1)->orderBy('order', 'asc)->get();

But then as far as I could see I'd end up with a messy situation when trying to update that data from the admin ordering/visibility form.

At the end of the day here, so perhaps the brain just isn't seeing clearly... any query efficient suggestions much appreciated!

Cheers, Alex

alexleonard left a reply on [L5] Codecept Broken Since Bootstrap/start.php Removed • 2 years ago

D'oh. And there was I thinking I had double checked everything. Sorry dude...

You've fixed me up once again! Working straight out.

alexleonard left a reply on [L5] Codecept Broken Since Bootstrap/start.php Removed • 2 years ago

Hmm, I wonder what's causing it to not pick it up.

Here's a screenshot showing my functional.suite.yml, .env.testing, the Cept where I dd env values, and my composer.json file, plus CLI output of composer update, 'codecept build, andcodecept run`.

https://drive.google.com/file/d/0Byi9NAYvWDPfRFBRdFRuRldIaEU/view?usp=sharing

It seems to wholly be picking up the standard .env instead of .env.testing.

I'll have a bit more of a dig around and see whether I can find out anything else.

Sorry about this!

30th January, 2015

alexleonard left a reply on Many To Many Polymorphic With Additional Identifiers • 2 years ago

Tak! Indeed I am here :) Moved here in August. My fiancee is Polish (surname Snochowska). I have struggled immensely to get anywhere learning Polish though, although I'm definitely in winter hibernation mode so I spend most of my time working on web development and music production in the warmth. Not so much opportunity for Polish practice.

Getting married here in Zakopane in June :) The Irish-Polish connections continue to strengthen.

And thanks for the correction on that, I did indeed mean belongsTo :)

alexleonard left a reply on Many To Many Polymorphic With Additional Identifiers • 2 years ago

@JarekTkaczyk

You're talking a lot of sense there! Don't worry, I'm definitely not disappointed (considering the evident struggle I've had conceptually here) :)

I think that will cover things perfectly. I guess I hadn't thought of setting up a hasOne for the Portfolio featured image, and a separate hasMany for the Portfolio gallery. That all sounds like it makes good sense to me and will save me lots of headaches.

Thanks for sticking with me and helping me get my head around it all. So really the best type of polymorphism example is the 'tags' type example, where multiple tags can be related to multiple models, then you save on wasted tables. But in my case because only one of my models actually requires a many to many relationship, the approach you have suggested is much more efficient.

Brilliant! I think I have that all a lot clearer in my head now. Thanks from me in snowy Zakopane!

alexleonard left a reply on Many To Many Polymorphic With Additional Identifiers • 2 years ago

Sorry I should have been a bit clearer. There's definitely an art to asking the right question!

The same single photo could

  1. Belong to a Post (as featured image - and yes, only one featured image)
  2. Belong to a Portfolio (as featured image - only one feature image)
  3. Belong to a Portfolio (as one of its gallery images - multiple images)

Additionally, I'm going to have some Meta management which would allow that single photo to also be used as as Facebook/Twitter meta image.

So I think the morphing does make sense, it's just a question of, as you originally suggested, using pivot data to specify whether the photoable is featured or gallery (when photoable is related to a App\Portfolio record). When the photoable is related to Post or a Meta record, then I don't need to set the pivot data.

That all is starting to make sense in my head now, thanks. I have a feeling if I tried to do the above without a polymorphic setup I'd start to run into some confusion :)

alexleonard left a reply on No Longer Receiving Laracast Forum Emails • 2 years ago

I sometimes get email notifications, and other times I don't. Then I check the thread and see the subscribe checkbox is no longer ticked, even though I didn't change it.

Perhaps there's some funny logic issues going on with updating (or failing to update) thread subscriptions?

alexleonard left a reply on Many To Many Polymorphic With Additional Identifiers • 2 years ago

Fair point @JarekTkaczyk!

So the logic behind it is that the user can upload photos to the system and those photos can be related to one or more models in the application.

For example, if they create a new Page, they can set a featured image for that page either by uploading a new Photo or relating it to a previously uploaded Photo.

They could also create a Portfolio record which can have both a featured image and a gallery of images.

So my thinking behind an extra 'featureables' table would be that it would allow a page and a portfolio item to both share the same featured image, but I'm thinking that if I set up a pivot on the original photoable table, and say

  1. Page 1 has photo 1 related via photoable
  2. Portfolio has photo 1 related but as a gallery image

Oh, hang on... they'd have two separate photoables records, so the pivot would exist on the photoables table and I wouldn't have the issue I was thinking I'd have.

I think my brain was placing the pivot data on the photos table, not the photoables table.

Ok, let me have a play around with this and see if I can get a sample up and running.

Thanks!

alexleonard left a reply on Many To Many Polymorphic With Additional Identifiers • 2 years ago

Thanks for the ideas folk. Whilst lying in bed last night completely failing to fall asleep it occurred to me that I could do the following.

Create a new table called featureables with

  • photo_id
  • featureable_id
  • featureable_type

and then add another relationship in my Portfolio model

public function featuredPhotos()
{
    return $this->morphToMany('App\Photo', 'featureable');
}

I think the extra table would be justified and would avoid any issues where one photo is set as 'featured' on multiple models?

What do you think?

29th January, 2015

alexleonard started a new conversation Many To Many Polymorphic With Additional Identifiers • 2 years ago

I haven't started coding this because I'm having a slightly difficult time wrapping my head around what would likely be the best approach.

So, I want to have say Portfolio and Page models. Both of these models can access a single Photo to use in SEO meta (for twitter sharing etc), but the Portfolio also needs to have a 'featured' photo which will be used as a thumbnail, but then can also have multiple photos to be displayed in a gallery.

I'm pretty sure I can set up the general morph stuff (although perhaps I'm still thinking in a flat polymorphic structure, not a many to many polymorphic structure) so that the Portfolio can have multiple images related to it, but how do I handle identifying a specific image as the 'featured' image vs the gallery images.

Ultimately I'd want to be able to do

$portfolio->featuredImage->filename

and

@foreach($portfolio->galleryPhotos as $photo)
    $photo->filename
@endforeach

I'm not sure out of the box that many to many polymorphism will do it, I seem to end up with a default photoables table like

+----+----------+--------------+----------------+
| id | photo_id | photoable_id | photoable_type |
+----+----------+--------------+----------------+
|  1 |        1 |            1 | App\Meta       |

I guess I could add a portfolio_id field to the photos table and set up an additional hasOne relationship, but that sort of feels like I'm not doing it the right way..

Any advice hugely appreciated.

Thanks! Alex

alexleonard left a reply on [L5] Codecept Broken Since Bootstrap/start.php Removed • 2 years ago

Thanks for getting back to me.

I tried that just now

Modified functional.suite.yml to be

class_name: FunctionalTester
modules:
    enabled: [Filesystem, Laravel5, Db]
config:
    Laravel5:
        environment_file: .env.testing

Created .env.testing in my project root:

APP_ENV=testing
APP_DEBUG=true
APP_KEY=some31charstring
DB_HOST=localhost
DB_DATABASE=testing
DB_USERNAME=root
DB_PASSWORD=
SESSION_DRIVER=native
MAIL_PRETEND=true

And then threw dd(\App::environment()); into my first cept which returned:

Functional Tests (12)
Trying to edit a page meta data (Admin/Meta/MetaEditCept)
"local"

Oh, I made sure to composer update (I'm using "janhenkgerritsen/codeception-laravel5": "dev-master"), and did a codecept build as well just in case.

Anything I might be missing?

28th January, 2015

alexleonard left a reply on [L5] Codecept Broken Since Bootstrap/start.php Removed • 2 years ago

Hey @JanHenkG

I'm a total idiot! Can't believe I didn't spot this before but I after I submitted the form in the cept I had

$I->amOnRoute('public.contact');

Not

$I->seeCurrentRouteIs('public.contact');

Ahem... Sorry about that.. it's working now!

One other thing

Before I spotted that though I did notice something that seemed unusual. See the returns when I fire the following in my cept:

dd(\App::environment());
    // returns "local"
dd(\Config::get('session.driver'));
    // returns "array"

Pretty certain last time I did that I got "testing" and "native".

Not sure why it wouldn't be returning the 'testing' environment.

I tried editing the functional.suite.yml to include

class_name: FunctionalTester
modules:
    enabled: [Filesystem, Laravel5, Db]
config:
    Laravel5:
        environment: testing

But it still reports 'local'. Perhaps I need to do something new with .env files?

26th January, 2015

alexleonard left a reply on [L5] Codecept Broken Since Bootstrap/start.php Removed • 2 years ago

Hey @JanHenkG,

Thanks for the speedy response!

I checked out those new methods seeFormHasErrors and seeFormErrorMessages and tried them out, sadly both to no avail. I either get

Couldn't see form has errors :
Failed asserting that false is true.

or

Couldn't see form error messages {"email":"We need your email address so we can reply to you."}:
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'We need your email address so we can reply to you.'
+''

I tried turning off my old TestingServiceProvider as well (which would set Session back to the current default which is just file, but no joy there (although perhaps this no longer makes a difference), I'm leaving the testing env on native for the time being anyway.

My packages are all up to date and I'm using dev-master for your L5 Codecept module, other than that it's pretty much a fresh L5 install.

I have a troubling feeling that I'm missing something patently obvious!

alexleonard left a reply on [L5] Codecept Broken Since Bootstrap/start.php Removed • 2 years ago

@JanHenkG I've just started a new L5 project and seem to be running into issues getting my session variables to be seen after form posts and so on by Codecept. I thought it would make sense to check back in from this thread as there's a bunch of Session related stuff in here.

So I have a very simple contact form I'm testing, and I want to make sure that when the form is submitted with no data, the user gets standard error messages back.

$I->submitForm('#pa-contact-form', []);
$I->amOnRoute('public.contact');
$I->see('Do not forget to include your name.');

Whilst it's working as expected when manually submitting the form in the browser (the session->has errors and displays them).

But if I dd(Session::all()) in codecept right after Codecept submits the form, there are no errors in the session.

So perhaps something has changed since the last time I set this up. Following your previous advice I set up a TestingServiceProvider and registered it in config/app.php after the SessionServiceProvider.

<?php namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class TestingServiceProvider extends ServiceProvider {

         /**
            * Register the service provider.
            *
            * @return void
            */
        public function register()
        {
                if ($this->app->environment() == 'testing')
                {
                    $this->app['config']['session.driver'] = 'native';
                }
        }
}

If I dd(Config::get('session.driver') in Codecept it correctly returns 'native'. So I know the environment is being set to testing, and I know I'm using the native session driver, but I'm still not seeing the expected errors key in the session.

Perhaps I've forgotten some other step I needed to take to get it running.

I'm also using the L5 module for codecept functional tests (here's my functional.suite.yml)

class_name: FunctionalTester
modules:
    enabled: [Filesystem, Laravel5, Db]

Am I missing something obvious?

20th January, 2015

alexleonard left a reply on Anyone Else Getting An Odd Composer Update Error Today? • 2 years ago

Even though my composer wasn't out of date, it looks like a composer self-update was required.

Thanks @darryldecode

19th January, 2015

alexleonard left a reply on Anyone Else Getting An Odd Composer Update Error Today? • 2 years ago

This is on my local machine, I haven't used homestead yet (I'm already in a virtual machine). Composer is up to date all right. Not getting composer errors on other projects either. Quite odd. Especially considering I can't see any mention of ^1.0.1 anywhere except my node_modules folder.

alexleonard started a new conversation Anyone Else Getting An Odd Composer Update Error Today? • 2 years ago

I started a fresh new laravel project last week and just came back to it to update a few things and make sure I'm keeping up with laravel/laravel develop commits.

First thing I did was composer update but this threw an error:

Could not load package phpspec/phpspec in http://packagist.org: [UnexpectedValueException] Could not parse version  constraint ^1.0.1: Invalid version string "^1.0.1"  

I did have phpspec/phpspec in my require-dev (although version ~2.1) so I commented that out of my composer.json and re ran composer update.

Sadly I still continued to receive the error.

I searched through my project for instances of phpspec/phpspec and none of them specify ^1.0.1 so I'm not really sure what's causing the error.

Anyone else getting this error on a composer update?

14th January, 2015

alexleonard left a reply on That Is The Question. Is It Time To Be Using Laravel 5? • 3 years ago

Very excited to hear when the beta finally touches down. I've got a new project coming up and would really love to start it on L5 beta!

11th December, 2014

alexleonard left a reply on [L5] Dec 4th Commit: Call To Undefined Method Illuminate\Config\Repository::package() • 3 years ago

Does anyone know if this has been rectified yet? A little worried that I'm falling behind on laravel/laravel updates by avoiding composer updating..

Edit Your Profile
Update

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