jesse_orange_newable

jesse_orange_newable

Member Since 1 Year Ago

Experience Points
7,650
Total
Experience

2,350 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
51
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

Level 2
7,650 XP
Sep
25
21 hours ago
Activity icon

Started a new Conversation Laravel Pagination In Vue.js

I am using Laravel's paginate method with Vue.js for a load more button, the pagination in my Vue component is an object like so:


(this.pagination = {
  from: response.data.from,
  to: response.data.to,
  total: response.data.total,
  current_page: response.data.current_page,
  last_page: response.data.last_page,
  next_page_url: response.data.next_page_url,
  prev_page_url: response.data.prev_page_url,
}),

As you can see I'm just grabbing what the paginate method responds with.

Here is the base paginate method


    /**
     * Paginate the given query into a simple paginator.
     *
     * @param  int  $perPage
     * @param  string  $pageName
     * @param  int|null  $page
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function paginate($perPage = null, $pageName = 'page', $page = null)
    {
        $engine = $this->engine();

        $page = $page ?: Paginator::resolveCurrentPage($pageName);

        $perPage = $perPage ?: $this->model->getPerPage();

        $results = $this->model->newCollection($engine->map(
            $this, $rawResults = $engine->paginate($this, $perPage, $page), $this->model
        )->all());

        $paginator = (new LengthAwarePaginator($results, $engine->getTotalCount($rawResults), $perPage, $page, [
            'path' => Paginator::resolveCurrentPath(),
            'pageName' => $pageName,
        ]));

        return $paginator->appends('query', $this->query);
    }

In Vue how can I append or amend parameters?

I see it has a query parameter already, is it possible to add more?

Sep
24
1 day ago
Activity icon

Started a new Conversation Using Laravel Scout Or An SQL LIKE Operator

In one of my projects we have Articles and Events (singular) and I wanted the ability to search through them with a search bar.

Laravel Scout was great for this as I could literally do the following:


/**
    * Perform a search using what was typed into the search bar
    * Uses Laravel Scout for full text indexing.
    *
    * @param  Request $request
    * @return void
    */
public function search(Request $request)
{
    // Do some validation
    $validated_data = $request->validate([
        'q' => 'nullable|string|max:255',
    ]);

    // Get what was searched for
    $query_string = $validated_data['q'];

    $articles = Article::search($query_string)
        ->where('status', 'published')
        ->orderBy('created_at', 'desc')
        ->get();

    $events = Event::search($query_string)
        ->where('published', 'published')
        ->orderBy('start_datetime', 'desc')
        ->get();
    }

This worked fine.

One day users want tagging so I use https://cartalyst.com/manual/tags/11.x to handle the many-to-many aspects of this request.

So, users now want to be able to search and if it returns nothing, it should instead compare the search term to any available tag.

I've been reading up and I don't think scout would be a good choice at this point because essentially I want to use a bunch or orWhere to do the following:

  1. Search through each column of the model and try to match the string
  2. If we don't find anything, search through the tags

$articles = Article::search($query_string)
    ->where('status', 'published')
    ->orderBy('created_at', 'desc')
    ->get();

if(!$articles){
    $articles = Article::whereHas('tags', function($query){
        $query->where('name', 'like', '%' . $query_string . '%');
    })
}

Is there a better, more efficient way to do this?

Sep
04
3 weeks ago
Activity icon

Replied to What's The Best Way To Limit A Many To Many Relation?

I'm always over complicating these things....

Activity icon

Started a new Conversation What's The Best Way To Limit A Many To Many Relation?

In a project I'm working on I have a many to many relation between a Post and a Tag so going by Laravel convention there is a pivot called post_tag to hook everything up.

What would be the best way to limit the number of tags that could be set on the Post model?

My ideas are as follows:

  1. A pivot model observer to hook into the created event and check the count
  2. A validation rule that checks the size of the array to be synced

I think 2. is more likely as I could validate the size of the array but in practice would there be any performance hit on making a rule similar to exists that gets the model count?

As then I could compare the array size to the number of rows.

What do you guys and girls think?

Sep
02
3 weeks ago
Activity icon

Replied to Correct Way To Pass Multiple Parameters Of Same Type

This is an Asynchronous request using Axios within a Vue.js component.

Activity icon

Started a new Conversation Listener In Event Doesn't Know Related Objects

I have the following in my EventServiceProvider.php file.


ApplicationSubmitted::class => [
    LogApplicationSubmitted::class,
    GenerateInvestmentApplicationPDF::class,
    SendUserApplicationSubmittedNotification::class,
    SendAdminApplicationSubmittedNotification::class,
    SendShareCentreApplicationSubmitted::class,
],

As you can see the event happens and then the listeners kick in.

I have a test to verify this:


/** @test */
public function submitting_a_fund_application_creates_an_activity_for_this_user()
{
    Notification::fake();

    $user = factory(User::class)->states('verified', 'certified', 'passive')->create();

    $user->investorDetails->update(factory(InvestorDetail::class)->raw([
        'user_id' => $user->id,
    ]));

    $this->assertTrue($user->investorDetails->is_completed);

    $application = [
        'type' => InvestmentApplication::TYPE_FUND,
        'deal_id' => null,
        'amount_pledged' => 10000,
        'payment_method' => InvestmentApplication::PAYMENT_BANK_TRANSFER,
        'fund_agreement' => 1,
        'electronic_signature' => 1,
    ];

    $this->actingAs($user)
        ->post(route('user.application.fund.store'), $application)
        ->assertStatus(302);

    $this->assertDatabaseHas('investment_applications', [
        'user_id' => $user->id,
        'type' => $application['type'],
        'deal_id' => null,
        'amount_pledged' => $application['amount_pledged'],
        'payment_method' => $application['payment_method'],
    ]);

    $this->assertDatabaseHas('user_activities', [
        'user_id' => $user->id,
    ]);
}

Inside LogApplicationSubmitted it is able to retrieve application->user just fine but then, in GenerateInvestmentApplicationPDF the same returns null.

<?php

namespace App\Listeners;

use App\Events\ApplicationSubmitted;
use App\Events\UserActivityOccurred;
use Log;

class LogApplicationSubmitted
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
    }

    /**
     * Handle the event.
     *
     * @param  ApplicationSubmitted $event
     * @return void
     */
    public function handle(ApplicationSubmitted $event)
    {
        $application = $event->investmentApplication;

        Log::info("An investment application of type {$application->type} was submitted with a pledged value of {$application->amount_pledged} by {$application->user->full_name}");

        event(new UserActivityOccurred(
            $application->user,
            'investment application',
            'submitted an investment application for  ' . $application->amount_pledged . ' via ' . $application->payment_method,
            $application->deal
        ));
    }
}



Then in the next listener


<?php

namespace App\Listeners;

use App\Events\ApplicationSubmitted;
use Illuminate\Contracts\Queue\ShouldQueue;
use Carbon\Carbon;
use PDF;
use Storage;

class GenerateInvestmentApplicationPDF implements ShouldQueue
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
    }

    /**
     * Handle the event.
     *
     * @param  ApplicationSubmitted $event
     * @return void
     */
    public function handle(ApplicationSubmitted $event)
    {
        $application = $event->investmentApplication;

        dd($application->user); // returns null

        $directory = "applications/{$application->user_id}";

        $filename = "{$application->name} Application - " . Carbon::now()->format('d-m-y-H-i-s') . '.pdf';

        $path = $directory . '/' . $filename;

        // Generate a PDF from the given view
        $pdf = PDF::loadView('pdf.user.investment-application', compact('application', 'user'))
            ->setPaper('a4', 'landscape');

        // Save this PDF to storage
        Storage::disk('local')->put($path, $pdf->output());

        // Update the investment application with the path to the newly created file
        $event->investmentApplication->update([
            'pdf_path' => $path,
        ]);
    }
}


