matttonks11

matttonks11

Member Since 1 Year Ago

Experience Points 23,270
Experience Level 5

1,730 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 202
Lessons
Completed
Best Reply Awards 3
Best Reply
Awards
  • start-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-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-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist 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.

12 Jul
1 week ago

matttonks11 left a reply on Model Relationship Only One Column

On your Product model, in the primary function you should change get() to first(), get() returns a collection instance, where first() returns the object

E.g.

 public function primary() {
    return $this->productImages()->select('image')->where('primary','=', 1)->first();
}

Hope this helps

09 Jul
1 week ago

matttonks11 left a reply on Why Is Laravel Adding A Trailing Forward-slash To My Values In My Form?

It is due to your value attributes missing ""

e.g. currently you have


value={{ $returns->customerNr }}/>

what it should be

value="{{ $returns->customerNr }}"/>

Hope this helps

03 Jul
2 weeks ago

matttonks11 left a reply on Creating Models With Controllers, Factories And Migrations

If you would like to create all 4 at once you can use the php artisan make:model Post -a you can also run php artisan help make:model to see the other options available

11 Jun
1 month ago

matttonks11 left a reply on A Non Well Formed Numeric Value Encountered On Laravel Excel Package

Hi, I used this function in one of my projects, just add it to your import class

private function transformDateTime(string $value, string $format = 'Y-m-d')
    {
        try {
            return Carbon::instance(Date::excelToDateTimeObject($value))->format($format);
        } catch (\ErrorException $e) {
            return Carbon::createFromFormat($format, $value);
        }
    }

You'll have to import Carbon\Carbon and the PhpOffice\PhpSpreadsheet\Shared\Date classes

To use it just change the line you have currently to

    $this->transformDateTime($row[3])

You can add a second argument to change the date's format if you need.

05 Jun
1 month ago

matttonks11 left a reply on Returning First() With Maatwebsite/laravel-excel

If your exporting a collection you need to update your class

use Maatwebsite\Excel\Concerns\FromCollection;

class SuppliersExport implements FromCollection
{
  
    public function collection()
    {
        return Supplier::query()->where('user_id', auth()->id())->latest()->first();
    }
}

You can see more here https://docs.laravel-excel.com/3.1/exports/collection.html

matttonks11 left a reply on Query Relationships In Laravel

Also relationships are generally there for ease of use I believe, so things like readability, it also saves you writing out that join multiple times in your codebase.

matttonks11 left a reply on Query Relationships In Laravel

Hi, are you sure everything is correct with spelling? Does the rest of the query work if you temporarily remove that line?

 DB::raw('MIN(carts.ca_numlineitems) as items')

matttonks11 left a reply on Query Relationships In Laravel

Hi, you should try

$vouchers = Voucher::with('cart.lineItems');

Since the cart model is the one with the lineItems relationship and not the Voucher model. You can then chain the rest of the methods like so

$vouchers = Voucher::with('cart.lineItems')
->whereBetween('vouchers.vchlastmodmsec', [$fromDate, $toDate])
->groupBy(['redeemed_date', 'order_date', 'order_id', 'settlement_status'])

I'm pretty sure you can use ```when()`` instead of the IF statements also if you prefer

see more here https://laraveldaily.com/less-know-way-conditional-queries/

So it looks something like this...

$query = Voucher::with('cart.lineItems')
->whereBetween('vouchers.vchlastmodmsec', [$fromDate, $toDate])
->groupBy(['redeemed_date', 'order_date', 'order_id', 'settlement_status']);

$query->when($request->filled('brand') && $request->input('brand'), function ($query) use($request) {
    return $query->where('carts.ca_brandid', $request->input('brand'));
})

$query->when($request->filled('city') && $request->input('city'), function ($query) use($request) {
    return $query->where('carts.ca_redmcitycode', $request->input('city'));
});

$vouchers = $query->get();
27 Mar
3 months ago

matttonks11 left a reply on Getting A Forbidden When Trying To Access My Controller

Hi what happens if you remove the 'web' from the Route::group I believe this already gets set so you may be trying to set it twice which is causing the issue?

24 Mar
3 months ago

matttonks11 left a reply on Return Eloquent Model With Extra Data

Hi I believe you can use an Accessor for this

https://laravel.com/docs/5.8/eloquent-mutators

