drewdan

drewdan

Member Since 6 Months Ago

Newport

PHP Engineer at Talkative Ltd

Experience Points 12,480
Experience Level 3

2,520 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 111
Lessons
Completed
Best Reply Awards 0
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.

07 Jul
1 week ago

drewdan left a reply on Massive Excel File Import Problems

Hello,

Thanks for your reply, my memory usage spikes and the server drops out. And the amount of time that it takes varies, but on my development server, its using well over 2 GB of memory.

I will certainly drop him a tweet. Thank you :)

drewdan started a new conversation Massive Excel File Import Problems

Hi All,

I have some data sheets in excel which I would like to import into a database so they can be used in my Laravel website.

These spreadsheets are about 80mb and have several sheets with over 40,000 rows per sheet.

The objective is to parse these spreadsheets, check the data, and then insert, or update it in the database. These spreadsheets are released a few times a year, which is why I am looking for a system which can parse them nicely whenever one is uploaded.

I am using the https://github.com/Maatwebsite/Laravel-Excel plugin to open and parse the file, and I am performing this as a job, so it can be run in the background, however, it always seems to hang after a while and give up.

I was wondering what you guys thought, and what approach you might take to parse this data?

I am looking forward to hearing your thoughts :)

Andrew

drewdan left a reply on Undefined Variable: Data (View: Resources\views\adminhome.blade.php)

Try doing a dd() on the $data variable to see if its actually returning anything. If its not, that could be causing the error

26 Jun
2 weeks ago

drewdan started a new conversation IP Address For Content Delivery With Load Balancing

Hello All,

I have been asked to investigate an issue with load balancing. Currently we post data to our clients with a post method to their server. Our request to their server is validated by several methods, but the one that I am looking into is the IP address the request comes from. Our clients validate the data comes from us by checking the IP address it is being sent from.

We currently host our website on a VPS with a static IP address. However if we go to a scalable load balancing solution, the IP address these requests come from will vary.

So I think the answer is a reverse proxy, so the requests are routed via the reverse proxy, but how does that work? Do we spin up a server which acts exclusively as a Reverse proxy, or can this be achieved through PHP?

I am a little out of my depth, so any advice would be fantastic.

Cheers Guys

04 Jun
1 month ago

drewdan left a reply on Redirect In A Try Catch

@SIANGBOON - I tried that, any form of redirect it seems will fail to be called.

drewdan started a new conversation Redirect In A Try Catch

Hey Guys, I have a try catch in my code

try {
            $response = $this->client->get('https://api.insight.ly/v2.2/permissions', [
                'headers' => [
                    'Authorization' => 'Basic '.base64_encode($request->get('key')),
                    'Content-Type' => 'application/json',
                ],
            ]);
        } catch (ClientException $e) {
            //catch the response code and store it within a variable
            $response = $e->getResponse()->getStatusCode();
            switch ($response) {
                case 400:
                    abort(400, 'You are missing some data. Please try again.');
                    break;
                case 401:
                    abort(400, 'Authentication failed. Your key may be incorrect or invalid');
                    break;
                case 403:
                    abort(400, 'API Key User does not have access to this organisation');
                    break;
                case 404:
                    abort(400, 'This organisation has not been found');
                    break;
                default:
                    abort(500);
                    break;
            }
        }

depending upon the error, I kick out an error page. However, I dont actually want to do this. I want to redirect the user back to the page they were on before with an error message, but when I use:

return redirect()->back()

nothing happens. The code is ignored and the script continues to run.

Any ideas?

Cheers!

03 Jun
1 month ago

drewdan started a new conversation Testing Guzzle Api Call

Hi All,

I am trying to do a feature test which will validate that a user can pass data to insightly CRM. However, I of course only want to mock this, and not ping Insightly everytime I run the script.

I figured I had to mock the client, pass this into the service container and I could then run my feature test, however, every time I do, it still hits the Insightly server.