Activity icon

Replied to Correct Way To Pass Multiple Parameters Of Same Type

I didn't realise there was a limit to be honest, although that's good to know. I'give the video and watch and update my question.

Aug
28
4 weeks ago
Activity icon

Started a new Conversation Correct Way To Pass Multiple Parameters Of Same Type

I have a page where users can filter by multiple tags in order to amend a search using Laravel scout.


    $search_term = $request->get('q');
    $tags = $request->get('tags');

    // Organise tags from request into usable array
    $tags = collect($tags)->map(function ($item, $key) {
        return [
            json_decode($item)->slug,
        ];
    })->flatten()->toArray();

    // Build error message if no results are found
    $error = ['error' => "No results found for '{$request->get('q')}'"];
    
    $error['error'] = count($tags) > 0
        ? $error['error'] . ' with ' . count($tags) . ' tag(s) selected.'
        : $error['error'];

    // If there is a search term, search for events meeting search criteria
    if (!empty($search_term)) {
        $events = Event::search($search_term)->query(function ($query) use ($tags) {
            return $query->listed()
                ->when(count($tags) > 0, function ($query) use ($tags) {
                    return $query->withTag($tags);
                })
                ->select('id', 'title', 'header_image_url', 'location', 'start_datetime', 'finish_datetime');
        })->paginate(6);
    }
    // If there is NO search term, load all listed events meeting tag criteria
    else {
        $events = Event::listed()
            ->withTag($tags)
            ->select('id', 'title', 'header_image_url', 'location', 'start_datetime', 'finish_datetime')
            ->orderBy('start_datetime')
            ->paginate(6);
    }

    return $events->count() ? $events : $error;
}


Where tags is an array of selections like blue, red, green, however the URLs become really odd:


Request URL: http://127.0.0.1:8000/api/events/search?q=&tags[]=%7B%22id%22:3,%22name%22:%22Find+International+Partners%22,%22slug%22:%22find-international-partners%22,%22checked%22:true%7D&tags[]=%7B%22id%22:5,%22name%22:%22Grow+in+the+US%22,%22slug%22:%22grow-in-the-us%22,%22checked%22:true%7D&tags[]=%7B%22id%22:14,%22name%22:%22Innovate+UK%22,%22slug%22:%22innovate-uk%22,%22checked%22:true%7D&tags[]=%7B%22id%22:7,%22name%22:%22Investment+Pitch%22,%22slug%22:%22investment-pitch%22,%22checked%22:true%7D&tags[]=%7B%22id%22:15,%22name%22:%22JP+Morgan%22,%22slug%22:%22jp-morgan%22,%22checked%22:true%7D&tags[]=%7B%22id%22:18,%22name%22:%22Newable%22,%22slug%22:%22newable%22,%22checked%22:true%7D

and then when I try to paginate, trying to append that is horrible.

Should it just be like so?

tags=tag1&&tag2&&tag3 rather than entire objects?

Aug
06
1 month ago
Activity icon

Replied to Working With Date And Time

My bad, I forgot a part:


/**
 * Set the start date & time
 *
 * @param [type] $value
 *
 * @return void
 */
public function setStartDatetimeAttribute($value)
{
    $date = $value['date'] ?? null;
    $time = $value['time'] ?? '';

    if (!is_null($date)) {
        return $this->attributes['start_datetime'] = Carbon::parse($date . $time);
    }

    return $this->attributes['start_datetime'] = Carbon::now();
}

Activity icon

Started a new Conversation Working With Date And Time

I have a query scope called inDate that is meant to check the given start_datetime and check whether its newer than today i.e Carbon::today(), however I can't wrap my head around this.

I have a test:

/** @test */
public function it_knows_if_its_in_date_query_scope()
{
    $start = Carbon::now();
    $end = Carbon::now()->addDay();

    $eventInDate = factory(Event::class)->create([
        'date_not_available' => false,
        'start_datetime' => [
            'date' => $start->format('Y-m-d'),
            'time' => $start->format('H:i'),
        ],
        'finish_datetime' => [
            'date' => $end->format('Y-m-d'),
            'time' => $end->format('H:i'),
        ],
    ]);

    $eventsDueToHappen = Event::inDate()->get();

    $this->assertFalse($eventsDueToHappen->contains($eventInDate));
}


Now, the start_datetime of dueToHappen is the current time, which for me is 2020-08-06 16:59:00

The query scope looks like this:


public function scopeInDate($query)
{
    return $query->where('start_datetime', '>=', Carbon::today()->startOfDay()->toDateTimeString());
}

Dumping this outputs the following SQL:


"select * from `events` where `start_datetime` >= ? and `events`.`deleted_at` is null"
array:1 [
  0 => "2020-08-06 00:00:00"
]

How can this test be failing as 16:00 is older than 00:00

Jul
01
2 months ago
Activity icon

Replied to Fixing Ugly Code

Hi,

Essentially, users fill in a web form and then this populates a template within DocuSign. Each model has a few envelope specific fields that I've added below.


$table->string('envelope_id')->nullable();
$table->string('envelope_status')->nullable();
$table->timestamp('envelope_sent_at')->nullable();
$table->timestamp('envelope_signed_at')->nullable();
$table->timestamp('envelope_voided_at')->nullable();
$table->string('envelope_completed_document_path')->nullable();

I feel these are fairly straightforward, literally just fields to hold information on the envelope that was sent.


// Retrieve the unsigned envelopes from the company registrations
        $actionPlanEnvelopes = CompanyActionPlan::select('envelope_id')
            ->unsignedEnvelope()
            ->unvoidedEnvelope()
            ->pluck('envelope_id')
            ->toArray();

This just says only bother checking models that have an envelope that hasn't already been voided or signed.


    /**
     * Check the action plan forms against the returned changes from DocuSign
     *
     * @param string $envelope
     * @param mixed  $client
     *
     */
    private function checkActionPlans($envelope, $client)
    {
        $actionPlan = CompanyActionPlan::where('envelope_id', $envelope['envelope_id'])->first();

        if ($actionPlan) {
            // If the document has been voided within DocuSign update our local record
            if ($envelope['status'] == 'voided') {
                Log::info("Action plan for company {$actionPlan->company_name} was voided.");
                $voidedAt = Carbon::parse($envelope['voided_date_time']);
                $actionPlan->markAsVoided($voidedAt);
                $actionPlan->user->notify(new ActionPlanStatusUpdated($actionPlan));
            }

            // If the document has been declined
            if ($envelope['status'] == 'declined') {
                Log::info("Action plan for company {$actionPlan->company_name} was declined.");
                $actionPlan->markAsDeclined();
                $actionPlan->user->notify(new ActionPlanStatusUpdated($actionPlan));
            }

            // If the document has been delivered
            if ($envelope['status'] == 'delivered') {
                Log::info("Action plan for company {$actionPlan->company_name} was delivered to the signer.");
                $actionPlan->markAsDelivered();
            }

            // If the envelope is complete, timestamp it, notify the creator and grab the signed document
            if ($envelope['status'] == 'completed') {
                Log::info("Action plan for company {$actionPlan->company_name} was completed.");
                $completedAt = Carbon::parse($envelope['status_changed_date_time']);

                $filePath = "/action-plans/{$actionPlan->id}/signed.pdf";

                $signedDocument = $client->envelopes->getDocument(1, $actionPlan->envelope_id);

                $documentContents = file_get_contents($signedDocument->getPathname());

                Storage::disk('local')->put($filePath, $documentContents);

                $actionPlan->markAsCompleted($completedAt, $filePath);

                $actionPlan->user->notify(new ActionPlanStatusUpdated($actionPlan));
            }
        }
    }