something like....


/**
 * Get the courses built up path.
 *
 * @return string
 */
public function getPathAttribute()
{
    return $this->path();
}

then when you fetch a course it should be accessible by using $course->path

09 Mar
4 months ago

matttonks11 started a new conversation 5.8 Testing Issue - No Application Encryption Key Has Been Specified.

Hi there,

I'm running into an issue when I install a new 5.8 project and run phpunit.

I get the following error...

1) Tests\Feature\ExampleTest::testBasicTest
RuntimeException: No application encryption key has been specified.

However I can visit the app in the browser and it doesn't throw the same error which it would do if the encryption key didn't actually exist.

Also if I run the command in a project that uses 5.7 it works fine and even if I install a fresh version of 5.7 using

composer create-project laravel/laravel="5.7.*" myProject

everything works fine.

Has anyone got any ideas or encountered this situation and could provide some guidance?

07 Mar
4 months ago

matttonks11 left a reply on Get Users Subjects With Lessons Scoped To User

Hi thank you both for your answers, but I still don't get the results I'm looking for. I've added the local/foreign keys to the subjects() relationship but when I use the relationship in my blade template I'm still getting all of the lessons for a particular subject rather than the ones a user belongs to.

@foreach ($userSubjects as $subject)
    <div class="card mb-2">
        <div class="card-header">
                        <a href="#"> {{$subject->name}}</a>
                </div>
                <div class="card-body">
            @foreach($subject->lessons as $userLesson)
                            <a href="#">{{$userLesson->name}}</a> //Should be only lessons that belong to user
                        @endforeach
                </div>
    </div>
 @endforeach

Updated Model

/**
* returns a users related subjects
*/
public function subjects()
{
    return $this->belongsToMany('App\Subject', 'user_subjects', 'user_id', 'subject_id');
 }
06 Mar
4 months ago

matttonks11 started a new conversation Get Users Subjects With Lessons Scoped To User

Hi there,

I have a relation set up on my User model to get a users Subjects

/**
* returns a users related subjects
*/
public function subjects()
{
    return $this->belongsToMany('App\Subject', 'user_subjects');
 }

On the Subject Model I have a relationship set up to get the related lessons

/**
* returns all the lessons for a particular subject
*/
public function lessons()
{
    return $this->hasMany('App\Lesson');
}

What I am trying to do is get the users subjects with the lessons that they belong to.

At the moment I'm just getting back all of the lessons for a particular subject rather than the lessons that belong to the user.

I have a migration set up to link the users and lessons so there is a relationship between users and lessons. I just cannot figure out how to get the users subjects with all of their specific lessons

Has anyone done anything similar or know how best to do this?

04 Mar
4 months ago

matttonks11 left a reply on Trying To Get Property Of Non-object Auth()->user()->subjects()

I've fixed this now, there was an issue with my scope

matttonks11 started a new conversation Trying To Get Property Of Non-object Auth()->user()->subjects()

Hi there,

I'm currently trying to test some middleware I created for my application. However i'm currently getting the error message...

ErrorException: Trying to get property 'subjects' of non-object (View: C:\xampp\htdocs\educatum\resources\views\home.blade.php)


use RefreshDatabase;

public function setUp() : void
{
        parent::setUp();

        Role::create(['name' => 'student']);
        Role::create(['name' => 'teacher']);
        Role::create(['name' => 'admin']);
}

/** @test */
public function a_student_can_access_student_pages()
{
    $this->withoutExceptionHandling();

    //create user
        $user = factory('App\User')->create();

    //assign them as a student
        $user->assignRole('student');


    //Sign them in
        $this->actingAs($user);

       
    Assert the student home page loads correctly
        $this->get('/students/home')->assertStatus(200);
}

subjects is a scope on the User model to fetch subjects for a signed in user.

The weird thing is there is no issue in the browser and everything works fine. If I removed the call to subjects in the blade file the test passes.

I'm just unsure as to why this affects the test, can anybody provide some help?

08 Feb
5 months ago

matttonks11 left a reply on Foreign Key Constraint Is Incorrectly Formed

What order are your migrations in?

If the Stock table has been created before the Medicine table when the migrations run they run in order of creation I think.

So if your adding a foreign key constraint to the Stock table involving the Medicine table it might not be able to find the Medicine table because it hasn't been migrated yet if that makes sense?

