Jam0r

Experience

25,400

0 Best Reply Awards

  • Member Since 1 Year Ago
  • 223 Lessons Completed
  • 18 Favorites

14th September, 2018

Jam0r left a reply on How To Add Pagination In Laravel Nova Tool? • 1 week ago

I'd imagine you have to use it yourself.

Have a look at index.vue within the Nova resources directory and see how Taylor does it.

19th August, 2018

Jam0r left a reply on What Is Your Preferred Re-factor Method? • 1 month ago

Thank you for the examples!

Keep them coming.

I'm currently using mostly events and listeners with the events being called from within the model observers automatically.

Jam0r started a new conversation What Is Your Preferred Refactor? • 1 month ago

When using solely Eloquent (so technically no need for repositories) what is your preferred method of choice when it comes to refactoring and performing multiple operations on CRUD events.

Observers? Events and Listeners? Repositories? Add helper methods to eloquent models?

An example..

I have a tenancy management app and every month I record a received rent payment which at the same time should create a statement along with an invoice and its corresponding invoice items whilst grabbing data off the tenancy, statement and maybe other models.

I could do all this inside a controller but I may also like the app to make statements automatically via a scheduled console command and perhaps I want a manual method to create a statement as well.

This is the time for a Job? Or use lots of events and listeners (payment created -> create statement, statement created -> create invoice, etc)? Or add a createStatement method on the Tenancy model? Or create a repository? Or create a dedicated service class?

I know there is technically no 'wrong' way so I'd just like to hear what route other people take

16th August, 2018

Jam0r left a reply on Catching Stripe Error Within A Job • 1 month ago

Found out why the invoice wouldn't get reverted back to unpaid in the failed method.

Stripe was giving an Error\Card exception and I was expecting a generic Exception.

    /**
     * The job failed to process.
     *
     * @param  Exception  $exception
     * @return void
     */
    public function failed(\Stripe\Error\Card $exception)
    {
        $this->invoice->forceFill([
            'status' => 'unpaid'
        ])->save();

        // Send user notification of failure, etc...
    }

This works fine now although I'd probably prefer the option to catch different errors later down the line.

Jam0r started a new conversation Catching Stripe Error Within A Job • 1 month ago

So I'm working on accepting payments for invoices and everything was working fine however as with everything I wanted to refactor and move the Stripe charging & customer creation into a job to stop the customer having to wait around for a response.

Using an accepted test card the process works fine.

I change the invoice status to 'payment-pending' before dispatching the Job.

I then call a recordPayment method on my Invoice eloquent model from within the job once the charge is made, which records the payment locally, attaches it to the invoice, updates the invoice balance and marks it as paid should no balance remain.

When using a failed test card the job process fails which is what I expect and it gives the correct reason through Horizon..

Stripe\Error\Card: Your card was declined.

But the failed method from within the job doesn't get called which is where I want to update the invoice status back to unpaid as the payment wasn't successful.

I'm using the billable trait on the user model.

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        /**
         * Create the stripe customer if not present.
         */
        if (! $this->user->hasStripeId()) {
            $this->user->createAsStripeCustomer($this->token);
        }

        $this->user->updateCard($this->token);
        
        $this->user->charge($this->invoice->total);

        $this->invoice->recordPayment($this->user, [
            'method' => 'Stripe'
        ]);
    }

    /**
     * The job failed to process.
     *
     * @param  Exception  $exception
     * @return void
     */
    public function failed(Exception $exception)
    {
        $this->invoice->forceFill([
            'status' => 'unpaid'
        ])->save();

        // Send user notification of failure, etc...
    }

11th August, 2018

Jam0r left a reply on Need To Learn How To Make Middleware Auth For Admin • 1 month ago

Have you seen the Nova announcement? Might be up your street.

https://nova.laravel.com/

9th July, 2018

Jam0r left a reply on Bootstrap Tabs "#/" Not Appearing And Can't Navigate Directly To Tab • 2 months ago

I had issues with this before, ended up making my own.

Have you had a look in the console, does it give any errors when loading? Can you share your Vue component .js file?

8th July, 2018

Jam0r started a new conversation Overwrite Axios Interceptors • 2 months ago