In this section I get the envelope status and then update some fields and send a notification. On creation I also download the signed envelope.

The main issue I had was that the actual form fields were different so I just made different models. In truth they are all fairly similar.

Activity icon

Started a new Conversation Fixing Ugly Code

Hi everyone,

I have been working with the DocuSign e Signature API to send out documents to clients, then to check for changes I have been using polling.

I have a job to accomplish this:


<?php

namespace App\Jobs;

use App\CompanyActionPlan;
use App\CompanyOutcome;
use App\GrowthHubOutcome;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\CompanyRegistration;
use App\Notifications\ActionPlanStatusUpdated;
use App\Notifications\OutcomesFormStatusUpdated;
use App\Notifications\RegistrationFormStatusUpdated;
use DocuSign;
use Carbon\Carbon;
use Storage;
use Log;

class PollDocuSignEnvelopes implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * The number of times the job may be attempted.
     *
     * @var int
     */
    public $tries = 3;

    /**
     * Create a new job instance.
     */
    public function __construct()
    {
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        // Create a new DocuSign client
        $client = DocuSign::create();

        // Create an empty array
        $envelopeIds = [];

        // Retrieve the unsigned envelopes from the company registrations
        $actionPlanEnvelopes = CompanyActionPlan::select('envelope_id')
            ->unsignedEnvelope()
            ->unvoidedEnvelope()
            ->pluck('envelope_id')
            ->toArray();

        // Retrieve the unsigned envelopes from the action plans
        $registrationEnvelopes = CompanyRegistration::select('envelope_id')
            ->unsignedEnvelope()
            ->unvoidedEnvelope()
            ->pluck('envelope_id')
            ->toArray();

        // Retrieve the unsigned envelopes from the outcomes
        $outcomeEnvelopes = CompanyOutcome::select('envelope_id')
            ->unsignedEnvelope()
            ->unvoidedEnvelope()
            ->pluck('envelope_id')
            ->toArray();

        // Retrieve the unsigned envelopes from the lgh outcomes
        $growthHubOutcomeEnvelopes = GrowthHubOutcome::select('envelope_id')
            ->unsignedEnvelope()
            ->unvoidedEnvelope()
            ->pluck('envelope_id')
            ->toArray();

        // Merge the collection and send all envelope IDs to DocuSign for checking
        $envelopeIds = array_merge($actionPlanEnvelopes, $registrationEnvelopes, $outcomeEnvelopes, $growthHubOutcomeEnvelopes);

        // Only do anything if there are envelopes
        if ($envelopeIds) {
            $options = $client->envelopes->listStatusChangesOptions([
                'count' => 25,
                'envelope_ids' => $envelopeIds,
            ]);

            $changes = $client->envelopes->listStatusChanges($options);

            foreach ($changes['envelopes'] as $envelope) {
                $this->checkActionPlans($envelope, $client);
                $this->checkRegistrations($envelope, $client);
                $this->checkOutcomes($envelope, $client);
                $this->checkGrowthHubOutcomes($envelope, $client);
            }
        }
    }

    /**
     * Check the action plan forms against the returned changes from DocuSign
     *
     * @param string $envelope
     * @param mixed  $client
     *
     */
    private function checkActionPlans($envelope, $client)
    {
        $actionPlan = CompanyActionPlan::where('envelope_id', $envelope['envelope_id'])->first();

        if ($actionPlan) {
            // If the document has been voided within DocuSign update our local record
            if ($envelope['status'] == 'voided') {
                Log::info("Action plan for company {$actionPlan->company_name} was voided.");
                $voidedAt = Carbon::parse($envelope['voided_date_time']);
                $actionPlan->markAsVoided($voidedAt);
                $actionPlan->user->notify(new ActionPlanStatusUpdated($actionPlan));
            }

            // If the document has been declined
            if ($envelope['status'] == 'declined') {
                Log::info("Action plan for company {$actionPlan->company_name} was declined.");
                $actionPlan->markAsDeclined();
                $actionPlan->user->notify(new ActionPlanStatusUpdated($actionPlan));
            }

            // If the document has been delivered
            if ($envelope['status'] == 'delivered') {
                Log::info("Action plan for company {$actionPlan->company_name} was delivered to the signer.");
                $actionPlan->markAsDelivered();
            }

            // If the envelope is complete, timestamp it, notify the creator and grab the signed document
            if ($envelope['status'] == 'completed') {
                Log::info("Action plan for company {$actionPlan->company_name} was completed.");
                $completedAt = Carbon::parse($envelope['status_changed_date_time']);

                $filePath = "/action-plans/{$actionPlan->id}/signed.pdf";

                $signedDocument = $client->envelopes->getDocument(1, $actionPlan->envelope_id);

                $documentContents = file_get_contents($signedDocument->getPathname());

                Storage::disk('local')->put($filePath, $documentContents);

                $actionPlan->markAsCompleted($completedAt, $filePath);

                $actionPlan->user->notify(new ActionPlanStatusUpdated($actionPlan));
            }
        }
    }

    /**
     * Check the registration forms against the returned changes from DocuSign
     *
     * @param string $envelope
     * @param mixed  $client
     *
     */
    private function checkRegistrations($envelope, $client)
    {
        $registration = CompanyRegistration::where('envelope_id', $envelope['envelope_id'])->first();

        if ($registration) {
            if ($envelope['status'] == 'voided') {
                Log::info("Registration for company {$registration->company_name} was voided.");
                $voidedAt = Carbon::parse($envelope['voided_date_time']);
                $registration->markAsVoided($voidedAt);
                $registration->user->notify(new RegistrationFormStatusUpdated($registration));
            }

            // If the document has been declined
            if ($envelope['status'] == 'declined') {
                Log::info("Registration for company {$registration->company_name} was declined.");
                $registration->markAsDeclined();
                $registration->user->notify(new RegistrationFormStatusUpdated($registration));
            }

            // If the document has been delivered
            if ($envelope['status'] == 'delivered') {
                Log::info("Registration for company {$registration->company_name} was delivered to the signer.");
                $registration->markAsDelivered();
            }

            // If the envelope is complete, timestamp it, notify the creator and grab the signed document
            if ($envelope['status'] == 'completed') {
                Log::info("Registration for company {$registration->company_name} was completed.");
                $completedAt = Carbon::parse($envelope['status_changed_date_time']);

                $filePath = "/registrations/{$registration->id}/signed.pdf";

                $signedDocument = $client->envelopes->getDocument(1, $registration->envelope_id);

                $documentContents = file_get_contents($signedDocument->getPathname());

                Storage::disk('local')->put($filePath, $documentContents);

                $registration->markAsCompleted($completedAt, $filePath);

                $registration->user->notify(new RegistrationFormStatusUpdated($registration));
            }
        }
    }

    /**
     * Check the registration forms against the returned changes from DocuSign
     *
     * @param string $envelope
     * @param mixed  $client
     *
     */
    private function checkOutcomes($envelope, $client)
    {
        $outcome = CompanyOutcome::where('envelope_id', $envelope['envelope_id'])->first();

        if ($outcome) {
            if ($envelope['status'] == 'voided') {
                Log::info("Outcome for company {$outcome->company_name} was voided.");
                $voidedAt = Carbon::parse($envelope['voided_date_time']);
                $outcome->markAsVoided($voidedAt);
                $outcome->user->notify(new OutcomesFormStatusUpdated($outcome));
            }

            // If the document has been declined
            if ($envelope['status'] == 'declined') {
                Log::info("Outcome for company {$outcome->company_name} was declined.");
                $outcome->markAsDeclined();
                $outcome->user->notify(new OutcomesFormStatusUpdated($outcome));
            }

            // If the document has been delivered
            if ($envelope['status'] == 'delivered') {
                Log::info("Outcome for company {$outcome->company_name} was delivered to the signer.");
                $outcome->markAsDelivered();
            }

            // If the envelope is complete, timestamp it, notify the creator and grab the signed document
            if ($envelope['status'] == 'completed') {
                Log::info("Outcome for company {$outcome->company_name} was completed.");
                $completedAt = Carbon::parse($envelope['status_changed_date_time']);

                $filePath = "/outcomes/{$outcome->id}/signed.pdf";

                $signedDocument = $client->envelopes->getDocument(1, $outcome->envelope_id);

                $documentContents = file_get_contents($signedDocument->getPathname());

                Storage::disk('local')->put($filePath, $documentContents);

                $outcome->markAsCompleted($completedAt, $filePath);

                $outcome->user->notify(new OutcomesFormStatusUpdated($outcome));
            }
        }
    }

    /**
     * Check the lgh outcomes forms against the returned changes from DocuSign
     *
     * @param string $envelope
     * @param mixed  $client
     *
     */
    private function checkGrowthHubOutcomes($envelope, $client)
    {
        $outcome = GrowthHubOutcome::where('envelope_id', $envelope['envelope_id'])->first();

        if ($outcome) {
            dd($envelope);
            if ($envelope['status'] == 'voided') {
                Log::info("Growth Hub Outcome for company {$outcome->company_name} was voided.");
                $voidedAt = Carbon::parse($envelope['voided_date_time']);
                $outcome->markAsVoided($voidedAt);
            }

            // If the document has been declined
            if ($envelope['status'] == 'declined') {
                Log::info("Growth Hub Outcome for company {$outcome->company_name} was declined.");
                $outcome->markAsDeclined();
            }

            // If the document has been delivered
            if ($envelope['status'] == 'delivered') {
                Log::info("Growth Hub Outcome for company {$outcome->company_name} was delivered to the signer.");
                $outcome->markAsDelivered();
            }

            // If the envelope is complete, timestamp it, notify the creator and grab the signed document
            if ($envelope['status'] == 'completed') {
                Log::info("Growth Hub Outcome for company {$outcome->company_name} was completed.");
                $completedAt = Carbon::parse($envelope['status_changed_date_time']);

                $filePath = "/outcomes/growth-hub/{$outcome->id}/signed.pdf";

                $signedDocument = $client->envelopes->getDocument(1, $outcome->envelope_id);

                $documentContents = file_get_contents($signedDocument->getPathname());

                Storage::disk('local')->put($filePath, $documentContents);

                $outcome->markAsCompleted($completedAt, $filePath);
            }
        }
    }
}


