Buy your loved one the ultimate gift. Lifetime gift certificates are $100 off.

haakym

Experience

29,690

2 Best Reply Awards

  • Member Since 3 Years Ago
  • 407 Lessons Completed
  • 2 Favorites

14th December, 2017

haakym left a reply on How Can I Convert This Sublime Text Snippet To VS Code? • 3 days ago

Each line in the snippet gets its own element in the body array:

Ahhh, gotcha!

I don't believe regex is supported however

: (

Maybe I'll raise it on the vscode git repo?

Thanks for your reply @tykus

haakym started a new conversation How Can I Convert This Sublime Text Snippet To VS Code? • 3 days ago

I have been using this awesome Sublime snippet (below) for creating new PHPUnit functions for some time now and haven't found anything to replace it in VS Code.

<snippet>
    <content><![CDATA[
/** @test */
public function ${1/\s/_/g}()
{
    ${0:// ${1:type name of method with spaces}}
}
]]></content>
    <!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
    <tabTrigger>test</tabTrigger>
    <!-- Optional: Set a scope to limit where the snippet will trigger -->
    <scope>source.php</scope>
</snippet>

I used this converter: https://www.npmjs.com/package/convert-snippets-to-vscode to produce the following:

{
    "test": {
        "prefix": "test",
        "body": "\r\n/** @test */\r\npublic function ${1/\s/_/g}()\r\n{\r\n    ${0:// ${1:type name of method with spaces}}\r\n}\r\n",
        "description": ""
    }
}

However, it didn't work.

Any idea how I can get this working in VS Code? Any help would be appreciated!

13th November, 2017

haakym left a reply on Having Condition In A Laravel Eloquent Query. • 1 month ago

@eddy1992 sortBy() is for collections whereas orderBy() is for DB interactions, so you will use it with Eloquent or the DB query builder.

https://laravel.com/docs/5.5/collections#method-sortby

https://laravel.com/docs/5.5/queries#ordering-grouping-limit-and-offset

2nd November, 2017

haakym left a reply on Log In A User Test, Failed Login Redirects To `/` Instead Of Back To `/login`? • 1 month ago

session()->setPreviousUrl('login')

did the trick!

haakym started a new conversation Log In A User Test, Failed Login Redirects To `/` Instead Of Back To `/login`? • 1 month ago

I've written the following test to check incorrect credentials do not log a user in.

/** @test */
public function logging_in_with_invalid_credentials()
{
    $user = factory(User::class)->states('verified')->create([
        'email' => '[email protected]',
        'password' => bcrypt('123456'),
    ]);

    $response = $this->post('/login', [
        'email' => '[email protected]',
        'password' => 'wrong-password',
    ]);

    $response->assertRedirect('/login');
}

However, when running the test it fails because it redirects to home / instead of back to /login.

PHPUnit 6.4.3 by Sebastian Bergmann and contributors.

F                                                                   1 / 1 (100%)

Time: 761 ms, Memory: 18.00MB

There was 1 failure:

1) Tests\Feature\LoginTest::logging_in_with_invalid_credentials
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'http://localhost/login'
+'http://localhost'

C:\laragon\www\attestation\vendor\laravel\framework\src\Illuminate\Foundation\Testing\TestResponse.php:96
C:\laragon\www\attestation\tests\Feature\Auth\LoginTest.php:55

Any idea why this is happening? When I run the code through my browser it works as expected which I find odd.

When looking at the ValidationException which is handled by the exception handler and the invalid() method on the Illuminate\Foundation\Exceptions\Handler class which decides the URL, url()->previous() returns http://localhost.

protected function invalid($request, ValidationException $exception)
{
    $url = $exception->redirectTo ?? url()->previous();

    return redirect($url)
            ->withInput($request->except($this->dontFlash))
            ->withErrors(
                $exception->errors(),
                $exception->errorBag
            );
}

I would have thought /login would have been the previous URL?

Any help here would be appreciated.

1st November, 2017

haakym left a reply on Laravel Frequently Showing 'Undefined Variable: _SERVER' • 1 month ago

If it's happening in Laravel and MySql may be an issue with your apache setup, have you modified it at all lately?

This link may have the answer for you:

https://odd.blog/2015/02/12/php-notice-undefined-variable-_server-in/

haakym left a reply on Refactoring A Test For User Registration • 1 month ago

@Talinon Thanks so much for your suggestions!

Annoyingly I can't reduce the request body so much because half of it is required for the form validation rules and isn't part of the user's attributes (of course I didn't expect you to know that or anything).

In any case, it was definitely a move in the right direction as I have swapped out some unnecessary code including the eloquent call by utilising the $user that I created (or make()'d) with the factory.

Right now I've got it looking like this...

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

    $this->seedDatabase(); // seeds the database with roles which are assigned on user creation
}

/** @test */
public function a_user_can_register()
{
    Mail::fake();

    NoCaptcha::shouldReceive('verifyResponse')
        ->once()
        ->andReturn(true);

    $user = factory(App\Models\User::class)->states('non-verified')->make();

    $response = $this->json('POST', '/register', 
        array_merge($user->toArray(), [
            'account_type' => 'personal',
            'password' => '123456',
            'password_confirmation' => '123456',
            'g-recaptcha-response' => '1',
        ])
    );

    $response->assertRedirect('/auth/verification/sent');

    $this->assertDatabaseHas('users', 
        array_merge($user->toArray(), [
            'verified' => 0,
        ])
    );

    Mail::assertSent(VerificationTokenGenerated::class, function ($mail) use ($user) {
        return $mail->hasTo($user->email);
    });
}

