D9705996

D9705996

Software Developer at Sabio Ltd

Glasgow

Member Since 3 Years Ago

Experience Points 276,540
Experience
Level
Lessons Completed 1229
Lessons
Completed
Best Reply Awards 242
Best Answer
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

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

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

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

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    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 Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

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

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

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

18 Jan
2 days ago

D9705996 left a reply on Install And Laravel-echo-server Multiple Times On The Same Server

@AHOI - No. You dont need to use pusher... from the blog link in the docs

It completely replaces the need for a service like Pusher or a JavaScript-based laravel-echo-server.

However I had some issues when setting thd env variables using random values so have a pusher account that I used just to generate them for me but isn't used for broadcasting

D9705996 left a reply on Issue With Vue Test Utils In Laravel

@JMARILLER - Awesome. Could you please mark your answer as best answer to solve the discussion

17 Jan
3 days ago

D9705996 left a reply on Attaching Relationship Data To Model Before Saving It?

I would move your generateCodes from your controller to your Discount model.

    public function generateCodes($codesToGenerate = 1)
    {
        for ($i = 0; $i < $codesToGenerate; $i++) {
          $code = new DiscountCode([
            'unicode => $this->generateRandomToken(),
        'expireDate' => Carbon::now()->addDays(365)
      ]);
          $this->discountcodes()->save($code);
        }
    }

You can then do

$discount->save();
$discount->generateCodes($request->input('codesToGenerate'));

D9705996 left a reply on Overwrite Queue And Delay In A Job

Looking at the api documentation for mailable there aren't any properties for defining thd queue or delay so nothing out of the box. However you could try adding your own custom static function e.g. sendLater but to be honest I wouldn't bother. IMO What you have is easy to read and maintain and follows the laravel way which I often find to be the right way

D9705996 left a reply on Validation

Have a look at the validation documentation

https://laravel.com/docs/5.7/validation

Sound like you need the alpha_num and image rules.

D9705996 left a reply on Issue With Vue Test Utils In Laravel

I'm not sure how to fix your issue but I think it's related to the latest version of laravel installing webpack 4 and the series you reference was on webpack 3.

Might help you narrow down your googling

16 Jan
4 days ago

D9705996 left a reply on Having A "debug"-option For All Routes?

You dont say whether you are using laravel or lumen and what versions but telescope might be a good option depending on what your trying to log/debug

https://laravel.com/docs/5.7/telescope

You can specify different logging for prod and dev (look at the filter section over the link)

D9705996 left a reply on Install And Laravel-echo-server Multiple Times On The Same Server