/** @test */
    public function testStoreInsightly() {
        $client = $this->createMockClient(200, json_encode(['status' => 200]));
        $this->app->bind(Client::class, $client);
        dd($client);


        $params = [
            '[email protected]' => [
            'method' => 'post',
            'route' => '/crms',
            'responseCode' => 302,
            'assertData' => '',
            'affectedTable' => '',
            'testData' => [
                    'crm' => 'insightly',
                    'key' => '0a71976b-bcb2-b8bd-221a-0cea63510721',
                ],
            ],
        ];
        $response = $this->featureTest($params);
    }

    public function createMockClient($status = 200, $body = '') {
        $mock = new MockHandler([
            new Response($status, [], $body),
        ]);
        $stack = HandlerStack::create($mock);
        return new Client(['handler' => $stack]);
    }

that is my test.

The feature test function it calls to run the test is:

protected function featureTest($testParams) {
        foreach ($testParams as $user => $params) {
            foreach ($params as $key => $param) {
                $$key = $param;
            }

            $this->signIn($user);
            $response = $this->$method($route, $testData);

            if ($assertData === true) {
                $this->assertDatabaseHas($affectedTable, $testData);
            } elseif ($assertData === false) {
                $this->assertDatabaseMissing($affectedTable, $testData);
            }
            $response->assertStatus($responseCode);
            //return($response);
        }
    }

I am unsure as to how to get this work. I thought mocking the Guzzle client would be it, but every time I get a response from the server.

Any advice or tips would be great!

17 May
1 month ago

drewdan left a reply on Test Starts Before Seeding Finishes

So I believe the issue was to do with me not specifying which database to seed. So the test database never got seeded. So the tests failed. However, from a performance stand point, because of the sheer amount of data that needs to be seeded. It became more practical to create a file based sqlite database and then seed that first, and then run all of the tests on that using db transactions.

Cheers for all of your assistance. As always, you are fantastic :)

10 May
2 months ago

drewdan left a reply on Multiple Relations On An Eloquent Model

@HONDNL - Sorry for the epic delay. Havent worked on this project in a while. Thank you for the pointer in the right direction. I got it working and it was much simpler than I thought!

Much appreciated!

09 May
2 months ago

drewdan started a new conversation Test Starts Before Seeding Finishes

Hey Guys,

How does seeding in tests work?

protected function setUp() {
        parent::setUp();
        $this->artisan('migrate');
        (new \DatabaseSeeder())->call(\DatabaseSeeder::class);
    }

I have this in my parent TestClass which migrates and seeds the db before every test. But the echo output always appears after the tests have finished. Does this mean the seeding hasnt finished before the test starts to run. Coincidentally the tests fail because my account doesnt have the right permissions, which is what the seeding is for.

Cheers for your help.

Andrew

drewdan left a reply on SQLite In Memory For PHPUnit Testing

I like the in memory idea, so I think I will stick with this approach. Just need to work out why all my tests keep failing authorisation now!

Cheers for the information :D

drewdan started a new conversation SQLite In Memory For PHPUnit Testing

Hi All,

I am working on optimising our unit tests, we are currently using a MySQL database to run our tests, and it takes quite a great deal of time and we only have currently about 20% code coverage.

Our plan was to use an SQLite database held in memory to speed up the performance. However, with every test, I need to migrate and seed the data. The seeding is slowing the process down considerably.

Can I migrate and seed the data once before the tests start, and then run all of my tests, or is it pretty standard to do the testing in this manner? I appreciate every test in isolation with the same start data is the best way to do it, but we are looking to balance our performance too.

Any thoughts and tips would be great.

Thanks

03 May
2 months ago

drewdan left a reply on Unable To Find Observer After Update To 5.8

@DKROFT - I didnt consider this, thanks for the reply. I will take a look!

29 Apr
2 months ago

drewdan started a new conversation Multiple Relations On An Eloquent Model

Hi Guys,

I am a little stuck on declaring this Model.

So I have a vehicle table, and in that table is a "makeID" and a "modelID". These fields relate to these two tables

Schema::create('vehicle_makes', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->timestamps();
        });
Schema::create('vehicle_models', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedInteger('make_id');
            $table->string('name');
            $table->timestamps();
        });

So, to access the make in the blade template I have the relationship

public function vehicleMake() {
        return $this->hasOne(VehicleMake::class, 'id', 'makeID');
    }

But I need to return the vehicle model too, but thats not just a relationship, but also requires an ID input to narrow it down to the correct one.

So do I need a has many relationship and then narrow it down, or, well. I am drawing a blank :(

Any tips would be great.

I had thought just pulling the make model into the vehicle stock model and performing a lookup using a where. Would that be best? Any tips would be fab :)