I'm still playing with the idea of abstracting the arrange and act parts into a single method then separating the assertions into their own methods. I'm trying to reach a place where it seems more readable which is why I've kept the act step (the POST request) assigned to the $response variable as I find it easier to read as I've already got the array merge going on inside the request body which honestly I don't like that much but I'll just leave it as it is for now and see if I get any fresh perspective later. Perhaps I'll separate the request body build up into its own variable so it's easier to reason about? Something like ...

$data = array_merge($user->toArray(), [
        'account_type' => 'personal',
        'password' => '123456',
        'password_confirmation' => '123456',
        'g-recaptcha-response' => '1',
    ]);

$response = $this->json('POST', '/register', $data);

31st October, 2017

haakym started a new conversation Refactoring A Test For User Registration • 1 month ago

I've written a test to check a user can register. The main outcomes of the registration are that a new user is in the database and is sent an email requesting they verify their registration. The test seemed a bit long to me and I thought I'd get some second opinions here on the forum with how I might refactor it. Here's the code:

/** @test */
public function a_user_can_register()
{
    $this->seedDatabase(); // seeds the database with roles which are assigned on user creation

    Mail::fake();

    NoCaptcha::shouldReceive('verifyResponse')
        ->once()
        ->andReturn(true);

    $response = $this->json('POST', '/register', [
        'name' => 'John Doe',
        'email' => '[email protected]',
        'contact_number' => '12345678',
        'account_type' => 'personal',
        'password' => '123456',
        'password_confirmation' => '123456',
        'g-recaptcha-response' => '1',
    ]);

    $response->assertRedirect('/auth/verification/sent');

    $this->assertDatabaseHas('users', [
        'name' => 'John Doe',
        'email' => '[email protected]',
        'contact_number' => '12345678',
        'verified' => 0,
    ]);

    $user = User::whereEmail('[email protected]')->first();

    Mail::assertSent(VerificationTokenGenerated::class, function ($mail) use ($user) {
        return $mail->hasTo($user->email);
    });
}

Would I be better of splitting each assertion into its own method and moving the actions that are used prior to the assertions into private methods or and the constructor?

30th October, 2017

haakym left a reply on Writing Test With Form That Uses No-captcha • 1 month ago

I got it working after modifying the POST data to include the g-recaptcha-response with a value of 1, as follows:

$response = $this->json('POST', '/register', [
    'name' => 'John Doe',
    'email' => '[email protected]',
    'contact_number' => '12345678',
    'account_type' => 'personal',
    'password' => '123456',
    'password_confirmation' => '123456',
    'g-recaptcha-response' => '1',
]);

haakym started a new conversation Writing Test With Form That Uses No-captcha • 1 month ago

I am writing a test for when a user registers. The registration form has a no-captcha field to prevent bots. I am using the following package to enable the no-captcha functionality: https://github.com/anhskohbo/no-captcha

There are some instructions on the readme with how to use the package when writing tests in Laravel, see here: https://github.com/anhskohbo/no-captcha#testing. However, I'm still running into issues so if anyone could help with writing the tests I would be grateful.

Here's my code...

RegistrationTest.php

/** @test */
public function a_user_can_register()
{
    // prevent validation error on captcha
    NoCaptcha::shouldReceive('verifyResponse')
        ->once()
        ->andReturn(true);

    // provide hidden input for your 'required' validation
    NoCaptcha::shouldReceive('display')
        ->zeroOrMoreTimes()
        ->andReturn('<input type="hidden" name="g-recaptcha-response" value="1" />');
    
    $response = $this->json('POST', '/register', [
        'name' => 'John Doe',
        'email' => '[email protected]',
        'contact_number' => '12345678',
        'account_type' => 'personal',
        'password' => '123456',
        'password_confirmation' => '123456',
    ]);

    $response->assertRedirect('/auth/verification/sent');

    $this->assertDatabaseHas('users', [
        'name' => 'John Doe',
        'email' => '[email protected]',
        'contact_number' => '12345678',
        'account_type' => 'personal',
        'password' => bcrypt('123456'),
        'verified' => 0,
    ]);
}

RegisterController.php (irrelevant methods stripped out)

protected $redirectAfterTokenGeneration = '/auth/verification/sent';

protected function validator(array $data)
{
    return Validator::make($data, [
        'name' => 'required|string|max:255',
        'email' => 'required|string|email|max:255|unique:users',
        'contact_number' => 'required|string|between:8,255',
        'account_type' => 'required|string|in:personal,agent',
        'password' => 'required|string|confirmed|min:6',
        'g-recaptcha-response' => 'required|captcha',
    ], [
        'g-recaptcha-response.required' => 'Please confirm you are not a robot.',
        'g-recaptcha-response.captcha' => 'You have failed to confirm you are not a robot, please try again.',
    ]);
}