I want to overwrite the default axios interceptors setup by Spark.

I've tried entering them in my app.js file hoping they would overwrite them to no avail.

Whats the best way of doing this?

8th June, 2018

Jam0r started a new conversation Brew Not Installing Php, Missing Lib Zip • 3 months ago

Fresh install of 10.14 beta and setting my Mac up again.

Installing php through Homebrew and it stops at lib zip saying it could not download the dependency.

Quick check of the site and it's also down.

Is there anyway to install this manually from else where?

23rd April, 2018

Jam0r left a reply on Please Explain What I'm Doing Wrong. • 4 months ago

The other issue I have is that I have a note component (notes.blade.php) which includes a modal to delete the related note.

<notes :user="user" v-for="note in notes" v-bind:note="note" v-bind:key="note.id" inline-template></notes>

is the line i'm using and the template is inline. However when I click the button to activate the modal, it always gives the last notes.id instead of the ID of the component it relates to.

Jam0r started a new conversation Please Explain What I'm Doing Wrong. • 4 months ago

I'm trying to create a notes list which includes child components, etc. I need it to be fairly flexible as I want to use it on different views/models.

I have three note components - notes-list, notes and create-note

I include these into the model specific notes component but some data isn't being transferred.

client-notes.blade.php

<client-notes :user="user" :client="client" inline-template>
    <div>

        <div v-if="user && client">

            <!-- Include Notes List -->
            @include('shared.notes.notes-list')

        </div>

    </div>
</client-notes>

client-notes.js

Vue.component('client-notes', {
    props: ['user', 'client'],


    data() {
        return {
            parent: this.client
        }
    },
    

    computed: {
        notes: function () {
            return this.client.notes.data;
        }
    }
});

notes-list.blade.php

<notes-list :user="user" :notes="notes" :parent="parent" inline-template>
    <div>

        <div class="mb-3 text-right">

            <!-- Create Note -->
            @include('shared.notes.create-note')

        </div>

        <div class="card card-default">

            <!-- Notes List -->
            @include('shared.notes.notes')

        </div>

    </div>
</notes-list>

notes-list.js

Vue.component('notes-list', {
    props: ['user', 'notes', 'parent']
});

First issue is that I want to send the model as the 'parent' to the notes list so that I can reference this when storing new notes when using the create-note modal.

However the data value parent just returns null no matter what?

16th April, 2018

Jam0r left a reply on Using Vue Variable In Blade @include • 5 months ago

Damn so there's no way to do this?

I was hoping to have different template names eg. expense_created, expense_updated, etc and then to include the correct one using the template name from the activity as I have done before but this time using vue.

Nevermind, i'll have to sort something else out.

Thanks for the quick reply.

Jam0r started a new conversation Using Vue Variable In Blade @include • 5 months ago

I've done this before with Blade and PHP variables but it confuses my head using Vue instead.

<div v-for="activity in activities">
    @include('templates.template_name')
</div>

Essentially I want to use activity.template_name to include a sub blade file but how do I access the activity variable inside the @?

I've used the following with PHP before

@foreach($activities as $activity)
    @include('templates.' . $activity->name);
@endforeach

15th March, 2018

Jam0r started a new conversation Stripe - Record Invoice Paid? • 6 months ago

I'd like to use Stripe to manage the invoices and subscriptions of an app however I know that there will be clients who will pay by UK bank transfer, cheque or cash.

Since Stripe does not accept these payments, is there an option to manually mark an invoice as paid?

I've looked on the testing dashboard and cannot find anything.

23rd February, 2018

Jam0r left a reply on Using Event On Vue Component To Trigger Update On Another. • 6 months ago

Perfect thank you.

Jam0r started a new conversation Using Event On Vue Component To Trigger Update On Another. • 6 months ago

<template>
    <div class="container">
        <div class="mb-3">
            <messages-create-modal @created="triggerRefreshMessagesOnMessageList"></messages-create-modal>
        </div>

        <messages-list></messages-list>
    </div>
</template>

I have the above component which comprises of two child components.

When a new message is created via the modal it emits a 'created' event which I then want to use to trigger a method inside the messages-list component (ie. when a new message is created, re-get the messages)