Thanks All. As always, your're awesome!

28 Apr
2 months ago

drewdan left a reply on Validation On Null With Vue And Laravel

@BOBBYBOUWMANN - Yes that worked a treat, thank you very much :D

drewdan left a reply on Validation On Null With Vue And Laravel

So if I use nullable it should be ok?

I couldn't figure out how to stop passing references back if the user didn't complete them on the Vue form. I will give this a go now.

Thank you for your reply :)

drewdan started a new conversation Validation On Null With Vue And Laravel

Hi All,

I have the following vue script, this is the relevant JS section

<script>
    import Datepicker from 'vuejs-datepicker';
    
        class Errors {

            
        }

    export default {

        components: {
            Datepicker
        },

        data: function() {
         return {
            vehicleMake: [],
            modelData: [],
            makeID: 1,
            modelID: 1,
            registrationPlate: null,
            vehicleRegistrationDate: null,
            variant: '',
            colourID: '',
            mileage: '',
            fuelTypeID: '',
            warranty: null,
            transmissionSpeed: '',
            transmission: '',
            purchasePrice: '',
            salePrice: '',
            specialPrice: '',
            bodyStyle: '',
            engineSize: '',
            doors: '',
            vat: '',
            reference: null,
            primaryImage: null,
            vehicleOptions: new Array(),
            errors: new Errors(),
            formData: '',
            }
        },

        created() {
            this.updateMake();
            this.updateModel(1);
        },

        methods: {
        updateModel(event) {
            this.modelData = [];
            axios.post('/vehicle/getModel', {
            id: this.makeID,
          })
            .then(response => {
                this.modelData = response.data
                this.modelID = response.data[0].id;
            });
           // .then(response => this.modelData = response.data);


        },

        updateMake() {
            axios.post('/vehicle/getMake', {
          })
            .then(response => this.vehicleMake = response.data);

        },

        onSubmit() {
            

            axios.post('/admin/vehicle', this.$data)

            .then(response => alert(response))

            .catch(error =>  this.errors = error.response.data);
        }
        
        }

    }
</script>

so I have all of my data bound to a form, and on submit it gets passed via axious to my laravel application. To where I validate the data:

 $vehicle = request()->validate([
            'registrationPlate' => 'required|alpha_num', //required
            'vehicleRegistrationDate' => 'date', 
            'makeID' => 'required|numeric', //required
            'modelID' => 'required|numeric', //required
            'variant' => 'sometimes|string',
            'colourID' => 'required|numeric', //required
            'mileage' => 'sometimes|numeric',
            'fuelTypeID' => 'required|numeric', //required
           'warranty' => 'sometimes|numeric',
            'transmissionSpeed' => 'sometimes|numeric', 
            'transmission' => 'required|numeric', //required
            'purchasePrice' => 'sometimes|numeric',
            'salePrice' => 'required|numeric', //required
            'specialPrice' => 'sometimes|numeric',
            'bodyStyle' => 'sometimes|numeric',
            'engineSize' => 'sometimes|numeric',
            'doors' => 'sometimes|numeric',
            'vat' => 'required|numeric',
            'reference' => 'sometimes|alpha_num',
            'primaryImage' => 'sometimes|image',            
        ]);

The problem I am encountering is that the validation on sometimes gets called because Axios is still posting an empty data object back, so for example, if the user did not enter a reference on the form, I would expect the validation to pass due to the sometimes directive, but it fails because the entry is empty and obiously not alpha numeric.

Any pointers to resolve this would be great. Thank you :)

25 Apr
2 months ago

drewdan left a reply on Want To Implement Payment Gateway Into The Api .

Would be really good if you refactored your code a little to make it more readable. And maybe considered using a library like Guzzle to interact with your API.

I cannot see where you are pulling your model in or saving the data to the database. Is that somewhere else?

drewdan left a reply on Disable CSRF In Tests

I placed

\Session::start();

inside my setUp() function

and then passed the

'_token' => csrf_token()

in my response object to the controller. It worked a treat.

Thank you

drewdan started a new conversation Disable CSRF In Tests

I am having a problem with my code where I am running a test as follows:

$this->withoutExceptionHandling();

        $this->withoutMiddleware(VerifyCsrfToken::class);

        $user = $this->getUser('[email protected]');

        $this->actingAs($user);

        $hexColour = $this->faker->hexcolor();

        $company = $this->companyModel->find(2);
        //try to access a company which does not belong to the admin
        \Storage::fake(); 

        $response = $this->patch('/companies/2/', [
            'emailCustomisation' => [
                'logo' => UploadedFile::fake()->image('avatar.jpg'),
                'color' => $hexColour,
            ],
            'company' => [
                'label' => 'foo',
                'name' => $company->name,
                'home_page' => $company->home_page,
                'phone_number' => $company->phone_number,
                'timezone' => $company->timezone
            ]
        ]);

        $response->assertStatus(419);

        \Storage::assertExists('avatar.jpg');

And I am getting a token mismatch error.

Can I disable CSRF middleware without removing any other? Or is there a way to inject a CSRF token?

drewdan left a reply on Faking A File Upload

@DEVFREY - Thank you for your feedback. Unit vs Feature testing is an ongoing debate in my office, so we are writing tests from both approaches to see which has the best outcome. I think I would be eager to agree with you at this point. Is there a way around my issue performing a Unit Test, or is it something of a dead end?

drewdan left a reply on Faking A File Upload