public function register(Request $request)
{
    $this->validator($request->all())->validate();

    DB::beginTransaction();

    try {

        Auth::login($this->create($request->all()));

        $user = auth()->user();

        UserVerification::generate($user);

        UserVerification::send($user, 'UKSACB | Attestation - Account Verification');

    } catch(\Exception $e) {
        DB::rollback();
        throw $e;
    }

    DB::commit();

    return redirect($this->redirectAfterTokenGeneration);
}

protected function create(array $data)
{
    $user = User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'contact_number' => $data['contact_number'],
        'password' => bcrypt($data['password']),
    ]);

    $user = $this->assignRoles($user, $data['account_type']);

    return $user;
}

When running the test vendor\bin\phpunit --filter=a_user_can_register I get the following:

There was 1 failure:

1) RegistrationTest::a_user_can_register
Response status code [422] is not a redirect status code.
Failed asserting that false is true.

C:\laragon\www\attestation\vendor\laravel\framework\src\Illuminate\Foundation\Testing\TestResponse.php:92
C:\laragon\www\attestation\tests\Feature\Auth\RegistrationTest.php:36

When adding dd($response->getContent()); directly after the POST request, I see the following in my terminal:

"{"message":"The given data was invalid.","errors":{"g-recaptcha-response":["Please confirm you are not a robot."]}}"

Any ideas? Thanks.

29th September, 2017

haakym left a reply on Homework For "Learn Vuex With Me: Part 3" • 2 months ago

Thanks, @tykus. Got that working now!

haakym left a reply on Homework For "Learn Vuex With Me: Part 3" • 2 months ago

Wow, can't believe I missed that! It seems my code editor highlights updateTodo regardless of uppercase or lowercase which probably threw me off. Thank you! I'll try out your suggestions and see if I can get this thing working now.

haakym started a new conversation Homework For "Learn Vuex With Me: Part 3" • 2 months ago

I am trying to do the homework Jeffrey set here: https://laracasts.com/series/whatcha-working-on/episodes/23

For anyone who hasn't watched, Jeffrey went through creating a basic todo app using vuex and gave us the task of making a way to edit an existing todo.

I approached this by giving each to do an edit property that is initially set to false:

resources/assets/js/store/index.js