I could do this easily if the parent component was housing all the methods, etc.. But can't work out in my brain how to do this with a child component (still fairly new to vue)

16th February, 2018

Jam0r started a new conversation Resources And Using Local API • 7 months ago

I'm trying to get my head around this.

I'm using a UserResource to turn my repository data into a json response and using the API routes file, this returns the following:-

UsersAPIController

{
"data": [
{
"type": "users",
"id": 1,
"attributes": {
"title": "Mr",
"first": "James",
"last": "Morris",
"email": null,
"phone": null
},
"name": "James Morris",
"nickname": "James",
"select_name": "James Morris",
"registered": {
"date": "2018-02-14 17:24:07.000000",
"timezone_type": 3,
"timezone": "GMT"
},
"updated": {
"date": "2018-02-15 16:45:18.000000",
"timezone_type": 3,
"timezone": "GMT"
},
"deleted": null,
"links": {
"self": "http://backend.test/users/1",
"edit": "http://backend.test/users/1/edit"
},
"data": {
"relationships": {
"home": ""
}
}
},
{
"type": "users",
"id": 2,
"attributes": {
"title": "Mr",
"first": "Bob",
"last": "Morris",
"email": "[email protected]",
"phone": null
},
"name": "Bob Morris",
"nickname": "Bob",
"select_name": "Bob Morris",
"registered": {
"date": "2018-02-14 17:34:34.000000",
"timezone_type": 3,
"timezone": "GMT"
},
"updated": {
"date": "2018-02-15 09:21:35.000000",
"timezone_type": 3,
"timezone": "GMT"
},
"deleted": null,
"links": {
"self": "http://backend.test/users/2",
"edit": "http://backend.test/users/2/edit"
},
"data": {
"relationships": {
"home": ""
}
}
}
],
"links": {
"first": "http://backend.test/api/users?page=1",
"last": "http://backend.test/api/users?page=1",
"prev": null,
"next": null,
"self": "http://backend.test/users"
},
"meta": {
"current_page": 1,
"from": 1,
"last_page": 1,
"path": "http://backend.test/api/users",
"per_page": 30,
"to": 2,
"total": 2
}
}

Which is great.

What I want to do is grab this data for my UsersController index and return it together with a blade view and i'm struggling on finding a way to do this.

18th January, 2018

Jam0r started a new conversation Storing Information In The Cache On App Load? • 8 months ago

Whats the best way to store information in the cache upon first load if the cache doesn't already exist?

For example, a user can belong to many branches.

In the navbar on my app I list the user's branches however this runs a database query on every page load.

The branches a user is linked to will hardly every change so it seems daft to run this query on every page load.

How would I go about storing the user's branches into the cache automatically when the user logs in?

5th December, 2017

Jam0r left a reply on Where Do You Store Related Model Processes? • 9 months ago

Especially when I may want to action the TenancyUpdateStatus event on related update and deletes etc

Jam0r started a new conversation Where Do You Store Related Model Processes? • 9 months ago

I'm trying to work out what the best practice is with eloquent models and related updates, etc.

I have three models - Tenancy, Payment, Statement.

A tenancy can have many payments and statements and I have the following methods in my Tenancy eloquent model.

    public function storeRentPayment(Payment $payment)
    {
        $payment = $this->rent_payments()->save($payment);
        $payment->users()->attach($this->tenants);

        event(new TenancyUpdateStatus($this));

        return $payment;
    }

    public function storeStatement(Statement $statement)
    {
        $statement = $this->statements()->save($statement);
        $statement->users()->sync($this->property->owners);

        event(new TenancyUpdateStatus($this));

        return $statement;
    }

However it doesn't feel the correct way to go about things.

As you can see I store the given model to the tenancy and then carry out other actions such as adding users, actioning events, etc.

19th November, 2017

Jam0r started a new conversation Nexmo Delivery Receipts? • 10 months ago

Has anyone got this working?

The SMS sends through the notification fine and is stored inside my database.

I've setup the web hook and the SMS controller to accept the response.

If I enter the GET details manually it works fine but Nexmo doesn't seem to be sending the receipt.

Do I have to set this manually via the config/options?

Jam0r left a reply on Nexmo SMS Response Via Notifications? • 10 months ago