06 Feb
5 months ago

matttonks11 started a new conversation Using Laravel Rules

Hi,

I'm using the maatwebsite/excel package to import data to my application and I would like to validate that data.

Following their documentation they use the Rule facade to get the rules required.

I am wondering how do you reference the validation rules like regex using facades? The Illuminate\Validation\Rule facade only contains a few of the available validation rules and I've tried to look through the API reference for the answer with no luck.

Any help would be greatly appreciated

03 Feb
5 months ago

matttonks11 left a reply on Creating A Manual Simple Paginator

Paginator {#12748 ▼
  #hasMore: false
  #items: Collection {#12750 ▶}
  #perPage: 16
  #currentPage: 2
  #path: "https://lybrary.test/books"
  #query: []
  #fragment: null
  #pageName: "page"
  +onEachSide: 3
  #options: array:1 [▶]
}

hasMore always seems to be returning false which is stopping the links from showing

I updated my controller method to this


public function index(Request $request, Book $book)
    {
        $books = $book->groupBy('isbn')->latest()->get()->toArray();

        $perPage = 16;
        $offsetPages = $request->input('page', 1) - 1;

        $books = array_slice($books, $offsetPages * $perPage, $perPage);

        $books = new Paginator( $books, $perPage, Paginator::resolveCurrentPage(), ['path' => Paginator::resolveCurrentPath()]);


        return view('books.index', ['books' => $books]);
    }

matttonks11 left a reply on Creating A Manual Simple Paginator

@jlrdw thanks for that information, Is there a need for me to use that code if I just want a simple Paginator with the previous and next links?

I took this code from the Laravel up and running book to manually create a paginator, the data gets returned properly, but the links won't display on the first page of results.

If I manually add ?page=2 to the url to get the second page of results, the next page link does not work and the previous page link ignores the current path within my application and returns to app.test?page=2 rather than app.test/books?page=2


public function index(Request $request, Book $book)
    {
        $books = $book->groupBy('isbn')->latest()->get()->toArray();

        $perPage = 16;
        $offsetPages = $request->input('page', 1) - 1;

        $books = array_slice($books, $offsetPages * $perPage, $perPage);

        $books = new Paginator( $books, $perPage);

        return view('books.index', ['books' => $books]);
    }

{{ $books->links() }} //Displaying links in blade view

Do you have any ideas as to what is going wrong?

02 Feb
5 months ago

matttonks11 started a new conversation Creating A Manual Simple Paginator

Hi,

I was wondering if someone can explain how to create a manual simple paginator?

I've got my data, which uses a groupBy statement so I believe I need to create a manual paginator.

I've just got no idea how to do this and from looking around online, there's no simple concrete examples I can find

I think I'm supposed to pass the data to the Illuminate\Pagination\Paginator construct method but where do I go from there in terms of returning my view and displaying the pagination links in that view...


$book->groupBy('isbn')->latest() //my data

Any help would be greatly appreciated

29 Jan
5 months ago

matttonks11 left a reply on Append Additional Data To Request

@jawelo That's great, thanks for your advice

matttonks11 started a new conversation Append Additional Data To Request

When making a post request to store some data, I'm using a Request object to validate the data first before it hits the store method on my controller.

I was wondering is there a simple way to add an extra piece of data to the request object so it's available when the validated data hits the controller?

25 Jan
5 months ago

matttonks11 left a reply on Help Testing Laravel Excel Import

I've found this which has helped me write the test, might be useful to anyone coming back to this

https://github.com/Maatwebsite/Laravel-Excel/issues/1917

matttonks11 started a new conversation Help Testing Laravel Excel Import

Hello there,

I'm currently using Maatwebsite/Laravel-Excel to import some data to my application. I've quickly set up the store method on my controller to import the data and have physically tested that the data gets imported properly, which it does.

However I'm looking to write a test just for peace of mind, but I'm having trouble writing the test.

Here's my current test at the moment


class ImportingBorrowersTest extends TestCase
{
    use RefreshDatabase;

    /** @test */
    public function a_user_can_import_borrowers_via_spreadsheets()
    {
        $this->signIn();

        Storage::fake('borrowers');

        $testFile = UploadedFile::fake()->create('borrowers.xlsx');

        Excel::fake();

        $this->post('borrowers', ['borrowers' => $testFile]);

        Excel::assertImported('borrowers.xlsx', 'borrowers');
    }
}