At the moment I have a private method to check each model type BUT they literally all basically do the same thing:

  • Check a status
  • Call a function
  • Send an email

Is this readable, and also, is there a better way?

I just feel like there's so much repetition.

Any suggestions?

May
13
4 months ago
Activity icon

Replied to Unknown Error When Logging Out

To all who are interested, it turns out the Listener for my Logout event was using the wrong Request class,.

I had imported use Illuminate\Http\Client\Request;

When it fact it should have been use Illuminate\Http\Request;.

I solved this because you guys mentioned checking my facades, so I had a comb through literally everything and found this rather annoying issue.

May
12
4 months ago
Activity icon

Started a new Conversation Unknown Error When Logging Out

In my application I decided to make my own LogoutController as I didn't see the necessity of using Auth::routes


<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Auth;

class LogoutController extends Controller
{
    /**
     * Logout and redirect to the login page
     *
     * @return void
     */
    public function logout(Request $request)
    {
        Auth::logout();

        $request->session()->invalidate();

        $request->session()->regenerateToken();

        return redirect()->route('login.ms');
    }
}

However, every time i try to actually log out i get the following error:

Illuminate\Contracts\Container\BindingResolutionException: Unresolvable dependency resolving [Parameter #0 [ $request ]] in class Illuminate\Http\Client\Request

I've never seen this error in my life and I'm certain it refers to something being added to the container but am unsure why this affects logging out specifically.

Activity icon

Replied to Testing Socialite Drivers

That's fair, I just think where Socialite does a lot of the heavy lifting initially there seems to be no reason to deep dive, I think I'm gonna go read up on Mocking a little more as you must be able to mock the provider.

Activity icon

Replied to Testing Socialite Drivers

I'm just surprised that the documentation is a little thin on this, because obviously you would expect it to work but also because i am then potentially creating a user from the returned Socialite user object, I kinda need to check.

I think the rest of the test classes are perhaps overly kind because you can just fake everything whereas i haven't seen Socialite::fake() anywhere.

If that were the case you could just provide a dummy user object, but in my login controller I have this:


try {
    $user_oath = Socialite::with('graph')->stateless()->user();
} catch (RequestException  $e) {
    Log::warning('A user attempted to login using an expired authorisation token using IP: ' . \Request::ip());
    return redirect()->route('login.ms');
} catch (\Exception $e) {
    Log::warning('A user could not login and was redirected back to the login screen using IP: ' . \Request::ip());
    return redirect()->route('login.ms');
}

So if you don't provide a valid set of parameters you get redirected anyway, so in my test I just get redirected.

Activity icon

Replied to Testing Socialite Drivers

So essentially just pretend i have a response from Socialite? That makes sense, I'll try it and post any updates.

May
11
4 months ago
Activity icon

Started a new Conversation Testing Socialite Drivers

In my application I have a LoginController that uses a third party Socialite driver in order to login using Microsoft OAuth.

https://socialiteproviders.netlify.app/providers/microsoft-graph.html

Testing the redirect was dead simple:


<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class LoginTest extends TestCase
{
    use RefreshDatabase;

    /** @test */
    public function it_is_redirected_to_microsoft_graph_login()
    {
        $response = $this->get(route('login.ms'));

        $this->assertStringContainsString('login.microsoftonline.com/common/oauth2/v2.0/authorize', $response->getTargetUrl());
    }

    /** @test */
    public function it_receives_graph_login_and_returns_user()
    {
        $response = $this->get(route('login.ms.callback'));

        // TODO: How do you test Socialite provider callback?
    }
}

I have no idea how to test the call back however.

Here is my LoginController


<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Socialite;
use App\User;
use Log;
use Auth;
use Illuminate\Http\Request;

class LoginController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');

        $this->citibase_email_domains = [
            '@citibase.co.uk', '@easyhub.com',
        ];

        $this->newable_email_domains = [
            '@newable.co.uk', '@tradelondon.org.uk', '@tradesoutheast.com',
        ];
    }

    /**
     * Redirect the user to the GitHub authentication page.
     *
     * @return \Illuminate\Http\Response
     */
    public function redirectToProvider()
    {
        return Socialite::driver('graph')->redirect();
    }

    /**
     * Obtain the user information from GitHub.
     *
     * @return \Illuminate\Http\Response
     */

    /**
     * Obtain the user information from OAuth and then either create or authenticate a user
     *
     * @return \Illuminate\Http\Response
     */
    public function handleProviderCallback(Request $request)
    {
        // Attempt to retreive a user through Microsoft Graph oAuth, if token has expired retry
        try {
            $user_oath = Socialite::with('graph')->stateless()->user();
        } catch (RequestException  $e) {
            Log::warning('A user attempted to login using an expired authorisation token using IP: ' . \Request::ip());
            return redirect()->route('login.ms');
        } catch (\Exception $e) {
            Log::warning('A user could not login and was redirected back to the login screen using IP: ' . \Request::ip());
            return redirect()->route('login.ms');
        }

        // Get the email used to authenticate
        $email = strtolower($user_oath->userPrincipalName);

        // Check to see if this user exists
        $user = User::withTrashed()->where('email', $email)->first();

        // Login the user if they exist
        if ($user) {
            // Restore this user if trashed
            if ($user->trashed()) {
                $user->restore();
            }

            // Login the user, setting a remember token
            Auth::login($user, true);

            // Redirect the user
            return redirect()->intended('/');
        } else {
            // If this user has a Citibase email address
            if (strpos_arr($email, $this->citibase_email_domains)) {
                //Create new user
                User::create([
                    'ms_id' => $user_oath->id,
                    'first_name' => $user_oath->givenName,
                    'last_name' => $user_oath->surname,
                    'email' => $user_oath->userPrincipalName,
                ]);
            } elseif (strpos_arr($email, $this->newable_email_domains)) {
                dd('Newable account');
                // NewableProfile::createNewableUser($email, $user_oath);
                return redirect()->intended('/');
            } else {
                // If no user was found but the user did not enter a valid email address
                Log::warning("{$email} attempted to access the Citibase Intranet but is not a recognised user");

                abort(403, 'Please ensure you are using a Citibase or Newable email address when attempting to access MyCitibase.');
            }
        }
    }
}