Nevermind, it's working.

I removed database from the via method and I get the nexmo message instance.

Jam0r started a new conversation Nexmo SMS Response Via Notifications? • 10 months ago

I need to get the sms message id from the nexmo response but I get null when I do the following

        $response = $user->notify(new UserSmsMessage($request->message));
    return dd($response);

When according to their docs I should get something along the lines of

  "message-count":"1",
  "messages":[
    {
    "status":"returnCode",
    "message-id":"messageId",
    "to":"to",
    "client-ref":"client-ref",
    "remaining-balance":"remaining-balance",
    "message-price":"message-price",
    "network":"network",
    "error-text":"error-message"
    }
  ]
}

any ideas?

7th November, 2017

Jam0r started a new conversation Accessing User Within A Notification • 10 months ago

I'm sure I read somewhere that you could access the user model within a notification?

$user->notify(new RandomNotification($model));

and then within the Notification you could use $this->user

Did I dream this and for some reason I cannot get it to work and doing dd($this) within the Notification shows no sign of the $user

31st October, 2017

Jam0r left a reply on Storing A Date Modifier In A Table? • 10 months ago

Good catch.

I guess creating a custom date helper to check for this and prevent this could be a solution?

Jam0r left a reply on Storing A Date Modifier In A Table? • 10 months ago

Bit messy but this is what I came up with.

Recurring invoices migration

        Schema::create('invoice_recurring', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->integer('invoice_id')->unsigned();
            $table->string('interval_type');
            $table->integer('interval');
            $table->date('next_invoice');
            $table->date('ends_at')->nullable();
            $table->text('data')->nullable();
            $table->timestamps();

            $table->foreign('invoice_id')->references('id')->on('invoices')->onDelete('cascade');
        });

GenerateRecurringInvoices job

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $recurring_invoices = InvoiceRecurring::invoiceDue()->get();

        foreach ($recurring_invoices as $recur) {

            $invoice = Invoice::findOrFail($recur->invoice_id);

            $new_invoice = new Invoice();
            $new_invoice->user_id = $invoice->user_id;
            $new_invoice->property_id = $invoice->property_id;
            $new_invoice->invoice_group_id = $invoice->invoice_group_id;
            $new_invoice->recipient = $invoice->recipient;
            $new_invoice->terms = $invoice->terms;
            $new_invoice->save();

            $new_invoice->users()->sync($invoice->users);

            $interval = 'add' . $recur->interval_type;

            $recur->next_invoice = $recur->next_invoice->$interval($recur->interval);
            $recur->save();
        }
    }

The above job is executed daily at midnight.

Jam0r left a reply on Storing A Date Modifier In A Table? • 10 months ago

Thank you for that.

I'm not sure the days option would work as I think there may be cases when I want an invoice to recur on the 1st of April and the 1st of October every year for example.

This is where I'm getting a bit stuck.

I could perhaps have two columns, one being the interval type (eg. day, month, year, etc) and then an integer column for the interval to work with the type.

Is that the cleanest way of doing this?

Jam0r started a new conversation Storing A Date Modifier In A Table? • 10 months ago

I've got a basic invoicing app but I want to be able to setup recurring invoices.

My plan is to use a separate table to store when I want the first recurring invoice to start and how often I want it to recur.

I'm using Laravel with Carbon to handle the dates.

I have a date column called 'starts_at' but I'm having trouble deciding on how to store the date modifier as I want it to be fairly flexible.

eg. if the user wants a new invoice every day or every month, I want the system to work instead of hard coding stuff.

Any suggestions?

24th October, 2017

Jam0r started a new conversation Validation, Redirect On Not Authorised. • 10 months ago

I am checking for duplicate records within a custom validation Request and when found, it returns an not authorized error. Fine

However I want to simply return to the previous page and show an error 'that property already exists' for example.

Any ideas?

<?php

namespace App\Http\Requests;

use App\Gas;
use Illuminate\Foundation\Http\FormRequest;

class GasInspectionStoreRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        if (Gas::where('property_id', request()->input('property_id'))->exists()) {
            return false;
        }

        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'expires_on' => 'required',
            'property_id' => 'required|numeric',
            'contractors' => 'required'
        ];
    }
}