When I run this, it fails with the message borrowers.xlsx is not stored on disk borrowers. Failed asserting that an array has the key 'borrowers.xlsx'.

My question is, has anyone written a similar test who could help me understand how to write it properly?

15 Jan
6 months ago

matttonks11 left a reply on Single Test Making Multiple Assertions

@tomopongrac Ah right, thank you that makes sense now.

matttonks11 started a new conversation Single Test Making Multiple Assertions

Hi,

I'm not sure if I'm missing something but whenever I run one or two tests in my test suite they seem to be making multiple assertions despite the test only having one assertion.

Here's an example to illustrate the point. When I include this test I get the output OK (12 tests, 21 assertions If I comment it out however, my output is OK (11 tests, 19 assertions)

/** @test */
    public function a_guest_cannot_view_a_single_book()
    {
        $book = factory('App\Book')->create();
    
        $this->get($book->path())
            ->assertRedirect('/login');
    }

Something seems to be wrong because I only make a single assertion in that test?

Not sure if it's my code or something else, any help would be greatly appreciated

29 Nov
7 months ago

matttonks11 left a reply on Pause Between Jobs In The Queue

Hi there, this thread may be of use

https://laracasts.com/discuss/channels/laravel/delay-between-each-job-queue-worker?page=0

You can use the delay function that queues offer and then do some maths to figure out the delay between each request

Here's the info on delayed dispatching with queues

https://laravel.com/docs/5.7/queues#delayed-dispatching

Hope this helps

05 Nov
8 months ago

matttonks11 left a reply on Decrypting Data In Eloquent Query

@D9705996 Thanks for your help, it works well for what I need

matttonks11 left a reply on Decrypting Data In Eloquent Query

@D9705996 Thanks that may be a better option, I'll check it out

matttonks11 left a reply on Decrypting Data In Eloquent Query

@D9705996 I think the error is something to do with this line maybe

//Model Decrypter.php

$model->setAttribute($attribute, decrypt($model->getAttribute($attribute)));

When I remove the decrypt helper function and run dd(parent::getAttributeValue($key)) i get the data back with encrypted values

In my Encryptable.php file I'm decrypting the data when the getAttribute method runs so I think its trying to decrypt the data twice maybe? Which is leading to the invalid payload error

//Encryptable.php

public function getAttribute($key)
    {
        $value = parent::getAttributeValue($key);

        //dd(parent::getAttributeValue($key));
        
        if (in_array($key, $this->encryptable)) {
            return $value = Crypt::decrypt($value);
        }
        return $value;
    }

matttonks11 left a reply on Decrypting Data In Eloquent Query

I just get the value 2 returned, I'm guessing this is the number of encrypted fields?

matttonks11 left a reply on Decrypting Data In Eloquent Query

@D9705996 thank you, that's worked, now I'm getting an error that says the payload is invalid.

Any thoughts?

matttonks11 left a reply on Decrypting Data In Eloquent Query

@martinbean Hi thank you for this, it looks great. However i'm getting an error on the ->getEncryptable() method, it's saying it doesn't exist.

Call to undefined method App\Client::getEncryptable()

``

Here's my model...