Essentially I'd like to test the conditions in the controller but how can I return a user from Socialite when I'd never enter my real email and password in a test?

Apr
20
5 months ago
Activity icon

Started a new Conversation Using Auth()->user() Within A Test

In an application I'm building a Comment can have a relation to both a User and an Article, so when creating the comment I just do the following:


$article->comments()->create($request->validated());

Then to associate the User I hook into the creating event of the Comment model to associate the user with the comment like so:


$comment->user()->associate(auth()->user());

However, in my test case it always squawks about comment user_id being null, which leads me to believe that in the test case auth()->user() is null.

How can this be so when I'm using actingAs() when calling the route to add the comment?

Apr
09
5 months ago
Activity icon

Started a new Conversation Optimising A Job Class

In my application I have a Job class that polls the DocuSign API for changes to envelopes, then if the envelope is seen as completed I update a bunch of fields and then place the signed file into local storage.

The class looks like this:


z<?php

namespace App\Jobs;

use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\CompanyRegistration;
use DocuSign;
use App\Notifications\RegistrationFormSigned;
use Carbon\Carbon;

class PollDocuSignEnvelopes implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * The number of times the job may be attempted.
     *
     * @var int
     */
    public $tries = 2;

    /**
     * Create a new job instance.
     */
    public function __construct()
    {
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        // Create a new DocuSign client
        $client = DocuSign::create();

        // Retrieve the application forms that have been created as envelopes, but not signed
        $envelopeIds = CompanyRegistration::select('envelope_id')
                            ->whereNotNull('envelope_id')
                            ->whereNull('envelope_signed_at')
                            ->pluck('envelope_id')
                            ->toArray();

        if ($envelopeIds) {
            // Define the options to be used when checking for changes
            $options = $client->envelopes->listStatusChangesOptions([
                'count' => 10,
                'envelope_ids' => $envelopeIds,
            ]);

            // Retrieve the changes via the listStatusChanges() API method
            $changes = $client->envelopes->listStatusChanges($options);

            // Iterate over the changed envelopes
            foreach ($changes['envelopes'] as $envelope) {
                $registration = CompanyRegistration::where('envelope_id', $envelope['envelope_id'])->first();

                $registration->update([
                    'envelope_status' => $envelope['status'],
                ]);

                // If the envelope is complete, timestamp it, notify the creator and grab the signed document
                if ($registration->envelope_status == 'completed') {
                    $path = "/registrations/{$registration->id}/signed.pdf";

                    // Retrieve the first document associated with the completed envelope
                    $document = $client->envelopes->getDocument(1, $registration->envelope_id);

                    $documentContents = file_get_contents($document->getPathname());

                    Storage::disk('local')->put($path, $documentContents);

                    $registration->update([
                        'envelope_signed_at' => Carbon::now(),
                        'envelope_completed_document_path' => $path,
                    ]);

                    $registration->user->notify(new RegistrationFormSigned($registration));
                }
            }
        }
    }

    /**
     * The job failed to process.
     *
     * @param  Exception $exception
     * @return void
     */
    public function failed(Exception $exception)
    {
        // Send user notification of failure, etc...
    }
}

I can't help think this is sub-optimal however, because I make a number of database calls and I can see a bunch of places it might fall over. Is it okay for jobs just to die silently, or should I break this into some listeners and trigger a main event from within the job?

E.g

Event

EnvelopeCompleted

Listeners

UpdateDocuSignStatus DownloadSignedFile

I'm in two minds...

Apr
07
5 months ago
Activity icon

Replied to Undefined Properties In Job

I have a basic question, that I've never really acknowledged as I've just gone with various examples from the documentation, it has two parts.

  1. If I could just create a new instance of what I need within the handle method, would I even need to pass it through the constructor, is it possible to just new up an object in the actual constructor?

  2. If I can just use $this within classes to access properties, is there any need to define properties, more so within job classes?

Lastly, within a job the handle method seems to be doing most of the work but I'm assuming you could pass attributes passed through the constructor?

Activity icon

Started a new Conversation Using Dependencies Inside Job Classes

When using a job in Laravel 6, how do you go about injecting dependencies? I read this is the documentation -

"The handle method is called when the job is processed by the queue. Note that we are able to type-hint dependencies on the handle method of the job. The Laravel service container automatically injects these dependencies."

Here is the example given:


<?php

namespace App\Jobs;

use App\Podcast;
use App\AudioProcessor;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class ProcessPodcast implements ShouldQueue
{
    use InteractsWithQueue, Queueable, SerializesModels;

    protected $podcast;

    /**
     * Create a new job instance.
     *
     * @param  Podcast  $podcast
     * @return void
     */
    public function __construct(Podcast $podcast)
    {
        $this->podcast = $podcast;
    }

    /**
     * Execute the job.
     *
     * @param  AudioProcessor  $processor
     * @return void
     */
    public function handle(AudioProcessor $processor)
    {
        // Process uploaded podcast...
    }
}

But say I wanted to use a 3rd party package, would it work in the same way?

Activity icon

Started a new Conversation Undefined Properties In Job

I am using DocuSign within my application and I created a job to accomplish polling, that is, checking whether a document was updated without using a webhook.

The job is called PollDocuSignEnvelopes and makes a call to the DocuSign API to check for changes.

Here is the code:


<?php

namespace App\Jobs;

use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\CompanyRegistration;
use App\DocuSign\DocuSign as DocuSignWrapper;
use App\Notifications\RegistrationFormSigned;