12th October, 2017

Jam0r left a reply on Uploading Storage Files Through GIT • 11 months ago

Perfect thank you.

Worked first time with the public/images folder and using asset() helper.

Jam0r started a new conversation Uploading Storage Files Through GIT • 11 months ago

I'm making a mostly static website and I want to upload a few logos with it to be used on certain pages.

I've done the usual

php artisan storage:link

and tried placing the logos in both the public/storage and storage/app folders but they never get uploaded to my git repo. I've also tried removing the folders from gitignore but no luck.

What am I doing wrong?

2nd October, 2017

Jam0r left a reply on Best Implementation Of A 'setup' Page For A New App? • 11 months ago

So what i'v done for the time being is setup two new routes. Then I just head to that URL eg. domain.com/setup and it shows the page for creating the first user, setting some basic settings like company name, etc.

In the SetupController I call a check on whether there are user accounts. If so, then i just redirect back to the dashboard otherwise I show the setup pages.

Jam0r started a new conversation Best Implementation Of A 'setup' Page For A New App? • 11 months ago

Once a user has installed my app, i'd like there to be a setup page (similar to vBulletin or PHPBB) where the user can create their account along with setting some basic settings and store them in the table.

Any suggestions as to how I go about doing this?

20th September, 2017

Jam0r left a reply on Latest Update Has Broken My Routes? • 1 year ago

So updated my composer.json to 5.5.5 and it works fine now so seems to be an issue after that?

Jam0r started a new conversation Latest Update Has Broken My Routes? • 1 year ago

So just ran composer update and for some reason, my routing which was working perfectly before is now not playing ball.

There seems to be an issue with using optional parameters and when each route is executed?

For example:-

Route::get('overdue', '[email protected]')->name('tenancies.overdue');
Route::get('{id}/{section?}', '[email protected]')->name('tenancies.show');

This is how these two lines appear in my web routes file and this was working fine before the update. The overdue route would be called before show and both routes worked fine.

However now each time I try access overdue it now bypasses the overdue route and goes straight to show and pops up an error.

Any suggestions?

10th September, 2017

Jam0r left a reply on Same Methods In Multiple Models • 1 year ago

You could use a Trait quite easily for this as well.

In fact I'd actually use a trait in this instance

31st August, 2017

Jam0r started a new conversation Extra Validation And How To Prevent Duplicates? • 1 year ago

I'm using Requests to check for validation rules when filling in forms which works great but there are some cases where I may want to carry out further checks and ideally show warnings rather than out right errors.

For an example, I have two models.

App\Statement App\Expense

A statement can contain a number of expenses with an additional pivot field called 'amount'

When creating a new statement and adding an expense to it, I want to check whether there are similar expenses in previous statements ideally to prevent an expense being entered or paid twice.

1st August, 2017

Jam0r started a new conversation Removing Word Break From Markdown Mailables? • 1 year ago

I've tried and tried but I cannot seem to stop laravel from breaking words in a markdown e-mail.

I've updated the default.css style and removed word-break elements but it still does it.

Any suggestions?

21st July, 2017

Jam0r started a new conversation Complex Query, Comparing Sum Of Different Tables • 1 year ago

I have a base model with has a relation to two other models.

I'm calculating a balance and appending to the base model based on amounts recorded in the relationship models.

Both relationship models have fields named 'amount' which I total, and then subtract from each other, giving me a balance on the fly.

This works well as if and when a record in a relationship table is deleted, the balance gets updated on the fly without any extra calculations and query saves.

However I'd like to show a list of all base model records with a positive balance.

I can do this by getting the complete collection through eloquent and then filtering through the collection but this seems a waste of resources.

Is there another way?

I've tried getting my head around using a whereHas and a raw query but i'm confusing myself something rotten.

20th July, 2017

Jam0r left a reply on Storing Sent Emails In The Database • 1 year ago

For example, when sending an email:-

Mail::to($request->user())->send(new OrderShipped($order));

Is there any way to get the user from the 'to' later on? I know I could add $user to the OrderShipped example but was wondering if there was an easier, more fluid/automatic way.

This would be so I could attach the email and user via a pivot table in case they ever changed their email address.