```php

class Client extends Model
{
    use Encryptable;

    protected $encryptable = [
        'email',
        'mobile'
    ];
}

And here's the trait class...

namespace App\Traits;
use Crypt;

trait Encryptable
{
    public function getAttribute($key)
    {
        $value = parent::getAttributeValue($key);

        if (in_array($key, $this->encryptable)) {
            return $value = Crypt::decrypt($value);
        }
        return $value;
    }

    public function setAttribute($key, $value)
    {
        if (in_array($key, $this->encryptable)) {
            $value = Crypt::encrypt($value);
        }

        return parent::setAttribute($key, $value);
    }
}

Not sure what I'm doing wrong, any advice?

matttonks11 started a new conversation Decrypting Data In Eloquent Query

Hello there,

I have some data in my database that I would like to encrypt/decrypt when I make eloquent calls.

I added this encryptable trait from this discussion and it works fine when I use dd(Client::first()->mobile)

https://laracasts.com/discuss/channels/laravel/encrypting-model-data

However I'm trying to pass this data to some DataTables on the front-end using yajra/laravel-datatables package I'm currently passing the whole query, which means the front end is receiving the encrypted values not the decrypted values.

Does anyone know if it is possible to change my eloquent call to get the decrypted values?

Here's my code for passing the data to the front-end

$client = $client->with('groups:id,name')
            ->select('clients.id','clients.forename', 'clients.surname', 'clients.mobile', 'clients.email', 'clients.created_at')->latest();

return datatables()->of( $client )->toJson();

02 Nov
8 months ago

matttonks11 left a reply on View Composer - Undefined Variable

Hi, how is your views folder laid out? it looks like your navigation view is in this path resources/Views/page/includes/navigation.blade.php but your view composer is passing the variable to resources/Views/includes/navigation.blade.php

you could try and change 'includes.navigation' to 'pages.includes.navigation' and see if that works?

14 Oct
9 months ago

matttonks11 left a reply on Laravel Jobs Not Failing

Hi, when you run the queue:work command do you include the --tries option? It specifies the maximum number of times a job should be attempted.

php artisan queue:work --tries=3

If a job fails after 3 times it should appear in the failed_jobs table and non run exhaustively

Here's the link to the docs for more info

https://laravel.com/docs/5.7/queues#dealing-with-failed-jobs

Hope this helps

13 Oct
9 months ago

matttonks11 left a reply on Convert Sql Query

Hi, there's nothing wrong with your query you just need to add ->first() or ->get() on the end to actually get the data like so...

//gets the first user where usuario_ad is danielad
Usuarios::where("usuario_ad","=",'danielad')->first();

//get all the records where usuario_ad  is danielad
Usuarios::where("usuario_ad","=",'danielad')->get();

12 Oct
9 months ago

matttonks11 left a reply on Many To Many Relationships

Update - I found that you can do this by using Client::with('groups:id,name')

matttonks11 started a new conversation Many To Many Relationships

Hi,

I have a many to many relationship set up using Laravels belongsToMany.

class Client extends Model
{
    protected $guarded = [];

    public function groups(){
        return $this->belongsToMany(Group::class)->withTimestamps();
    }
}


What I need is to be able to fetch all of the clients and have a value that contains an array of all the groups they belong to?

But it needs to be in the same query if that makes sense. So i get back all of the clients details as well as an array of groups they belong to

09 Oct
9 months ago

matttonks11 left a reply on Laravel Mail & AttachData()

Okay thank you for the advice

matttonks11 started a new conversation Laravel Mail & AttachData()

Hi,

I'm working on adding attachments to some mail I'm sending and I was wondering how you specify the file name if you don't know the file extension.

For example if I want to allow users to send excel files and pdfs, how would I create the file name based on it's extension? if that makes sense?


    public function build()
    {
        return $this->view('emails.orders.shipped')
                    ->attachData(
                $this->pdf, 
                'name.pdf' // could be one of many file types 
            );
    }

03 Oct
9 months ago

matttonks11 left a reply on Now() Returning Wrong Time

Thank you, works perfectly

matttonks11 started a new conversation Now() Returning Wrong Time

Hi, I've set the timezone and locale values in my php config/app.php file so that when I call the now() function it should return the date and correct time for the UK. However it's currently returning

Carbon @1538563125 {#747 ▼
  date: 2018-10-03 10:38:45.893988 +00:00
}

Which is an hour behind the current time. Am I missing something? how do I fix this?

config/app.php file


/*
    |--------------------------------------------------------------------------
    | Application Timezone
    |--------------------------------------------------------------------------
    |
    | Here you may specify the default timezone for your application, which
    | will be used by the PHP date and date-time functions. We have gone
    | ahead and set this to a sensible default for you out of the box.
    |
    */

    'timezone' => 'GMT',

    /*
    |--------------------------------------------------------------------------
    | Application Locale Configuration
    |--------------------------------------------------------------------------
    |
    | The application locale determines the default locale that will be used
    | by the translation service provider. You are free to set this value
    | to any of the locales which will be supported by the application.
    |
    */

    'locale' => 'uk',
02 Oct
9 months ago

matttonks11 left a reply on Event Stops Working When Added To Queue

Thanks for your suggestion, I've just tried this and it didn't work

matttonks11 started a new conversation Event Stops Working When Added To Queue

Hi I'm currently trying to send a text message after I create a new record the store controller currently looks like this

$newMessage = $message->create([
            'user_id' => auth()->user()->id,
            'mobile' => $request->mobile,
            'title' => $request->title,
            'body' => $request->body,
            'send_at' => $request->send_at
        ]);

        if($newMessage->exists){
            event(new MessageCreated($newMessage));
            Alert::success("Done", "Your message has now been scheduled to be sent");
            return redirect('messages');
        }


My event logic looks like this ...

namespace App\Events;

use App\Message;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class MessageCreated
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(Message $message)
    {
        $this->message = $message;
    }
}

And my listener logic looks like this...


namespace App\Listeners;

use App\Events\MessageCreated;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class SendTextMessage implements ShouldQueue
{
    use InteractsWithQueue;
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        $this->twillio = resolve("Aloha\Twilio\Twilio");
    }

    /**
     * Handle the event.
     *
     * @param  MessageCreated  $event
     * @return void
     */
    public function handle(MessageCreated $event)
    {
        $this->twillio->message($event->message->mobile, $event->message->body);
    }
}

The problem is when I use implements ShouldQueue the job fails and this exception gets stored in the failed jobs table in the database...

ErrorException: Undefined property: App\Events\MessageCreated::$message in C:\xampp\htdocs\inform.ly\app\Listeners\SendTextMessage.php:31
Stack trace:
#0 C:\xampp\htdocs\inform.ly\app\Listeners\SendTextMessage.php(31): Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(8, 'Undefined prope...', 'C:\xampp\htdocs...', 31, Array)
#1 [internal function]: App\Listeners\SendTextMessage->handle(Object(App\Events\MessageCreated))
#2 C:\xampp\htdocs\inform.ly\vendor\laravel\framework\src\Illuminate\Events\CallQueuedListener.php(86): call_user_func_array(Array, Array)
#3 [internal function]: Illuminate\Events\CallQueuedListener->handle(Object(Illuminate\Foundation\Application))
#4 C:\xampp\htdocs\inform.ly\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php(29): call_user_func_array(Array, Array)
#5 C:\xampp\htdocs\inform.ly\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php(87): Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
#6 C:\xampp\htdocs\inform.ly\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php(31): Illuminate\Container\BoundMethod::callBoundMethod(Object(Illuminate\Foundation\Application), Array, Object(Closure))
#7 C:\xampp\htdocs\inform.ly\vendor\laravel\framework\src\Illuminate\Container\Container.php(564): Illuminate\Container\BoundMethod::call(Object(Illuminate\Foundation\Application), Array, Array, NULL)
#8 C:\xampp\htdocs\inform.ly\vendor\laravel\framework\src\Illuminate\Bus\Dispatcher.php(94): Illuminate\Container\Container->call(Array)
#9 C:\xampp\htdocs\inform.ly\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(116): Illuminate\Bus\Dispatcher->Illuminate\Bus\{closure}(Object(Illuminate\Events\CallQueuedListener))
#10 C:\xampp\htdocs\inform.ly\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(104): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Events\CallQueuedListener))
#11 C:\xampp\htdocs\inform.ly\vendor\laravel\framework\src\Illuminate\Bus\Dispatcher.php(98): Illuminate\Pipeline\Pipeline->then(Object(Closure))
#12 C:\xampp\htdocs\inform.ly\vendor\laravel\framework\src\Illuminate\Queue\CallQueuedHandler.php(49): Illuminate\Bus\Dispatcher->dispatchNow(Object(Illuminate\Events\CallQueuedListener), false)
#13 C:\xampp\htdocs\inform.ly\vendor\laravel\framework\src\Illuminate\Queue\Jobs\Job.php(83): Illuminate\Queue\CallQueuedHandler->call(Object(Illuminate\Queue\Jobs\DatabaseJob), Array)
#14 C:\xampp\htdocs\inform.ly\vendor\laravel\framework\src\Illuminate\Queue\Worker.php(327): Illuminate\Queue\Jobs\Job->fire()
#15 C:\xampp\htdocs\inform.ly\vendor\laravel\framework\src\Illuminate\Queue\Worker.php(277): Illuminate\Queue\Worker->process('database', Object(Illuminate\Queue\Jobs\DatabaseJob), Object(Illuminate\Queue\WorkerOptions))
#16 C:\xampp\htdocs\inform.ly\vendor\laravel\framework\src\Illuminate\Queue\Worker.php(118): Illuminate\Queue\Worker->runJob(Object(Illuminate\Queue\Jobs\DatabaseJob), 'database', Object(Illuminate\Queue\WorkerOptions))
#17 C:\xampp\htdocs\inform.ly\vendor\laravel\framework\src\Illuminate\Queue\Console\WorkCommand.php(102): Illuminate\Queue\Worker->daemon('database', 'default', Object(Illuminate\Queue\WorkerOptions))
#18 C:\xampp\htdocs\inform.ly\vendor\laravel\framework\src\Illuminate\Queue\Console\WorkCommand.php(86): Illuminate\Queue\Console\WorkCommand->runWorker('database', 'default')
#19 [internal function]: Illuminate\Queue\Console\WorkCommand->handle()
#20 C:\xampp\htdocs\inform.ly\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php(29): call_user_func_array(Array, Array)
#21 C:\xampp\htdocs\inform.ly\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php(87): Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
#22 C:\xampp\htdocs\inform.ly\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php(31): Illuminate\Container\BoundMethod::callBoundMethod(Object(Illuminate\Foundation\Application), Array, Object(Closure))
#23 C:\xampp\htdocs\inform.ly\vendor\laravel\framework\src\Illuminate\Container\Container.php(564): Illuminate\Container\BoundMethod::call(Object(Illuminate\Foundation\Application), Array, Array, NULL)
#24 C:\xampp\htdocs\inform.ly\vendor\laravel\framework\src\Illuminate\Console\Command.php(183): Illuminate\Container\Container->call(Array)
#25 C:\xampp\htdocs\inform.ly\vendor\symfony\console\Command\Command.php(255): Illuminate\Console\Command->execute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
#26 C:\xampp\htdocs\inform.ly\vendor\laravel\framework\src\Illuminate\Console\Command.php(170): Symfony\Component\Console\Command\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
#27 C:\xampp\htdocs\inform.ly\vendor\symfony\console\Application.php(888): Illuminate\Console\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#28 C:\xampp\htdocs\inform.ly\vendor\symfony\console\Application.php(264): Symfony\Component\Console\Application->doRunCommand(Object(Illuminate\Queue\Console\WorkCommand), Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#29 C:\xampp\htdocs\inform.ly\vendor\symfony\console\Application.php(145): Symfony\Component\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#30 C:\xampp\htdocs\inform.ly\vendor\laravel\framework\src\Illuminate\Console\Application.php(89): Symfony\Component\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#31 C:\xampp\htdocs\inform.ly\vendor\laravel\framework\src\Illuminate\Foundation\Console\Kernel.php(122): Illuminate\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#32 C:\xampp\htdocs\inform.ly\artisan(37): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#33 {main}

However if I don't implement Should Queue the message gets sent

I was wondering if anyone could tell me what's going wrong?

27 Sep
9 months ago

matttonks11 left a reply on Check If Entry Exists

Hi, you could try this...


$recordExists = DB::table('table_name')::where('name', '=', $property->name)->first();

if($recordExists){
    //break
}else{
    //add record
}

25 Sep
9 months ago

matttonks11 left a reply on Eager Loading Nested Relationships

OK I think I've got the wrong end of this when setting up my migrations, and I've set up a category_school link, which I'm now realising should have been a relationship between the asset and the school. Thanks for your help. I'll update what I've got so far to reflect this, and see how I get on. face palm

24 Sep
9 months ago

matttonks11 started a new conversation Form Requests & WithValidator()

Is it possible to use the withValidator method on a form request to change the redirection of the page if the validation fails? This is my current code but it doesn't work


public function withValidator($validator)
    {
        if ($validator->fails()) {
            return Auth::check() ? redirect('admin/dashboard') : redirect('/');
        }
    }
23 Sep
9 months ago

matttonks11 left a reply on Specifying Custom Validation Messages In Language Files

That's great, Thank you for your help

matttonks11 started a new conversation Specifying Custom Validation Messages In Language Files

Hi,

I'm currently customising the validation message for the 'exists' validation condition in the language files. I was wondering if its possible to customise it based on which table the value should exist in...

e.g.

exists:Table1 - custom message

exists:Table2 - different message