// ...
export default new Vuex.Store({
    state: {
        todos: [
            { body: 'Go to the store', done: false, edit: false },
// ...

...this can then be dynamically changed on a double click event on the todo changing it from a readable state where it displays its body value in a <label> tag when set to false. Then when edit is set to true it will display it in an editable state using an <input>:

resources/assets/js/components/Todo.vue

<template>
    <li class="todo" :class="{ 'is-complete': todo.done }">
        <input type="checkbox" :checked="todo.done" @change="toggleTodo(todo)">
        <span>
            <label v-text="todo.body" v-show="! todo.edit" @dblclick="todo.edit = true"></label>
            <input :value="todo.body" v-show="todo.edit" :autofocus="todo.edit" @keyup.enter="updateTodo">
        </span>
        <button @click="deleteTodo(todo)">x</button>
    </li>
</template>

to confirm the edit made, I set an updateTodo method to fire when the enter key is hit on the input:

<input :value="todo.body" v-show="todo.edit" :autofocus="todo.edit" @keyup.enter="updateTodo">

However, when I run this code I get the following errors in the console:

app.js:2163 [Vue warn]: Property or method "updateTodo" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.

found in

---> <Todo> at resources\assets\js\components\Todo.vue
       <Root>

and

Uncaught TypeError: _vm.updateTodo is not a function
    at keyup (app.js:43508)
    at HTMLInputElement.invoker (app.js:3508)

Any idea what I'm doing wrong here? I can clearly see the updateTodo method is available in the Todo.vue file so I am a bit confused as to why the method can't be invoked. I was also looking at the vuex example by Evan You and it shows a similar approach: https://github.com/vuejs/vuex/blob/dev/examples/todomvc/components/Todo.vue#L47 which I assume runs fine.

Here is the full code for the files I've mentioned above:

resources/assets/js/store/index.js

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
    state: {
        todos: [
            { body: 'Go to the store', done: false, edit: false },
            { body: 'Buy groceries', done: true, edit: false },
            { body: 'Finish homework', done: false, edit: false },
        ]
    },

    mutations: {
        addTodo ({ todos }, body) {
            todos.push({
                body,
                done: false,
                edit: false
            });
        },

        completeAll ({ todos }) {
            todos.forEach(todo => todo.done = true);
        },

        toggleTodo (state, todo) {
            todo.done = ! todo.done;
        },

        deleteTodo ({ todos }, todo) {
            todos.splice(todos.indexOf(todo), 1);
        },

        editTodo (state, { todo, value }) {
            todo.text = value
        }
    }
});

resources/assets/js/components/Todo.vue

<template>
    <li class="todo" :class="{ 'is-complete': todo.done }">
        <input type="checkbox" :checked="todo.done" @change="toggleTodo(todo)">
        <span>
            <label v-text="todo.body" v-show="! todo.edit" @dblclick="todo.edit = true"></label>
            <input :value="todo.body" v-show="todo.edit" :autofocus="todo.edit" @keyup.enter="updateTodo">
        </span>
        <button @click="deleteTodo(todo)">x</button>
    </li>
</template>

<script>
    import { mapMutations } from 'vuex';

    export default {
        props: ['todo'],

        methods: {
            ...mapMutations(['deleteTodo', 'toggleTodo', 'editTodo']),
            updateToDo (e) {
                console.log('hi');
            }
        }
    }
</script>

<style>
    .todo.is-complete {
        color: grey;
    }
</style>

Any help would be appreciated!

6th July, 2017

haakym left a reply on Unknown Error: Cannot Find Chrome Binary Using Laravel Dusk And Valet • 5 months ago

The error messages states:

... cannot find Chrome binary ...

Do you have Google Chrome installed?

6th June, 2017

haakym left a reply on Guidance On Contributing To Laravel • 6 months ago

@Flugg

Ah, okay thanks! Sorry wasn't super clear to me.

Thanks for the encouragement!

5th June, 2017

haakym started a new conversation Guidance On Contributing To Laravel • 6 months ago

I would like to contribute to the Laravel framework. I started by browsing the issues on github and found this issue: https://github.com/laravel/framework/issues/19445.

The Laravel documentation states:

To encourage active collaboration, Laravel strongly encourages pull requests, not just bug reports. "Bug reports" may also be sent in the form of a pull request containing a failing test.

https://laravel.com/docs/5.4/contributions#bug-reports

As most issues are above my understanding, I thought I'd start off small and try to write a failing test for the aforementioned issue. Perhaps that wasn't very helpful? However, I thought that if I don't try I won't learn anything.

I made a PR to the 5.4 branch with the failing test which was subsequently closed: https://github.com/laravel/framework/pull/19460.

and I now have a couple of questions about contributing that I would hope somebody could answer...

How and where would one submit a bug report in the form of a PR/failing test, is it meant to go on a different branch?

The response I got after submitting the PR with the failing test suggested that I should be submitting a fix in the PR and not just a failing test. I assume they meant the fix and a passing test as I couldn't understand how you could have a failing test accompanied with a fix? Have I misunderstood the feedback I got on the PR or/and the context of the text I quoted above from the docs contribution guide, in which case please explain to me what I have misunderstood.

Any guidance on this would be greatly appreciated, thank you!

28th March, 2017

haakym left a reply on Async Await In Vue Component Compiling With Laravel Mix • 8 months ago

Right, so I'm using the async/await wrong, nothing to do with Mix as far as I'm aware.

haakym started a new conversation Async Await In Vue Component Compiling With Laravel Mix • 8 months ago

Hi everyone.

I've written the following methods in a .vue component utilising async/await on an axios post request call. However, when running the code it doesn't appear the async/await stuff is working as some of the variables that get set using it return undefined until the end of the execution of the code. I've stripped the code down to what I think are the important parts, happy to show more if needed.

resources/assets/js/components/PrintTicketDashboard.vue

printTicket() {
    let ticketInfo = this.saveTicket() // <-- async method is invoked here, see below
    
    let zplCommand = this.buildZplCommand()
    
    let printJob = this.printZpl(zplCommand)
},

async saveTicket() {
    const response = await axios.post('/tickets/store', {
        'department_id': this.ticket.department.id,
        'student_id': this.ticket.student.id,
        'ticket_data': JSON.stringify(this.ticket)
    })
    
    const createdAt = new Date(response.data.created_at)
        
    this.ticket.sequenceNumber = response.data.sequence_number
    this.ticket.dateTime = `${createdAt.getHours()}:${createdAt.getMinutes()} ${createdAt.getDate()}/${createdAt.getMonth() + 1}/${createdAt.getYear()}`
    /*
        ^--- these props are accessed in buildZplCommand() and printZpl() invoked in method above but return undefined until end of execution
    */
},

I'm using laravel mix to compile my assets and was under the impression the mix.js() method will compile any ES2015 (such as async/await) as mentioned here https://laravel.com/docs/5.4/mix#working-with-scripts.

I've tried mix.babel() instead but got some errors that I couldn't make sense of, perhaps I need a babel.rc file?

app.js

Vue.component('print-ticket-dashboard', require('./components/PrintTicketDashboard.vue'));

const app = new Vue({
    el: '#app'
});

webpack.mix.js

const { mix } = require('laravel-mix');

mix.js('resources/assets/js/app.js', 'public/js')
   .sass('resources/assets/sass/app.scss', 'public/css')
   .browserSync('ticket.dev')
   .disableNotifications();

Any ideas on what I might be doing wrong here?

17th March, 2017

haakym left a reply on Laravel Mix Windows Npm Error • 9 months ago

@rik13 Thank you!

10th March, 2017

haakym left a reply on Showing Request Validation Errors When Submitting Form By Ajax • 9 months ago

Hi @pjfl

If your endpoint is not understanding that it's an ajax request it may be returning a redirect back with the errors instead of a failed response back with the errors as json.

You might be best creating your own question with the code you're using.

6th March, 2017

haakym started a new conversation Braintree Setting Amount And Avoiding Rounding Errors • 9 months ago

I am creating a web app using PHP/Laravel and Braintree for payments. I am using the Braintree dropin.

A simplified flow of the web app:

  1. User uploads a file and selects a service from dropdown, submits form
  2. User is shown quote/price which is calculated by taking the uploaded file's word count * selected service
  3. User selects payment via Braintree drop-in, submits form to pay
  4. Web app fires Braintree_Transaction::sale()
  5. User is shown success page

Charging the customer

Regarding the above, I would like to get some advice on best practice for setting the amount in the Braintree_Transaction::sale() method call in step 4.

In the Braintree PHP example on github the amount used in the Braintree_Transaction::sale() method call is taken from a text input in the form, this can be edited by the user, I assume for example purposes.

In my web app flow described above, after step 1, would I be correct to set the quote/price of the selected service in the session then show this value from the session to the user in step 2 and finally pass the value from the session as the amount to Braintree_Transaction::sale()? Or is there a different recommended approach to take? My main concern is charging the customer the correct amount.

Avoiding rounding errors

As the quote/price is calculated in PHP by taking the uploaded file's word count and multiplying it with the service a customer has selected this will at times involve floating point numbers. E.g. Word count is 1000, selected service is proof-reading which is x1.5, so quote would be 1500 => £15.00.

If my memory serves me correctly Stripe represents, for example, one pound (£) in pennies `10. This is nice as it helps avoid rounding errors. Braintree on the other hand I believe expects one pound (£) to be represented with the decimal point `1..

What would be my best approach to avoid any rounding errors in such a scenario?

Thanks for any suggestions and please ask for more details if required I've tried to make this as brief and general as possible.

1st March, 2017

haakym left a reply on Add Watermark/stamp To PDF With Preview • 9 months ago

Hi @sorcjc

Yes, my working solution (although a bit hacky) was to use Mozilla's pdf.js and a JS drag and drop library as a preview in the browser. Then send the data over to the server and use FPDF or FPDI (I forget which one) to perform creation of the stamped documents.

What are you trying to do exactly? Would love to help if I can.

26th January, 2017

haakym left a reply on Preparing The Database Before A Test For A Model With Many Dependencies, Is There A Better Way? • 10 months ago

For anyone interested, I have made an SO question with an answer to use \Schema::disableForeignKeyConstraints(); which works. See here:

http://stackoverflow.com/questions/41802499/laravel-preparing-the-database-before-a-test-for-a-model-with-many-dependencies

Please note my comment under this answer:

although this achieves what I originally asked in my question, i.e. "Is there a more simple approach where I only create the model that is under test" - is this considered "bad practice" at all? I know with testing and programming, in general, there is not always a right way to do something but I'm just wondering if there are any implications that I should consider before taking on this approach throughout my whole test suite?

Any guidance would be greatly appreciated. Thanks!

20th January, 2017

haakym started a new conversation Preparing The Database Before A Test For A Model With Many Dependencies, Is There A Better Way? • 10 months ago

I am writing a test for a page that performs updates, the test simply checks that one of the model's attributes hasn't changed prior to submitting the form in order to prevent two users from updating the model if they had it both open in their browser at the same time.

The test requires the use of a model in my Laravel web app: App\Models\Application and I am using factories to create some fake data for this model. The test simply checks that one of the model's attributes hasn't changed prior to submitting the update form that will change it.

The Application model has many belongsTo relationships, which in turn requires for the related model to exist prior to the creation of the Application model. For example, the Application model has a belongsTo relationship with Applicant, so I need to create an Applicant model with a factory prior to creating an Application and an Applicant also has belongsTo relationships with User, which I also need to create before ... you get the idea.

So this has left me wondering if I am taking the wrong approach? Is there a more simple approach where I can simply create the model that is under test?

Thanks for any advice.

29th September, 2016

haakym left a reply on Using Vue.js In Laravel 5.3 • 1 year ago

Did you solve this? I am facing the same question...

@Raido

There's a response to my question here if you're interested: http://stackoverflow.com/questions/39708680/using-vue-js-in-laravel-5-3

27th September, 2016

haakym left a reply on Using Vue.js In Laravel 5.3 • 1 year ago

I'm going to repeat the question again as based on some of the answers it seems as I didn't get my point across. Hope this makes things clearer.

In Laravel projects prior to 5.3 I've utilised Vue.js using the script tag like this:

<script type="text/javascript" src="../js/vue.js"></script>

I would then create a Vue instance specific for that page like this:

<script>
    new Vue({
      el: '#app',
      data: {
        message: 'Hello Vue.js!'
      }
    });
</script>

and then bind it to the relevant div#id in my HTML.

Now, in Laravel 5.3 Vue.js comes bundled and I am fully aware that I can use components as described in the docs, however, my question is if I want to create a Vue.js instance like I just mentioned, i.e. where I create a Vue.js instance strictly for a given page (not a component) how do I do it?

Do I set it up like I used to by importing the vue.js library in a script tag firstly or can I use generated app.js?

Am I not supposed to do it, should I be creating components for everything?

For me, it doesn't make sense to make a component for something I am only using once - I thought the purpose of components was that they are reusable. As mentioned in the Vue.js docs:

Components are one of the most powerful features of Vue.js. They help you extend basic HTML elements to encapsulate reusable code.

Any advice would be appreciated, thanks!

haakym left a reply on Using Vue.js In Laravel 5.3 • 1 year ago

@ejdelmonico Thanks for your reply. So are you saying that all interactions with Vue.js should be via components?

26th September, 2016

haakym left a reply on How To "DRY Up" My Tests Set Up • 1 year ago

@ohffs

Haha, at least you're honest!

Thanks for your insights and advice, very helpful! I think I'll probably reach for traits once I get a few more tests knocked out and can begin getting an idea of how I can structure the setup more wisely.

haakym left a reply on How To "DRY Up" My Tests Set Up • 1 year ago

@ohffs Thanks for your reply.

I think that's a good approach to take. How would you go about pulling in the global setup when you need to utilise it?

I like the method name you chose for delete shred() - haha!

haakym started a new conversation Using Vue.js In Laravel 5.3 • 1 year ago

In previous Laravel projects, I've dropped Vue.js into a page and created a Vue instance specific for that page. Something like this at the bottom of my page:

<div id="app">
    @{{ message }}
</div>
...
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.27/vue.js"></script>
<script>
        new Vue({
          el: '#app',
          data: {
            message: 'Hello Vue.js!'
          }
        });
    </script>

Now in Laravel 5.3 Vue.js comes bundled up with it and I have got a slight grasp on how I can create components which I can then drop into a page. However, I am struggling to understand how I can create a Vue.js instance like the aforementioned, i.e. where I just need to drop a vue instance into a page instead of creating a whole component.

Can I utilise Vue that gets incorporated into app.js when running gulp or do I need to pull in Vue as I did before with the script tag?

Thanks!

haakym left a reply on Vou-Router • 1 year ago

@LJ90

I maybe should mention that the vue-devtools in my chrome browser do not appear in the browser (and I have absolutely no idea why), so I cannot check for errors.

I have had this issue before when I'm using minified vue vue.min.js - try using it when it's not minified and see if that works.

haakym left a reply on How To "DRY Up" My Tests Set Up • 1 year ago

@ohffs I haven't actually. I'll be sure to check it out, thank you.

@ifpingram Thanks for your response. You really addressed my concerns there!

Perhaps my question should have been, should I be DRYing up my test setup - not how. I think I had the idea that a particular approach may have tackled the issues you mentioned more effectively. For now, I think I'll leave my tests alone and see how things pan out once I've written some more tests. Thanks again.

haakym started a new conversation How To "DRY Up" My Tests Set Up • 1 year ago

Hey everyone. I'm trying to practice a little TDD after watching Adam Wathan's videos at Laracon etc. I've got about three test classes so far and I seem to be doing a lot of setup that involves adding data to the DB that's required for the test. I would like to know what would be the best approach to clearing up such repetitive code from my tests and to further utilise this as my number of tests increase.

Some of the methods from my tests with similar setup flow looks like this:

  1. create a user(s)
  2. create a department the user(s) belongs to
  3. create a resource related to the user(s)

AuthenticationTest.php

/** @test */
public function user_is_logged_in()
{
    $user = factory(User::class)->make([
        'username' => 'jsmith',
        // ... some data
    ]);

    $department = factory(Department::class)->create(['name' => 'IT Department']);
    
    $department->users()->save($user);

    // sets $_SERVER['REMOTE_USER'] variable via SSPI
    $this->setRemoteUser($user->username); 

    $this->visit('/')
        ->assertEquals($user->username, Auth::user()->username);
}

AccountTest.php

/** @test */
public function user_can_view_their_account()
{
    $user = factory(User::class)->make([
        // ... some data
    ]);

    $department = factory(Department::class)->create(['name' => 'IT Department']);
    
    $department->users()->save($user);

    $employeeDetails = factory(EmployeeDetail::class)->make([
        // ... some data
    ]);
    
    $user->employeeDetails()->save($employeeDetails);

    Auth::login($user);
    
    $this->visit('/account')
         ->see($user->name)
         ->see($user->department->name)
         ->see($user->employeeDetails->start_date->format('d-m-Y'))
         ->see($user->employeeDetails->employee_type);
}

UserEmployeeRequestTest.php

/** @test */
public function user_can_view_their_requests()
{
    $employee = factory(User::class)->make([
        // ... some data
    ]);

    $manager = factory(User::class)->make([
        // ... some data
    ]);

    $department = factory(Department::class)->create(['name' => 'IT Department']);
    
    $department->users()->save($employee);
    $department->users()->save($manager);

    $employeeRequest = factory(EmployeeRequest::class)->make([
        // ... some data
        'manager' => $manager->id,
    ]);
    
    $employee->employeeRequests()->save($employeeRequest);

    Auth::login($employee);
    
    $this->visit('/employee/employee-requests')
        ->see(/* data from employee request */);;
}

So, as far as I'm aware, I have some of the following options:

  1. Extract the setup to a method on a base class
  2. Extract to a trait(s)
  3. Extract to a setUp() method on the class and call parent::setUp()

I'd appreciate any recommended ways to clear up the repetitive code while keeping it flexible enough to scale as I write more tests that may require different or more set up data. Thanks!

22nd September, 2016

haakym left a reply on Submitting Form In Vue.js With Ajax • 1 year ago

@sorcjc What does your console say - any errors?

22nd July, 2016

haakym started a new conversation Add Watermark/stamp To PDF With Preview • 1 year ago

In an application I'm building the admin users are currently downloading a PDF file then manually adding 3 image files as a stamp/watermark then re-uploading that PDF.

If at all possible, I would like to add this functionality to the web application. The functionality I'm looking for would allow the user to view the PDF in the webpage and decide where the stamp is placed using up/down, left/right buttons then once decided they could place the stamp in the desired location onto the PDF and add another if needed. The reason for this is because sometimes the stamp may not be visible if added to the same place each time due to content in the PDF.

So far I've looked at FDPF which I've used before to merge two PDF files together - I'm guessing this would help me achieve the watermark part, but how could I go about doing the preview part?

Any ideas or suggestions are welcome. I'm not restricted to PHP, any reasonable solution in PHP, JS or a script that could run in a Laravel application would be fine.

Thanks!

23rd May, 2016

9th May, 2016

haakym left a reply on Correct Approach To Creating Record Then Immediately Adding One-to-one Relation • 1 year ago

I'm trying this code:

$applicant = Applicant::create($this->applicantDataFromRequest($request));

$application = new Application([
    'status'           => 'pending',
    'reference_number' => $request->get('passport_number'),
    'organisation_id'  => $request->get('organisation'),
    'qualification_id' => $request->get('qualification') ?: null,
]);

$applicant->application()->save($application);

dd('done');

And still getting the same error:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`attestation`.`applications`, CONSTRAINT `applications_applicant_id_foreign` FOREIGN KEY (`applicant_id`) REFERENCES `applications` (`id`) ON DELETE CASCADE) (SQL: insert into `applications` (`status`, `reference_number`, `organisation_id`, `qualification_id`, `applicant_id`, `updated_at`, `created_at`) values (pending, 5730970933C7B, 24, 1, 22, 2016-05-09 14:56:25, 2016-05-09 14:56:25))

haakym left a reply on Correct Approach To Creating Record Then Immediately Adding One-to-one Relation • 1 year ago

@pmall

Thanks, I updated the question from:

$application = $applicant->applications()->create([
    // data
]);

to:

$application = $applicant->application()->create([
    // data
]);

haakym left a reply on Correct Approach To Creating Record Then Immediately Adding One-to-one Relation • 1 year ago

@desaijay123 so I would need to pass it a new instance rather than array in that case:

$application = new Application([
    // data
]);

$application = $applicant->application()->save($application);

haakym left a reply on Correct Approach To Creating Record Then Immediately Adding One-to-one Relation • 1 year ago

@pmall

Sorry! It's a one-to-one relation. Corrected the question.

haakym started a new conversation Correct Approach To Creating Record Then Immediately Adding One-to-many Relation • 1 year ago

I've got the following eloquent models and relations set up:

Applicant

class Applicant {
    public function application()
    {
        return $this->hasOne(Application::class);
    }
}

Application

class Application {
    public function applicant()
    {
        return $this->belongsTo(Applicant::class);
    }
}

I simply want to create a new applicant then add a new application for the applicant just created:

$applicant = Applicant::create([
    // data
]);

$application = $applicant->applications()->create([
    // data
]);

However, when running this code I receive the following error:

SQLSTATE[23000]: Integrity constraint violation: 
1452 Cannot add or update a child row: a foreign key constraint fails (
    `attestation`.`applications`, CONSTRAINT `applications_applicant_id_foreign` 
    FOREIGN KEY (`applicant_id`) REFERENCES `applications` (`id`) ON DELETE CASCADE
)
(SQL: insert into `applications` (
    `status`,
    `reference_number`,
    `organisation_id`,
    `qualification_id`,
    `applicant_id`,
    `updated_at`,
    `created_at`
) values (
    pending,
    573066CE59BFE,
    24,
    1,
    12, // <------ applicant_id, i.e. the foreign key!
    2016-05-09 11:30:38,
    2016-05-09 11:30:38
))

As I understand, the error is occuring because I'm passing it a foreign key that doesn't exist in the database. So I was wondering what is happening here with the first call to the DB that I make to create the applicant:

$applicant = Applicant::create([
    // data
]);

Is it not written to the DB before the second statement that creates the application:

$application = $applicant->applications()->create([
    // data
]);

... and thus causing the integrity constraint violation? Because if I dd($applicant) immediately after creating it or dd(Applicant::find($applicant->id)) I get the record and I can also view it in the DB.

I've found that prior to re-factoring my code when I was calling create() to add a new record then building up a new application line by line and using save(), I didn't encounter this issue. So I'm curious to know how both calls differ (if they do) and what would be the correct way to approach such a scenario as I thought it was something very simple with eloquent which I've done many times before. Any advice would be most appreciated, thanks!

3rd May, 2016

haakym left a reply on Testing A Form, Dropdown Issues Where Dropdown Is Populated Via Vuejs • 1 year ago

Great, thanks for the suggestion @ohffs I will check out the video and see if its manageable.

Jeffrey Way did mention the following on an AMA on hashnode last month:

One pain point for me at the moment would relate to testing code that requires JavaScript. Right now, we have a great API in place for integration testing...but, once you introduce JavaScript, it gets a little tricky. I'm hoping that someone will PR a Selenium driver that allows us to use the exact same API we currently have, but leverage Selenium behind the scenes.

https://hashnode.com/ama/with-jeffrey-way-cimd458uo01bwtg53yed55n8n#cimdltl9l01eltg53in0oaiqk

Here's hoping it gets implemented.

haakym left a reply on Question On Book: PHP Objects, Patterns, And Practice • 1 year ago

@robgeorgeuk Looks like there is something in the works! No idea when it will be completed though?

Just signed a contract to write PHP Objects Patterns and Practice Edition 5 - should be a fun one!

https://twitter.com/getInstance_mz/status/685193564368814085

haakym left a reply on Question On Book: PHP Objects, Patterns, And Practice • 1 year ago

Thanks a lot for the suggestions guys!

25th April, 2016

haakym started a new conversation Question On Book: PHP Objects, Patterns, And Practice • 1 year ago

Hey everyone,

At the following link https://laracasts.com/recommended-reading the book "PHP Objects, Patterns, and Practice 4th ed. 2013 Edition" by Matt Zandstra is recommended.

I wanted to purchase the book on kindle, but as the book was published in 2013 I was curious to know whether a large part of the content would be outdated or not, or if there's a newer version in the works that I should wait for.

Any advice on this or recommendations for other books would be appreciated.

Thank you!

20th March, 2016

haakym started a new conversation Testing A Form, Dropdown Issues Where Dropdown Is Populated Via Vuejs • 1 year ago

I'm writing a small test for a form and I'm getting errors when running phpunit. It gets stuck because it can't see any options in one of the dropdown boxes named organisation which is populated by vuejs. The dropdown in question is populated with a list of json values loaded when the page first loads up and is further filtered by the first dropdown list in the form, namely academic_certificate.

Here's my view/blade file with the dropdown:

<select name="organisation" id="" class="form-control" {{-- required="required" --}} v-model="organisation">
    <option value="">Select</option>
    <option v-for="organisation in organisations | filterBy application_type in 'organisation_types'">
        @{{ organisation.name }}
    </option>
</select>

Here's my test:

/** @test */
public function verified_user_can_create_academic_certificate_application()
{
    $faker = Faker::create();

    $user = factory(App\Models\User::class)->create();
    $applicant = Role::where('name', 'applicant')->firstOrFail();
    $user->roles()->attach($applicant->id);
    
    $this->actingAs($user)
        ->visit('/applicant/application/create')
        ->select('academic_certificate', 'application_type')
        ->type($faker->firstNameMale, 'first_names')
        ->type($faker->lastName, 'last_name')
         // fill out rest of form ...
        /****************************************
            here's where it gets an error!
        ****************************************/
        ->select('Some organisation', 'organisation')   
        ->select('1', 'qualification')
        ->type('IT', 'speciality')
        ->type('2002', 'year_of_award')
        ->press('Submit')
        ->see('complete');
}

The test:

$ vendor/bin/phpunit
PHPUnit 4.8.23 by Sebastian Bergmann and contributors.

E.FF

Time: 7.15 seconds, Memory: 37.00Mb

There was 1 error:

1) ApplicationTest::verified_user_can_create_academic_certificate_application
InvalidArgumentException: Input "organisation" cannot take "Some organisation" as a value (possible values: ,
                                                {{ organisation.name }}
                                            ).