18th July, 2017

Jam0r left a reply on Accessing The Mailable Properties From The MessageSending Event That Is Triggered When Sending Mail Through The Mail Facade • 1 year ago

Can you elaborate on your MyMailer class?

I'm trying to do something similar but i'm ending up with two build methods (in my UserWelcome mailer which extends my BaseMailer) which won't work.

Jam0r left a reply on Storing Sent Emails In The Database • 1 year ago

Hadn't thought about recording attachments but now that you mention it, that would be useful as well.

I was doing this just to record basic emails but we often send emails to users with statements and invoices attached so would be good to see the email exactly how it's sent.

Also, although I am recording the 'to' part of the email, I would like to link the email to the user(s) by the way of a pivot table but i'm wondering how to get the $user automatically?

Jam0r started a new conversation Storing Sent Emails In The Database • 1 year ago

So I want a way of storing sent emails inside of the database for future reference. I've hooked into the MessageSending event and am using the following handle in my listener.

    public function handle(MessageSending $event)
    {
        $message = $event->message;

        return dd($message);

        Email::create([
            'to' => !$message->getHeaders()->get('To') ? null : $message->getHeaders()->get('To')->getFieldBody(),
            'bcc' => !$message->getHeaders()->get('Bcc') ? null : $message->getHeaders()->get('Bcc')->getFieldBody(),
            'subject' => $message->getHeaders()->get('Subject')->toString(),
            'body' => $this->getMimeEntityString($message),
        ]);
    }

    protected function getMimeEntityString(\Swift_Mime_MimeEntity $entity)
    {
        $string = (string) $entity->getHeaders().PHP_EOL.$entity->getBody();

        foreach ($entity->getChildren() as $children) {
            $string .= PHP_EOL.PHP_EOL.$this->getMimeEntityString($children);
        }
        
        return $string;
    }

Is this the best (easiest and quickest) way of doing this?

15th June, 2017

Jam0r left a reply on Notifications From Controller • 1 year ago

I presume your running > 5.3 so

php artisan make:notification InvoicePaid --markdown=mail.invoice.paid

That will place the blade template for the email in views -> mail

Jam0r left a reply on Notifications From Controller • 1 year ago

Could you not just use a mailable notification?

Jam0r started a new conversation Storing Bank Accounts In The DB • 1 year ago

I'm working on a project which requires being able to store bank accounts (bank name, account name, account number and sort code) against users inside mysql.

Form my understanding although this is sensitive data, it poses no security risk compared to the likes of storing credit/debit cards.

Can someone confirm whether this is the case, what the best practices are and whether there are any outsider companies (Stripe for example) who would be able to handle this should they need to?

14th June, 2017

Jam0r left a reply on Please Explain Why Encrypt() Changes Each Time? • 1 year ago

Excellent, that clears that up! Thank you for that.

Taking this further, if I wanted to dose basic encryption on lets say, a phone number inside my database, what would be the quickest way of doing this?

Furthermore, I'm recording activity on the user model to track changes made so in a perfect world, if the phone number doesn't change, I'd want the resulting hash to be unchanged.

I'm using $user->dirty() to find the updated fields.

Jam0r started a new conversation Please Explain Why Encrypt() Changes Each Time? • 1 year ago

Can someone explain why when using encrypt() the output changes each time even though the value being encrypted doesn't change?

Is it possible to stop this from happening?

Jam0r started a new conversation Saving Relation To Scout When Creating New Instance • 1 year ago

I have the following code

        // We find the parent property
        $property = $this->properties->findOrFail($request->property);

        // Store the expense against the property
        $expense = $property->expenses()->create($request->input());

        // Attach any users to the expense
        if ($request->has('users')) {
            $expense->users()->sync($request->users);
        }

However with scout and algolia, I also want to have the user names stored against the item.

Clearly I save the expense (and thus send it to algolia) before the users are attached so that so whats the best way to 'update' scout once the users have been added?

31st May, 2017

Jam0r left a reply on Modify The Header And Footer In Mail Markdown Mails • 1 year ago

Update on this.

Once I have published the vendor email files, even when I change the header in message, it does not take effect when the email is sent?

Edit Your Profile
Update

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