class PollDocuSignEnvelopes implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * The number of times the job may be attempted.
     *
     * @var int
     */
    public $tries = 2;

    /**
     * The instance of DocuSignWrapper
     *
     * @var DocuSign
     */
    public $docusignWrapper;

    /**
     * Create a new job instance
     *
     * @param \App\DocuSign\DocuSign $docusignWrapper
     */
    public function __construct()
    {
        $this->docuSignWrapper = new DocuSignWrapper;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        // Retrieve the application forms that have been sent
        $envelopeIds = CompanyRegistration::select('envelope_id')
            ->whereNotNull('envelope_id')
            ->pluck('envelope_id')
            ->toArray();

        $envelopes = $this->docuSignWrapper->pollEnvelopeChanges($envelopeIds);

        foreach ($envelopes as $envelope) {
            $registration = CompanyRegistration::where('envelope_id', $envelope['envelope_id'])
                ->first()
                ->update([
                    'envelope_status' => $envelope['status'],
                ]);

            // If the status comes back as completed, notify the creator
            if ($registration->is_completed) {
                $registration->user->notify(new RegistrationFormSigned($registration));
            }
        }
    }

    /**
     * The job failed to process.
     *
     * @param  Exception $exception
     * @return void
     */
    public function failed(Exception $exception)
    {
        // Send user notification of failure, etc...
    }
}

However, apparently DocuSignWrapper is undefined even though I'm clearly setting it? Am I not supposed to new up classes in the __construct() method?


ErrorException: Undefined property: App\Jobs\PollDocuSignEnvelopes::$docuSignWrapper in /homepages/6/d142103519/htdocs/development-sites/ita-portal/app/Jobs/PollDocuSignEnvelopes.php:56
Stack trace:
#0 /homepages/6/d142103519/htdocs/development-sites/ita-portal/app/Jobs/PollDocuSignEnvelopes.php(56): Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(8, 'Undefined prope...', '/homepages/6/d1...', 56, Array)
#1 [internal function]: App\Jobs\PollDocuSignEnvelopes->handle()
#2 /homepages/6/d142103519/htdocs/development-sites/ita-portal/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(32): call_user_func_array(Array, Array)
#3 /homepages/6/d142103519/htdocs/development-sites/ita-portal/vendor/laravel/framework/src/Illuminate/Container/Util.php(36): Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
#4 /homepages/6/d142103519/htdocs/development-sites/ita-portal/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(90): Illuminate\Container\Util::unwrapIfClosure(Object(Closure))
#5 /homepages/6/d142103519/htdocs/development-sites/ita-portal/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(34): Illuminate\Container\BoundMethod::callBoundMethod(Object(Illuminate\Foundation\Application), Array, Object(Closure))
#6 /homepages/6/d142103519/htdocs/development-sites/ita-portal/vendor/laravel/framework/src/Illuminate/Container/Container.php(590): Illuminate\Container\BoundMethod::call(Object(Illuminate\Foundation\Application), Array, Array, NULL)
#7 /homepages/6/d142103519/htdocs/development-sites/ita-portal/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php(94): Illuminate\Container\Container->call(Array)
#8 /homepages/6/d142103519/htdocs/development-sites/ita-portal/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(130): Illuminate\Bus\Dispatcher->Illuminate\Bus\{closure}(Object(App\Jobs\PollDocuSignEnvelopes))
#9 /homepages/6/d142103519/htdocs/development-sites/ita-portal/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(105): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(App\Jobs\PollDocuSignEnvelopes))
#10 /homepages/6/d142103519/htdocs/development-sites/ita-portal/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php(98): Illuminate\Pipeline\Pipeline->then(Object(Closure))
#11 /homepages/6/d142103519/htdocs/development-sites/ita-portal/vendor/laravel/framework/src/Illuminate/Queue/CallQueuedHandler.php(83): Illuminate\Bus\Dispatcher->dispatchNow(Object(App\Jobs\PollDocuSignEnvelopes), false)
#12 /homepages/6/d142103519/htdocs/development-sites/ita-portal/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(130): Illuminate\Queue\CallQueuedHandler->Illuminate\Queue\{closure}(Object(App\Jobs\PollDocuSignEnvelopes))
#13 /homepages/6/d142103519/htdocs/development-sites/ita-portal/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(105): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(App\Jobs\PollDocuSignEnvelopes))
#14 /homepages/6/d142103519/htdocs/development-sites/ita-portal/vendor/laravel/framework/src/Illuminate/Queue/CallQueuedHandler.php(85): Illuminate\Pipeline\Pipeline->then(Object(Closure))
#15 /homepages/6/d142103519/htdocs/development-sites/ita-portal/vendor/laravel/framework/src/Illuminate/Queue/CallQueuedHandler.php(59): Illuminate\Queue\CallQueuedHandler->dispatchThroughMiddleware(Object(Illuminate\Queue\Jobs\DatabaseJob), Object(App\Jobs\PollDocuSignEnvelopes))
#16 /homepages/6/d142103519/htdocs/development-sites/ita-portal/vendor/laravel/framework/src/Illuminate/Queue/Jobs/Job.php(88): Illuminate\Queue\CallQueuedHandler->call(Object(Illuminate\Queue\Jobs\DatabaseJob), Array)
#17 /homepages/6/d142103519/htdocs/development-sites/ita-portal/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(368): Illuminate\Queue\Jobs\Job->fire()
#18 /homepages/6/d142103519/htdocs/development-sites/ita-portal/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(314): Illuminate\Queue\Worker->process('database', Object(Illuminate\Queue\Jobs\DatabaseJob), Object(Illuminate\Queue\WorkerOptions))
#19 /homepages/6/d142103519/htdocs/development-sites/ita-portal/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(134): Illuminate\Queue\Worker->runJob(Object(Illuminate\Queue\Jobs\DatabaseJob), 'database', Object(Illuminate\Queue\WorkerOptions))
#20 /homepages/6/d142103519/htdocs/development-sites/ita-portal/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(112): Illuminate\Queue\Worker->daemon('database', 'default', Object(Illuminate\Queue\WorkerOptions))
#21 /homepages/6/d142103519/htdocs/development-sites/ita-portal/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(96): Illuminate\Queue\Console\WorkCommand->runWorker('database', 'default')
#22 [internal function]: Illuminate\Queue\Console\WorkCommand->handle()
#23 /homepages/6/d142103519/htdocs/development-sites/ita-portal/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(32): call_user_func_array(Array, Array)
#24 /homepages/6/d142103519/htdocs/development-sites/ita-portal/vendor/laravel/framework/src/Illuminate/Container/Util.php(36): Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
#25 /homepages/6/d142103519/htdocs/development-sites/ita-portal/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(90): Illuminate\Container\Util::unwrapIfClosure(Object(Closure))
#26 /homepages/6/d142103519/htdocs/development-sites/ita-portal/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(34): Illuminate\Container\BoundMethod::callBoundMethod(Object(Illuminate\Foundation\Application), Array, Object(Closure))
#27 /homepages/6/d142103519/htdocs/development-sites/ita-portal/vendor/laravel/framework/src/Illuminate/Container/Container.php(590): Illuminate\Container\BoundMethod::call(Object(Illuminate\Foundation\Application), Array, Array, NULL)
#28 /homepages/6/d142103519/htdocs/development-sites/ita-portal/vendor/laravel/framework/src/Illuminate/Console/Command.php(134): Illuminate\Container\Container->call(Array)
#29 /homepages/6/d142103519/htdocs/development-sites/ita-portal/vendor/symfony/console/Command/Command.php(255): Illuminate\Console\Command->execute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
#30 /homepages/6/d142103519/htdocs/development-sites/ita-portal/vendor/laravel/framework/src/Illuminate/Console/Command.php(121): Symfony\Component\Console\Command\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
#31 /homepages/6/d142103519/htdocs/development-sites/ita-portal/vendor/symfony/console/Application.php(1001): Illuminate\Console\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#32 /homepages/6/d142103519/htdocs/development-sites/ita-portal/vendor/symfony/console/Application.php(271): Symfony\Component\Console\Application->doRunCommand(Object(Illuminate\Queue\Console\WorkCommand), Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#33 /homepages/6/d142103519/htdocs/development-sites/ita-portal/vendor/symfony/console/Application.php(147): Symfony\Component\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#34 /homepages/6/d142103519/htdocs/development-sites/ita-portal/vendor/laravel/framework/src/Illuminate/Console/Application.php(93): Symfony\Component\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#35 /homepages/6/d142103519/htdocs/development-sites/ita-portal/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(131): Illuminate\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#36 /homepages/6/d142103519/htdocs/development-sites/ita-portal/artisan(37): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#37 {main}