C:\wamp\www\attestation\vendor\symfony\dom-crawler\Field\ChoiceFormField.php:140
C:\wamp\www\attestation\vendor\symfony\dom-crawler\FormFieldRegistry.php:128
C:\wamp\www\attestation\vendor\symfony\dom-crawler\Form.php:77
C:\wamp\www\attestation\vendor\laravel\framework\src\Illuminate\Foundation\Testing\Concerns\InteractsWithPages.php:808
C:\wamp\www\attestation\vendor\laravel\framework\src\Illuminate\Foundation\Testing\Concerns\InteractsWithPages.php:788
C:\wamp\www\attestation\vendor\laravel\framework\src\Illuminate\Foundation\Testing\Concerns\InteractsWithPages.php:775
C:\wamp\www\attestation\tests\acceptance\applicant\ApplicationTest.php:55

Any help would be really appreciated, I'm trying to get to grips with testing and would hate to get stuck here! Thank you.

14th March, 2016

haakym left a reply on Generating A Unique ID/Code For Resource • 1 year ago

@premsaurav

No, not really. The main reason I was asking the question is that firstly I was wondering if there are any issues with the methods that I have considered, i.e. uniqid() and if there's a better way that others may have used in their projects.

haakym started a new conversation Generating A Unique ID/Code For Resource • 1 year ago

Apologies if this has already been addressed on the fourms, wasn't entirely sure what to search for.

I'm developing an application where a user submits an Application. Each Application needs to have a unique ID or code which will primarily be used by the user and the system admins in order to identify an particular Application.

My question is what would be the best way to generate this ID/code in PHP? I have the following considerations for the ID/code:

  1. It has to be unique
  2. It can't be too long (if the applicant phones up we don't him reading a 30/40 digit number over the phone)

I've considered using uniqid() or uniqid(rand()) which generates a unique string of 13 and 23 characters respectively. From my searching around I've also seen UUID been mentioned but didn't feel it was right for my use case.

Any suggestions or guidance on this would be appreciated.

Thank you!

26th February, 2016

haakym left a reply on Dynamic Eloquent Relationship • 1 year ago

Many thanks @harryg and @pmall

I've implemented some of the suggestions you made and the structure although I think I could do a bit more refining the database is looking a lot better now! The adam wathan video was quite useful too.

Thanks again for your helpful advice.

Edit Your Profile
Update

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