You should be able to run more than one instance of echo server on a single server as long as you configure different TCP ports and either separate redis instances or a separate database in your redis config](https://github.com/tlaverdure/laravel-echo-server#database). You should then only need to configure your javascript that creates you echo connection to point to the correct port.

Admittedly I haven't tried this but should work. I would strongly suggest checking out laravel websockets as it has multi tenancy built in sp you wouldn't need seperate socket server instances

https://docs.beyondco.de/laravel-websockets/1.0/basic-usage/pusher.html#pusher-configuration

15 Jan
5 days ago

D9705996 left a reply on ES6 Import In Vue Components Or Globally In App.js?

@SCHEMEZA - Depends on the project. The majority I import where I need them but in some of them where I was importing almost everywhere I add to bootstrap.js.

14 Jan
6 days ago

D9705996 left a reply on Running Just VUEJS Application Alongwith Blade

@DANYAL14 - If you need to serve blade templates you can still do so with Lumen as lumen has access to Illuminate/View which includes the blade compiler.

12 Jan
1 week ago

D9705996 left a reply on Sublime Text 3 Package Control Server Offline

@THAVARSHAN - No worries. Can you please mark discussion as solved (as it's a 3rd party issue) just incase anyone else has the same question

D9705996 left a reply on Factory Faker Unique() Across All Tests?

@DHERMANN - Your tests should have zero dependencies on your other tests. Your factories will honour your uniqueness in a single test. You need to ensure your validation prevents duplicates

D9705996 left a reply on Connect No Sql Collections From MySQL To Laravel

If you have an array you can wrap it in collect( ... ) to make a collection. If that's not what you want then I'm not sure. Maybe if you show some code it might help.

D9705996 left a reply on Intersect Two Collections Or Some Other Way?

To be honest I dont think your going to find a better way to do this. It seems pretty optimal to me.the only obvious refactor would be to return the data immediately rather than assign a temp variable

return $category_cars->intersect($color_cars);

D9705996 left a reply on Your Understanding Of What A MySQL Schema Is?

@DAVESTEAD - To be honest I think we argue about the different vendor definitions of what is a schema, database, etc and how they relate to laravel forever and isn't something I want to spend any real effort on.

You want to reduce any ambiguity when you ask for help here so all I can give you is what would help me if you start a discussion that I wanted to help with.

For 99% of times avoid the ambiguous terms completely and explain your problem in plain English, what you have tried, any errors and the relevant code as this helps more than whether its a schema, database, etc.

Laravel hides a lot of the implementation details behind interfaces/config so details like database shouldnt matter as migrations, eloquent, etc are agnostic to this detail.

Just remember that everyone here is doing so as part of a community and does so of there own free will so the harder you make it for us to help with unnecessary issues the less likely you are to get that help in the first place.

D9705996 left a reply on Running Just VUEJS Application Alongwith Blade

@DANYAL14 - If your not using any php logic why would you need a php framework? Just serve your static html from your webserver.

D9705996 left a reply on Sublime Text 3 Package Control Server Offline

Looks like any issue with package control as when you go to https://packagecontrol.io/ in a browser you get a server error

Server Error Sorry, apparently we ran into an error we were not expecting!

D9705996 left a reply on Running Just VUEJS Application Alongwith Blade

Although they have been removed from the documentation it looks like you can still serve views with lumen as it includes "illuminate/view": "5.7.*", in composer.

https://stackoverflow.com/questions/39812407/views-in-lumen-5-2

I dont use lumen so can't confirm but theory looks good. You might want to consider using vue router to create an SPA and you can just server your static page from your webserver and consume your lumen API. Have a look at

https://scotch.io/tutorials/how-to-build-a-simple-single-page-application-using-vue-2-part-1

D9705996 left a reply on Add Functions To Vue Object

Have a look at the documentation on how to add to the vudu prototype

https://vuejs.org/v2/cookbook/adding-instance-properties.html

D9705996 left a reply on How Can I Get Value If I Save A Field In Json Encode With Its Id?

@VICKYAGGARWAL - If you are new to laravel you really should spend time learning the basics. There is a good introduction series here

https://laracasts.com/series/laravel-from-scratch-2018

You also ask why you need a pivot table... this is databass design fundamentals rather than laravel but theres also a series here

https://laracasts.com/series/eloquent-relationships

11 Jan
1 week ago

D9705996 left a reply on Testing Laravel Mailables And Passing Data

AssertSent checks to see if the preceding code sent a mail that matches the class and any condition s in the call back. However you are trying to use this to send the mail which wont work as you need to do something like.

    Mail::to(User::first())->send(NewBroadcastMessage::class('test_subject',message'));

    Mail::assertSent(NewBroadcastMessage::class, function ($mail) {
  
        return $mail->subject === 'test_subject';
    });

Thd test isn't very useful but should help you get started

https://laravel.com/docs/5.7/mocking#mail-fake

D9705996 left a reply on Path To Mailables Inside A Package

@NAM_CO - Could you please mark the discussion as solved

D9705996 left a reply on How Can I Get Value If I Save A Field In Json Encode With Its Id?

Storing the related ids in a json encoded column isn't the right way to go IMO.

You need to have a many-to-many relationship between Classes and Users (assuming a User can take many classes)

You therefore need 3 tables, your existing users and classes and a pivot table for class_user that has a column for user_id and class_id

Schema::table('class_user', function (Blueprint $table) {
    $table->increments('id');
    $table->unsignedInteger('user_id');
    $table->unsignedInteger('class_id');

    $table->unique(['user_id','class_id']); // prevent the user appearing in the same class twice

    $table->foreign('user_id')->references('id')->on('users');
    $table->foreign('class_id')->references('id')->on('classes');
});

Then in your User model you need to setup the relationship

public function classes() {
    return $this->belongsToMany(Class::class);
}

In your class model

public function users() {
    return $this->belongsToMany(User::class);
}

You can then get the user details for a specific class with

foreach(Class::find(1)->users as $user) {
    dump($user->mobile);
}

or if you want all the classes for a user

foreach(User::find(1)->classes as $class) {
    dump($class->name);
}

The above is assuming you have followed laravel naming conventions but if not just change to fit your specifics. You will probably have to tinker a bit to get up and running but should give you the general idea.

D9705996 left a reply on Path To Mailables Inside A Package

Can you share how you have configured the autoloader sections of composer.json for your local package?

D9705996 left a reply on Carbon - Get Date Depending On Now() Value

You can get the 1st September of the current year with the following (from the docs)

Carbon::createFromDate(null, 9, 1)

This gives the following in tinker

>>> Carbon\Carbon::createFromDate(null, 9, 1);
=> Carbon\Carbon @1567347837 {#3292
     date: 2019-09-01 14:23:57.0 UTC (+00:00),
   }

D9705996 left a reply on ES6 Import In Vue Components Or Globally In App.js?

Personally I prefer to only import and register my components in the components that require them rather than globally. I find this helps me encapsulate my components so I can easily reuse them in other projects e.g. A task-list item component is only going to be used within my task-list component

This also helps when you review code as you can see exactly where your components are coming from rather than having to keep going back to app.js.

If you wanted to automatically import all of your components globally from a specific directoy you could look at this gist from Jonathan Reinink and add to your app.js

const files = require.context('./', true, /\.vue$/i)
files.keys().map(key => {
    const name = _.last(key.split('/')).split('.')[0]
    return Vue.component(name, files(key))
})

D9705996 left a reply on Convenient And DRY Way To Save Morphable To Relationship

@SERGEY_BRUHIN - There is an interesting article on structuring your laravel application by domain.

https://stitcher.io/blog/organise-by-domain

D9705996 left a reply on How Should I Handle Workflow Of My App According Global Settings?

@ILYAPETROV - To avoid having to have an if statement for each key in your store, if you match the setting name to the relationship you could loop around them (I don't know how your settings helper work so below is using the native package methods.

$relations = ['responsible_person', 'staff'];

$valuestore->put('activities', 'value');
$valuestore->put('working_places', 'value');

foreach ($valuestore->all() as $setting) {
    $relations[] = $setting;
}

$divisions = Division::with($relations)->get();

D9705996 left a reply on Your Understanding Of What A MySQL Schema Is?

@DAVESTEAD - > MySQL database - server/host.

MySQL schema - table-containing "database"

The database is not the server/host. A database server is an application running on a server which can have many databases.

The schema is not a table containing the database. The schema defines the structure of each table within a specific database (for example you may have a different user table schema for different databases).

I would advise to avoid any ambiguity when posting within Laracasts to stick to Laravel specific terminology e.g. rather than saying schema use migrations and show the content of the relevant migration(s), That way 99% of people will understand exactly what you mean rather than having to interpret your own domain specific language

10 Jan
1 week ago

D9705996 left a reply on How Should I Handle Workflow Of My App According Global Settings?

@ILYAPETROV - Could you share the link to the spatie package you are using.

D9705996 left a reply on Is Build A Separate Real Time Server Good Idea?

If your struggling with socket.io and node websockets havd z look at

https://docs.beyondco.de/laravel-websockets/

A php socket server that is pusher api compatible and has great docx to get you up and running really easily. Much easier than trying to split out your so lets go a separate server

D9705996 left a reply on How Should I Handle Workflow Of My App According Global Settings?

Have a look at the Querying Relationship Existence section of the documentation

https://laravel.com/docs/5.7/eloquent-relationships

The has, whereHas, etc methods sound like what you need

D9705996 left a reply on Convenient And DRY Way To Save Morphable To Relationship

@SERGEY_BRUHIN - If you are going to reuse your classes across multiple projects you might want to consider making a package. Not the easiest thing in he world but I found this series really useful

https://www.youtube.com/playlist?list=PLpzy7FIRqpGBQ_aqz_hXDBch1aAA-lmgu

D9705996 left a reply on Autoload_classmap.php And Autoload_static.php In Vendor/composer

I believe so unless you use --no-autoloader

D9705996 left a reply on How To Solve This Error: `app.js:38038 POST Http://www.notification.test/broadcasting/auth 403 (Forbidden)`

Have a read of the documentation on how to authorise access to private channels. You need to return a boolean from Broadcast::Channel method

As test if you change to just return true, does it work.

Broadcast::channel('notifications', function ($user) {
    return true;
});

If so then you need to work out your authorisation logic.

D9705996 left a reply on Queued Jobs And Withoutoverlapping

@JOVEICE - If you find the changes resolve your issue can you please mark the discussion as solved.

D9705996 left a reply on Using Phpunit/ Why Phpunit Removes All Data In My Database

@ABDULJAKUL-SALSALANI - The RefreshDatabase Trait will reset the database after every test. If you have configured a InMemory Database this runs artican migrate which you can see in the source

It would be worth making sure that your tests are picking up the correct settings from phpunit.xml by creating a new temporary test and dumping the configuration settings to make sure they match

dump(env("DB_CONNECTION"));
dump(env("DB_DATABASE"));

D9705996 left a reply on Using Phpunit/ Why Phpunit Removes All Data In My Database

If you have added this to your phpunit.xml then phpunit will use an in-memory database for your tests.

<env name="DB_CONNECTION" value="sqlite"/>
<env name="DB_DATABASE" value=":memory:"/>

Is you problem that when you run your tests you data in your non-test database is removed as this shouldn't happen with the setup above unless you are overriding anything within Laravel e.g. separate database connections on you eloquent models.

If this is still a problem I would find a test that is causing your data to be removed and work through exactly what that test is doing and the application code it is calling to figure out a bit more detail about why your data is being removed.

09 Jan
1 week ago

D9705996 left a reply on Laravel Working With Money

First thing, dont work with decimals when dealing with money e.g. instead of $12.25 store as 1225 cents due to rounding issues

https://martinfowler.com/eaaCatalog/money.html

For the maths I would do

$service = 1225;
$coupon = 25;

$net = $service * ( 100 - $coupon) / 100;

Gives 918.75 cents or round up to $9.19.

D9705996 left a reply on Problem With Laravel Telescope.

In the phpunit.xml add the following with your other env variables.

<env name="TELESCOPE_ENABLE" value="false"/>

This will disabld telescope shen testing see

https://github.com/laravel/telescope/issues/347

D9705996 left a reply on View Taking Way Too Long To Render As Text/xml

@FLYINGGHOTI - Awesome. Glad you got your issue fixed. If you could please mark the discussion as solved that would be great.

D9705996 left a reply on Overwrite Passport Keys Creation Location?

Why do you want to do this?

I had a look at the source code and the Passport class has a public keyPath property that is used to determine where to store the keys. However I dont see how you would go setting the path

There is a way go load thd keys from another location so might need to manually move the keys

Passport::loadKeysFrom('/var/http/path/to/files');

To be honest I would leave as is unless you have a deal breaker reason to change

D9705996 left a reply on Bug Fix/Extend Laravel 5.3 "custom" Project

@OVERTHANE - I had a look at your github repo and I have the following starters advice

  1. For each of your issue create a test to prove that you can reproduce the issue. Then fix it and close the issue I know you have been asked not to but you dont want to accidentally break it again later you can then be sure forever that this bit of your codd work

  2. Havd a look at https://guides.github.com/activities/hello-world/ about creating branches/ merge requests. Really useful for tracking the changes you make for each issue in isolation and let's you review in the future, it's also how anyone else can contribute to your project (e.g. if I wanted to fix an issue for you I could create a copy of your repo, make the changes and then create a merge request that you could approve, reject, discuss)

  3. Your routes dont follow restful convention e.g. using post routes to delete things. Not an issue as such but sticking to a convention helps readability https://laravel.com/docs/5.7/controllers#resource-controllers

  4. Your models are using a weird hybrid of raw SQL and query builder for no obvious reason. A lot of the code could be simplified with eloquent - https://laravel.com/docs/5.7/eloquent

  5. Your controllers have validation logic all over the place and is pretty bespoke. Look at form requests as they can do z lot of the heavy lifting for you in a centralised place. https://laravel.com/docs/5.7/validation#form-request-validation

  6. Authentication is being performed in your controller routes with repeated code. You can use the auth middleware to remove this and use policies for your authorization. https://laravel.com/docs/5.7/authorization

  7. Ids are being passed as request parameters. Look at route model binding to automatically get model by its id - https://laravel.com/docs/5.7/routing#route-model-binding

I know you aren't really in a position to refactorwrite tests so you might have to keep going with what you've got but I would try chipping away at some of the code if you can as it will get easier and the above are the quickest wins IMO but I feel for you as you have inherited an absolute beast

Good luck

D9705996 left a reply on Bug Fix/Extend Laravel 5.3 "custom" Project

@OVERTHANE - > Unfortunately my employer, upon knowing that I was performing tests careful and properly, ordered me to skip testing suites and attempt to apply the fixes directly to the code.

WOW. I know from previous experience the world of pain you will end up in without a test suite. A small seemingly innocuous change breaks core functionality, you have a fear of change as you dont have confidence to make changes xo everything takes many times more, debugging problems is a nightmare as the breaking change might have been months ago.

For your own sanity if nothing else I would continue testing as much as you can without compromising your employers delivery dates.

It's easier to ask for forgiveness than permission!!!

If you want a good reference book I highly recommend refactoring by Martin Fowler. I have 1st edition which is java orientated bug still relevant but link is for the new one which is javascript

D9705996 left a reply on Existing Dynamic Form Builder Library?

@NULLREFERENCE - No problem - If the links helps solve your issue can you please mark the discussion as resolved.

D9705996 left a reply on Laravel HTTP Tests

@DANYAL14 - Ok I have had a chance to test my last response and it doesn't work. Looking at this seems to suggest that Laravel intercepts the HTTP requests and handles them internally, which I suppose makes sense as HTTP tests work without needing to have a web server running.

If you still need to query an external site you can do this but you wont be able to use the in-built framework helpers and assertions. You will need to install an HTTP client like Guzzle and then you can write your tests to actually hit the API as per the below test class that tests a response from google contains the text Google.

<?php

namespace Tests\Feature;

use Tests\TestCase;
use GuzzleHttp\Client;
use Symfony\Component\HttpFoundation\Response;

class ExternalUrlTest extends TestCase
{
    protected $client;

    public function setUp()
    {
        $this->client = new Client();
        parent::setUp();
    }

    public function testExternalUrl()
    {
        $response = $this->client->get('https://www.google.co.uk');

        $this->assertEquals(Response::HTTP_OK, $response->getStatusCode());
        $this->assertContains('Google', $response->getBody()->getContents());
    }
}

If I run these tests I get

PHPUnit 7.5.1 by Sebastian Bergmann and contributors.


 ==> Tests\Feature\ExternalTest                   ✓

Time: 1.32 seconds, Memory: 20.00MB

However if I change the assertContains to somethign that doesn;t exist the error message isn't very helpful

PHPUnit 7.5.1 by Sebastian Bergmann and contributors.


 ==> Tests\Feature\ExternalTest                   ✖

Time: 1.58 seconds, Memory: 20.00MB

✖ There was 1 failure:

1) Tests\Feature\ExternalTest::testExternalUrl
sprintf(): Too few arguments

To be honest I would look at testing your http://www.danyal.dk API separately as doing so through this method is goign to be a PITA

08 Jan
1 week ago

D9705996 left a reply on Existing Dynamic Form Builder Library?

I've not seen any specific packages but you might want go look at this for inspiration

https://github.com/jringeisen/laravel-vue-formbuilder

D9705996 left a reply on Queued Jobs And Withoutoverlapping

Have a look at setting expirations on your jobs

https://laravel.com/docs/5.7/queues#max-job-attempts-and-timeout

You should just need to add this function to your job. Amend the contents with you specific needs for when jobs should timeout.

public function retryUntil()
{
    return now()->addSeconds(5);
}