Apr
03
5 months ago
Activity icon

Replied to Accessing Relationship Within A Pivot Table Using BelongsToMany

So you have 4 models:

  • Centre
  • HealthAndSafetyDocument
  • CentreHealthAndSafetyDocument
  • Document

In what you've you've defined that a Centre can have many HealthAndSafetyDocument

Do you have a relation between Document and HealthAndSafetyDocument?

I'm wondering if it'd be easier to define an extra relation on the Centre which is a HasManyThrough so you could get to Document through HealthAndSafetyDocument?

A hasManyThrough is defined in this way:

    public function posts()
    {
        return $this->hasManyThrough(
            'App\Post',
            'App\User',
            'country_id', // Foreign key on users table...
            'user_id', // Foreign key on posts table...
            'id', // Local key on countries table...
            'id' // Local key on users table...
        );
    }

So you could have within Centre a relation like so:


    public function documents()
    {
        return $this->hasManyThrough(
            'App\Document', // distant table
            'App\HealthAndSafetyDocument', // middle table
            'centre_id', // Foreign key on health safety table...
            'health_document_id', // Foreign key on documents table...
            'id', // Local key on this table
            'id' // Local key on middle table
        );
    }

Apr
02
5 months ago
Activity icon

Started a new Conversation Avoiding Duplication When Using Similar Models

In my application I have two models: Registration and Outcome these are used to hold data from two different forms.

Here is the schema for Registrations whose table is called company_registrations


<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateCompanyRegistrationsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('company_registrations', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('user_id');
            $table->string('envelope_id')->nullable();
            $table->string('envelope_status')->nullable();
            $table->foreign('user_id')->references('id')->on('users');
            // Company details
            $table->string('contact_name')->nullable();
            $table->string('international_trade_advisor')->nullable();
            $table->string('position')->nullable();
            $table->string('company_name')->nullable();
            $table->string('telephone_number')->nullable();
            $table->string('company_registration_number')->nullable();
            $table->string('unique_tax_reference')->nullable();
            $table->text('address')->nullable();
            $table->string('email')->nullable();
            $table->string('website')->nullable();
            // SME fields
            $table->boolean('employs_less_than_250_people')->nullable();
            $table->boolean('annual_turnover_below_50_million')->nullable();
            $table->boolean('balance_sheet_below_50_million')->nullable();
            $table->boolean('is_subsidary')->nullable();
            // Difficulty
            $table->boolean('is_undertaking_in_difficulty')->nullable();
            $table->boolean('insolvency_proceedings')->nullable();
            $table->boolean('share_accumulated_losses')->nullable();
            $table->boolean('in_receipt_of_rescue_aid')->nullable();
            // Other details
            $table->timestamp('date_of_incorporation')->nullable();
            $table->integer('employee_count')->nullable();
            $table->string('annual_turnover')->nullable();
            $table->string('sector')->nullable();
            // About company
            $table->text('products_services')->nullable();
            $table->text('countries_of_interest')->nullable();
            $table->boolean('is_intending_to_grow_export_business')->nullable();
            $table->boolean('is_making_new_market_sales')->nullable();
            $table->boolean('has_exported_in_last_12_months')->nullable();
            // Financial information
            $table->string('financial_year_end')->nullable();
            $table->string('turnover')->nullable();
            $table->string('export_turnover')->nullable();
            $table->string('total_salary_wage_cost')->nullable();
            $table->string('deprecation')->nullable();
            $table->string('net_profit_before_tax')->nullable();
            // Diversity
            $table->string('ethnic_ownership_majority')->nullable();
            $table->string('sex_ownership_majority')->nullable();
            $table->string('disability_ownership_majority')->nullable();
            $table->string('signer_age_group')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('company_registrations');
    }
}


The other table is kind of similar but has a few different fields, so I separated it into a new model.

To add a little more context, I'm using these forms to populate a DocuSign template.

The code for which is duplicated somewhat in both the RegistrationController and OutcomeController

The RegistrationController looks like this:


<?php

namespace App\Http\Controllers;

use App\CompanyRegistration;
use App\Http\Requests\StoreRegistration;
use App\Http\Requests\UpdateRegistration;
use App\Jobs\PollDocuSignEnvelopes;
use Illuminate\Http\Request;
use DocuSign;

class RegistrationController extends Controller
{
    /**
     * Create a new controller instance
     */
    public function __construct()
    {
        $this->client = DocuSign::create();
    }

    /**
     * Display a listing of all my registration forms
     */
    public function index()
    {
        $registrations = auth()->user()->registrations;

        PollDocuSignEnvelopes::dispatchNow();

        return view('forms.registrations.index', compact('registrations'));
    }

    /**
     * Display the view that holds the application form.
     */
    public function create()
    {
        $tempplateDefinition = $this->client->templates->get(CompanyRegistration::DOCUSIGN_TEMPLATE_ID);

        $tabs = $tempplateDefinition['recipients']['signers'][0]['tabs'];

        dump($tabs);

        return view('forms.registrations.create');
    }

    /**
     * Store an application in the database
     *
     * @param \Illuminate\Http\Request $request
     */
    public function store(StoreRegistration $request)
    {
        $attributes = $request->validated();

        $registration = auth()->user()->registrations()->create([
            'contact_name' => $attributes['contact_name'],
            'international_trade_advisor' => $attributes['international_trade_advisor'],
            'position' => $attributes['position'],
            'company_name' => $attributes['company_name'],
            'telephone_number' => $attributes['telephone_number'],
            'company_registration_number' => $attributes['company_registration_number'],
            'address' => $attributes['address'],
            'email_address' => $attributes['email'],
            'website' => $attributes['website'],
            'employs_less_than_250_people' => $attributes['employs_less_than_250_people'] ?? 0,
            'annual_turnover_below_50_million' => $attributes['annual_turnover_below_50_million'] ?? 0,
            'balance_sheet_below_50_million' => $attributes['balance_sheet_below_50_million'] ?? 0,
            'is_subsidary' => $attributes['is_subsidary'] ?? 0,
            'is_undertaking_in_difficulty' => $attributes['is_undertaking_in_difficulty'] ?? 0,
            'date_of_incorporation' => $attributes['date_of_incorporation'],
            'employee_count' => $attributes['employee_count'],
            'annual_turnover' => $attributes['annual_turnover'],
            'sector' => $attributes['sector'],
            'products_services' => $attributes['products_services'],
            'countries_of_interest' => $attributes['countries_of_interest'],
            'is_intending_to_grow_export_business' => $attributes['is_intending_to_grow_export_business'] ?? 0,
            'is_making_new_market_sales' => $attributes['is_making_new_market_sales'] ?? 0,
            'has_exported_in_last_12_months' => $attributes['has_exported_in_last_12_months'] ?? 0,
            'financial_year_end' => $attributes['financial_year_end'],
            'turnover' => $attributes['turnover'],
            'export_turnover' => $attributes['export_turnover'],
            'total_salary_wage_cost' => $attributes['total_salary_wage_cost'],
            'deprecation' => $attributes['deprecation'],
            'net_profit_before_tax' => $attributes['net_profit_before_tax'],
        ]);

        $this->addSupporters($registration, $attributes);

        return redirect()->route('registrations.edit', $registration)->withSuccess('Registration form saved. Now please review the details.');
    }