@DEVFREY - ``` $company = $this->companyModel->find(1);

    $hexColour = $this->faker->hexcolor();

    $request = new \Illuminate\Http\Request;

    $requestData = [
        'company' => [
            'label' => 'foo',
            'name' => $company->name,
            'home_page' => $company->home_page,
            'phone_number' => $company->phone_number,
            'timezone' => $company->timezone
        ], 
        'emailCustomisation' => [
            'logo' => UploadedFile::fake()->image('avatar.jpg'),
            'color' => $hexColour
        ] 
    ];

    $request->merge($requestData);

    $response = $this->controller->update($request, $company);

sorry, I should have put that in from the outset! Thanks for reviewing my code :D

drewdan started a new conversation Faking A File Upload

Hi All,

Im having a few issues with faking an image upload.

In my controller I have the following

if (isset($data['emailCustomisation'])) {
$emailCustomisation = new EmailCustomisation();     
$emailCustomisation->logo = $request
                ->file('emailCustomisation.logo')
                ->store('logos', config('filesystems.cloud'));
$emailCustomisation->company_id = $company->id;
$emailCustomisation->color = $data['emailCustomisation']['color'];
$emailCustomisation->save();

This is the test that I run on the controller, but it always fails

$requestData = [
            'company' => [
                'label' => 'foo',
                'name' => $company->name,
                'home_page' => $company->home_page,
                'phone_number' => $company->phone_number,
                'timezone' => $company->timezone
            ], 
            'emailCustomisation' => [
                'logo' => UploadedFile::fake()->image('avatar.jpg'),
                'color' => $hexColour
            ] 
        ];

It is failing with the error:

Error: Call to a member function store() on null

Does anyone know what may be causing this?

Thanks :)

24 Apr
2 months ago

drewdan left a reply on Laravel 5.5 Queue Redis

What environment is your application running on?

drewdan left a reply on How To Post Or Publish Content On Linkedin Profile After Click On Button Using Laravel

What content? Whats the problem?

Please give some more specifics of what your problem is. Does your application not work or are you just looking for someone to write code for you?

If you want to push data to LinkedIn you will need to utlilise their API and probably pull in a library like guzzle to handle the request for you. https://github.com/guzzle/guzzle https://packagist.org/packages/linkedinapi/linkedin

Pull these two packages into your application and follow the user docs to achieve what you want to achieve.

drewdan left a reply on Dynamic Time With Carbon

What are you actually trying to do? I presume your $date is being passed in with data from a database or similar?

Are you trying to calculate the length of time the resturant is open?

23 Apr
2 months ago

drewdan left a reply on Email Validation Passes When It Should Fail

@TYKUS - I did not consider it like that. I suppose Laravel could be used on an internal network as a Intranet, and then such emails would become useful. Thank you for your prompt answer!

drewdan started a new conversation Email Validation Passes When It Should Fail

I have some unit tests on my project which test emails to make sure emails that should not pass validation do not and so on. However, using Laravels validation tool, I am having a problem that "[email protected]" is passing validation. Does anyone know why this is? Surely as its missing a tld it should not pass.

Any insight into this issue would be amazing! Thanks Guys :)

drewdan left a reply on Tinker Not Working

It does sound like the package has become corrupt so I would do as Vandan says and try to refresh your vendor packages. Does it happen on all of your laravel instances, or just this one?

22 Apr
2 months ago

drewdan left a reply on This Is Undefined

Thank you, this worked a treat, I thought the arrow function was the wrong one, so avoided using it. Seems I was wrong. Thank you for your help!

drewdan started a new conversation This Is Undefined

Hi All,

I am trying to learn Vue, I have a little experience with it, but not a great deal. I have been following some of the tutorials on Laracasts and have hit a problem. This is my code.

const app = new Vue({
    el: '#app',
    components: {
        Datepicker
    },
    data: {
        vehicleModel: ''
    },

    methods: {
        updateModel: function() {
            axios.post('/vehicle/getModel', {
            id: 1,
          })
          .then(function (response) {
            this.vehicleModel = response.data;
          })
          .catch(function (error) {
            console.log(error);
          });
        }
    },
    created() {     
        this.vehicleModel = 'foo';
    }
});

import Datepicker from 'vuejs-datepicker';

My issue is that this. is undefined. However, following a Laracast video and this method seems to work, so I am at a loss at to where I am going wrong.

this.vehicleModel = response.data;

is where it is all falling down. Is there a different way I should be trying to access the data?

17 Apr
2 months ago

drewdan left a reply on Unable To Find Observer After Update To 5.8

@FTIERSCH - Sorry, It turns out that this observer no longer exists. It was dropped in a previous commit, but managed to not cause any errors until the update. Somewhat perplexing

drewdan left a reply on Unable To Find Observer After Update To 5.8

I am really not sure as to why this suddenly became an issue in 5.8. The GroupObserver was dropped in a previous version of the software. Its only just caused the system to fail after the composer update.

drewdan started a new conversation Unable To Find Observer After Update To 5.8

Hello All,

I have just updated my Distro to Laravel 5.8 and I hit an error during the composer update.

Unable to find observer: App\Providers\GroupObserver

Does anyone have any insight into what might cause this?

15 Apr
3 months ago

drewdan left a reply on SQL Query With ANDs ORs

It transpires that this cannot easily be done without somehow putting a load of joins in the search, but that gets pretty messy because they are lots of one to many joins.

For reference though, the query was being built up like this:

/**
     * Filter interactions by message content
     *
     * @param  string $daterange
     * @return Illuminate\Database\Eloquent\Builder
     */
    public function message($val)
    {
        $this->orWhereHas('messages', function ($query) use ($val) {
             return $query->where('message', 'LIKE', '%' . $val . '%');
        });
    }
    /**
     * Filter interactions by data content
     *
     * @param  string $daterange
     * @return Illuminate\Database\Eloquent\Builder
     */
    public function interactionData($val)
    {
        $this->orWhereHas('interactionData', function ($query) use ($val) {
            return $query->where('data', 'LIKE', '%' . $val . '%');
        });
    }

In the end we changed the system to have a general search and then a filter area instead.

11 Apr
3 months ago

drewdan started a new conversation SQL Query With ANDs ORs

Hi All,

I am using the Eloquent Filter to filter my database query, however, I have been asked to add a search field which will search values between multiple columns and tables.

The problem I am getting is that I have had to use or operators to query between the different tables as we dont neccesarily know which field needs to be searched, so we have to search them all with the same data and return whichever matches.

But, we also filter by the top table by date, and some other status flags.

This is the query that gets generated by Eloquent Filter

select * from `interactions` where (`company_id` = 2 or exists (select * from `messages` where `interactions`.`id` = `messages`.`interaction_id` and `message` LIKE '%dolor%') or exists (select * from `interaction_data` where `interactions`.`id` = `interaction_data`.`interaction_id` and `data` LIKE '%dolor%') or exists (select * from `users` where `interactions`.`user_id` = `users`.`id` and (`first_name` in ('dolor') or `last_name` in ('dolor')) and `users`.`deleted_at` is null) and `created_at` between '2019-04-01 00:04:00' and '2019-04-11 09:04:00') order by `created_at` desc limit 20 offset 0

However, this returns the data that matches the or statements, but ignored the created_at search.

So, I played around with the SQL in the workbench, and the only way I can see to get this working properly is like so:

select * from `interactions`
where exists (
    select * from `messages` 
    where `interactions`.`id` = `messages`.`interaction_id`
    and `message` LIKE '%dolor%'
    AND (`interactions`.`company_id` = 2 and `interactions`.`created_at` between '2019-04-01 00:04:00' and '2019-04-11 09:04:00' )
) 
OR exists (
    select * from `interaction_data` 
    where `interactions`.`id` = `interaction_data`.`interaction_id` 
    and `data` LIKE '%dolor%'
    AND (`interactions`.`company_id` = 2 and `interactions`.`created_at` between '2019-04-01 00:04:00' and '2019-04-11 09:04:00' )
) 
OR exists (
    select * from `users` 
    where `interactions`.`user_id` = `users`.`id` 
    and (`first_name` in ('dolor') or `last_name` in ('dolor')) 
    and `users`.`deleted_at` is null
    AND (`interactions`.`company_id` = 2 and `interactions`.`created_at` between '2019-04-01 00:04:00' and '2019-04-11 09:04:00' )
)
AND (`company_id` = 2 and `created_at` between '2019-04-01 00:04:00' and '2019-04-11 09:04:00' )

order by `created_at` desc limit 20 offset 0

which is essentially injecting into every or query.

Is there a better way to do this query?

10 Apr
3 months ago

drewdan left a reply on Eloquentfilter Multiple Tables

I found a solution to my issue:

$this->whereHas('messages', function ($query) use ($val) {
            return $query->where('message', 'LIKE', '%' . $val . '%');
        });

        //orwherehas changes the filter so it use or exists instead of and exists
        $this->orWhereHas('interactionData', function ($query) use ($val) {
            return $query->where('data', 'LIKE', '%' . $val . '%');
        });

replaces the "and exists" to "or exists" where orWhereHas is used

09 Apr
3 months ago

drewdan left a reply on Eloquentfilter Multiple Tables

So, I have expanded the code to include the following:

    public function search($val)
    {           
        $this->related('messages', 'message', 'LIKE', '%' . $val . '%');
        $this->related('interactionData', 'data', 'LIKE', '%' . $val . '%');

        return $this;
    }

This almost works, but in the SQL thats generated its showing me "and exists" in the query, I need to have it as OR rather than and. Anyone know how to achieve this?

drewdan started a new conversation Eloquentfilter Multiple Tables

Hello,

I am working a project using the Eloquent Filter library.

I can filter by single fields, but I have a field in my filter form which needs to search multiple tables.

How can I do this?

    public function search($val)
    {   
        return $this->related('messages', 'message', 'LIKE', "%$val%");

    }

This is what I currently have, but I need to also check if $val is present in another table.

I cannot find any documentation about this, so any help would be great thank you.

Drewdan

14 Mar
4 months ago

drewdan left a reply on Laravel Mail Log Not Working

So, I figured out the problem. Well I think so anyway.

I was encoding a rather large image directly into the email. I guess that was too large for the telescope database and the query kept failing. Once I dropped the image, it continued to work correctly.

drewdan started a new conversation Laravel Mail Log Not Working

I send an email in my code:

Mail::to(request()->email, request()->forename . " " . request()->surname)->send(
            new IntroductionEmail($contactAttributes)

I set the driver to log, so I could review the email in telescope which was working fine, however I upgraded to laravel 5.8 and also ran the vendor:publish command and for some reason, the email no longer gets written to the log. If I use a traditional SMTP server, the mail goes fine, but shows no record of it in Telescope.

Can anyone shed some light on this? I had a search on Google but could not find any answers, unless I just don't know how to work the question properly of course!

Thanks all!

02 Mar
4 months ago

drewdan left a reply on Route Orders Causing Confliction?

Ah that would make sense, so in the edit resource on the admin controller, it would be trying to load the resource with the key "product" right, yet that makes a lot more sense!

Thank you for the suggestion about the admin prefix, I will have a good read over the documentation now.

Thanks again :)

drewdan started a new conversation Route Orders Causing Confliction?

Hi Guys,

Just looking for some clarification on my web routes.

So I had:

Route::resource('/admin', 'AdminController');
Route::resource('/admin/product/import', 'ProductImport');
Route::resource('/admin/products', 'Admin\Products');

Which did not work, I just got a white screen with no errors.

However, buy reordering the routes too:

Route::resource('/admin/products', 'Admin\Products');
Route::resource('/admin', 'AdminController');
Route::resource('/admin/product/import', 'ProductImport');

It works fine, the correct controllers are loaded and everything is lovely, which is good. But I would like to understand why. There are no conflicting routes, or conflicting Controllers.

If anyone could enlighten me, I would be very grateful!

Cheers, Andrew

22 Jan
5 months ago

drewdan left a reply on How To Get Form Data Within A Form

Hello Rodrigo,

Thank you very much for your quick and detailed response. This has been most heplful and has worked perfectly.

I see what you mean about having the event handler on the form, in future I will adopt this method.

This has been really helpful, thank you again, I am extremely grateful.

Andrew :D

drewdan started a new conversation How To Get Form Data Within A Form

Hi All, I am struggling with Vue, I am very new to it and trying to make a component that will check to see if a domain is available to be registered, and if it is, allow the user to add it to their basket.

So far, I have managed to do an ajax call to get the list of available domains, and then output this into a table, however, each table has a nested form which will contain the domain name to register, including the top level domain. Initially these were all forms using hidden inputs to carry the data to the server side, however, I am stuck at this point, as I cannot correctly set or retrieve this data. Can anyone help please?

    <div class="card mb-4 box-shadow">
    <div class="card-header">
        <h4 class="my-0 font-weight-normal">Domain Search</h4>
    </div>
        <div class="card-body">
            <form action="/portal/domains/registerDomain" method="post">  
                <div class="form-group">
                <label for="domainName">Domain Name:</label>
                <input type="text" class="form-control" name="domainName" placeholder="www.domain.com" v-model="domainName">
                <small id="emailHelp" class="form-text text-muted">Enter the domain name you wish to search</small>
                </div>
                <button class="btn btn-lg btn-block btn-primary" type="submit" @click.prevent="search">Search Domain</button>
            </form>
<div class="table-responsive" v-if="domainList">
    <table class="table table-striped">
    <tbody>
        <tr v-for="data in domainList">
        
        <td class="text-left" style="width:60%;">www.{{data.domainName}}</td>
        
        

        <td v-if="data.isAvailable === 'yes'">&nbsp;</td>
        <td v-else class="align-middle text-center" style="width:20%;"><a target="_blank" v-bind:href="'http://'+ data.domainName">Visit Website</a></td>

        <td v-if="data.isAvailable === 'yes'" class="align-middle text-center" style="width:20%;">
        <form action="/portal/domains/registerDomain/addToBasket" method="post">     
            <input type="hidden" name="domainName" v-model="data.domainName" >
            <input type="hidden" name="topLevel" v-model="data.topLevel" >
            <button class="btn btn-primary w-100" @click.prevent="addToBasket">Add To Basket £{{((data.domainPrice)/100).toFixed(2)}}</button>
        </form>
        </td>   
        <td v-else>
            <button class="btn btn-primary w-100" disabled>Not Available</button>
        </td>               
        
        </tr>  
    </tbody>
    </table>
</div>
        </div>
    </div>

</template>

<script>
    export default {
        data() {

            return {
                domainName: '',
                domainList: [],
                domainTopLevel: [],
                domainToRegister: []
            }
            
        },
        mounted() {
            console.log('Component mounted.')
        },

        methods: {
            search() {
                axios.post('/portal/domains/registerDomain', this.$data)
                    .then(response => this.domainList = response.data);
            },

            addToBasket() {
                axios.post('/portal/domains/registerDomain/addToBasket', this.$data)
                    .then(response => alert("Done"));
            }
        }
    }
</script>
18 Jan
5 months ago

drewdan left a reply on Check Domain Name Is Formed Correctly

Superb, thank you very much, this will do. I thought Regex may be the solution, but wasnt sure if there was anything better. Thank you for your response. :D

drewdan started a new conversation Check Domain Name Is Formed Correctly

Hey Guys. I am hoping you can help me.

I need a function to validate that a domain name is in fact a domain name.

However, it cannot get the A record as this may be a domain name which isnt configured yet, all it needs to check is that the domain name is not malformed. So the domain is something.co.uk or something.com - can anyone point me in the right direction to check this?

I have been Googling it but there seems to be so much info that contradicts each other, im a little confused!