    /**
     * Display this registration
     *
     * @param \App\CompanyRegistration $registration
     */
    public function show(CompanyRegistration $registration)
    {
        return view('forms.registrations.show', compact('registration'));
    }

    /**
     * Display the form to edit a company registration
     *
     * @param \App\CompanyRegistration $registration
     */
    public function edit(CompanyRegistration $registration)
    {
        // $this->authorize('update', $registration);

        return view('forms.registrations.edit', compact('registration'));
    }

    /**
     * Store an application in the database
     *
     * @param \Illuminate\Http\Request $request
     */
    public function update(UpdateRegistration $request, CompanyRegistration $registration)
    {
        // $this->authorize('update', $registration);

        $attributes = $request->validated();

        $registration->update([
            'contact_name' => $attributes['contact_name'],
            'international_trade_advisor' => $attributes['international_trade_advisor'],
            'position' => $attributes['position'],
            'company_name' => $attributes['company_name'],
            'telephone_number' => $attributes['telephone_number'],
            'company_registration_number' => $attributes['company_registration_number'],
            'address' => $attributes['address'],
            'email_address' => $attributes['email'],
            'website' => $attributes['website'],
            'employs_less_than_250_people' => $attributes['employs_less_than_250_people'] ?? 0,
            'annual_turnover_below_50_million' => $attributes['annual_turnover_below_50_million'] ?? 0,
            'balance_sheet_below_50_million' => $attributes['balance_sheet_below_50_million'] ?? 0,
            'is_subsidary' => $attributes['is_subsidary'] ?? 0,
            'is_undertaking_in_difficulty' => $attributes['is_undertaking_in_difficulty'] ?? 0,
            'date_of_incorporation' => $attributes['date_of_incorporation'],
            'employee_count' => $attributes['employee_count'],
            'annual_turnover' => $attributes['annual_turnover'],
            'sector' => $attributes['sector'],
            'products_services' => $attributes['products_services'],
            'countries_of_interest' => $attributes['countries_of_interest'],
            'is_intending_to_grow_export_business' => $attributes['is_intending_to_grow_export_business'] ?? 0,
            'is_making_new_market_sales' => $attributes['is_making_new_market_sales'] ?? 0,
            'has_exported_in_last_12_months' => $attributes['has_exported_in_last_12_months'] ?? 0,
            'financial_year_end' => $attributes['financial_year_end'],
            'turnover' => $attributes['turnover'],
            'export_turnover' => $attributes['export_turnover'],
            'total_salary_wage_cost' => $attributes['total_salary_wage_cost'],
            'deprecation' => $attributes['deprecation'],
            'net_profit_before_tax' => $attributes['net_profit_before_tax'],
        ]);

        $this->addSupporters($registration, $attributes);

        return redirect()->route('registrations.show', $registration)->withSuccess('Details confirmed. Pleae review and send');
    }

    /**
     * Add registration supports to this registration
     *
     * @param \App\CompanyRegistration $registration
     * @param array                    $attributes
     */
    private function addSupporters(CompanyRegistration $registration, array $attributes)
    {
        $supporters = $attributes['registration_supporters'];

        if (is_array($supporters) && count($supporters) > 0) {
            foreach ($supporters as $support) {
                $registration->supporters()->create([
                    'funding_body' => $support['funding_body'],
                    'purpose' => $support['purpose'],
                    'amount' => $support['amount'],
                ]);
            }
        }
    }

    /**
     * Send the data in this form to a signer via DocuSign
     *
     * @param \App\CompanyRegistration $registration
     */
    public function sendForSigning(CompanyRegistration $registration, Request $request)
    {
        $data = $request->validate([
            'signer_name' => 'required|string|max:191',
            'signer_email' => 'required|string|email|max:191',
        ]);

        // Populate the template data attributes
        $defaultSigner = $this->client->templateRole([
            'email' => $data['signer_email'],
            'name' => $data['signer_name'],
            'role_name' => 'Signer 1',
            'routing_order' => 1,
            'tabs' => [
                'textTabs' => [
                    [
                        'tabLabel' => 'Contact name',
                        'value' => $registration->contact_name,
                    ],
                    [
                        'tabLabel' => 'International Trade Advisor',
                        'value' => $registration->international_trade_advisor,
                    ],
                    [
                        'tabLabel' => 'Position',
                        'value' => $registration->position,
                    ],
                    [
                        'tabLabel' => 'Company Name',
                        'value' => $registration->company_name,
                    ],
                    [
                        'tabLabel' => 'Telephone number',
                        'value' => $registration->telephone_number,
                    ],
                    [
                        'tabLabel' => 'Company registration number (CRN)',
                        'value' => $registration->company_registration_number,
                    ],
                    [
                        'tabLabel' => 'Address',
                        'value' => $registration->address,
                    ],
                    [
                        'tabLabel' => 'Email',
                        'value' => $registration->email,
                    ],
                    [
                        'tabLabel' => 'Website',
                        'value' => $registration->website,
                    ],
                ],
            ],
        ]);

        // Define the DocuSign envelope
        $envelopeDefinition = $this->client->envelopeDefinition([
            'status' => 'sent',
            'email_subject' => 'SME Application Form - Please review and sign',
            'template_id' => CompanyRegistration::DOCUSIGN_TEMPLATE_ID,
            'template_roles' => [
                $defaultSigner,
            ],
        ]);

        // Retrieve the envelope summary
        $envelopeSummary = $this->client->envelopes->createEnvelope($envelopeDefinition);

        // Update the envelope details on the model
        $registration->update([
            'envelope_id' => $envelopeSummary['envelope_id'],
            'envelope_status' => $envelopeSummary['status'],
        ]);

        return redirect()->route('dashboard')
            ->withSuccess('Registration form for ' . $registration->company_name . ' sent to ' . $data['signer_email']);
    }
}

The sendForSigning() method is going to be literally identical, minus the template ID and the data passed in.

IMHO this feels a little dirty because huge chunks will be replicated.

The same applies for the notifications of RegistrationSent and OutcomeSent, the only difference being the model type that gets passed in.

I also have a job that polls DocuSign for updates that feels repetitive.


<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\CompanyRegistration;
use App\DocuSign\DocuSign as DocuSignWrapper;
use App\Notifications\RegistrationFormSigned;

class PollDocuSignEnvelopes implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance
     *
     * @param \App\DocuSign\DocuSign $docusignWrapper
     */
    public function __construct()
    {
        $this->docusignWrapper = new DocuSignWrapper;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        // Retrieve the application forms that have been sent
        $registationEnvelopes = CompanyRegistration::select('envelope_id')
            ->isSentDocuSign()
            ->pluck('envelope_id')
            ->toArray();

        // Merge all the envelope IDs into one big array
        $envelopeIds = array_merge($registationEnvelopes);

        $envelopes = $this->docusignWrapper->pollEnvelopeChanges($envelopeIds);

        // Loop through the given envelopes and update the statuses
        foreach ($envelopes as $envelope) {
            $registration = CompanyRegistration::where('envelope_id', $envelope['envelope_id'])->first();

            $registration->update([
                'envelope_status' => $envelope['status'],
            ]);

            // If the status comes back as completed, notify the creator
            if ($registration->is_completed) {
                $registration->user->notify(new RegistrationFormSigned($registration));
            }
        }
    }
}

You can see how that would also become repetitive.

So, my question is: is this a bad thing, because the data in each form is technically a different entity?