automica

Building APIs at Bristol

Member Since 2 Years Ago

Bristol

Experience Points
136,650
Total
Experience

3,350 experience to go until the next level!

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

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

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

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

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

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

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    Laracasts Evangelist

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

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

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

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

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

Level 28
136,650 XP
Sep
25
9 hours ago
Activity icon

Replied to General Advice >Database Management System & Hosting Server

@gillesdeb when you write code, you should develop it on an environment as close to your live environment as possible.

local development is often done using a stack of PHP, Apache & MySQL, (or sometimes PHP, NGINX, MariaDB) Whether you install those natively (as you describe 'using Terminal to host a server') or via MAMP it amounts to the same thing.

The issue with installing this locally is matching and locking your versions to match those of your remote. Eg you could be running PHP 7.4 locally and publish up to PHP 7.3 which could mean stuff doesn't work. Likewise you might have MySQL 5 locally and MySQL 8 on your remote.

To that ends, you can locally develop using virtual machines or docker instances. This allows you to lock versions in config and also run different versions of php / MySQL etc to your native installed versions and provides more consistency and reliability. You can also see performance improvements as you get less issues with DNS and memory usage.

I would recommend looking at homestead which uses vagrant https://laravel.com/docs/8.x/homestead

and https://github.com/sinnbeck/laravel-served for docker.

@sinnbeck is very active on laracasts and you'll see a number of threads explaining about the package here.

Activity icon

Replied to GET Method Is Not Supported For Homepage

@sinnbeck so optimize fills the caches, and optimize:clear unfills everything. got it.

Activity icon

Replied to GET Method Is Not Supported For Homepage

@sinnbeck I thought that optimize had been deprecated in Laravel 5.5 and removed in 5.6?

https://laravel-news.com/laravel-5-6-removes-artisan-optimize

anyway it is still available. You also can call it without the :clear

php artisan optimize
Activity icon

Replied to Laravel Project Using Onion Architecture

@krishbala96 I've not heard of 'onion architecture'. do you have a link to describe that?

Activity icon

Replied to Best Laravel Version To Know ?

@youssefboudaya the best one to learn is all of them :P

if you are coming from Laravel 5.4 then you'll benefit from learning whats changed since then.

follow these series in order for that.

Activity icon

Replied to GET Method Is Not Supported For Homepage

@aavinseth do you need to run 'route:cache' in dev?

if you clear cache

php artisan config:clear

does your get work?

Activity icon

Awarded Best Reply on Any Idea How I Can Refactor This ? What Is Best Practice ?

@Moktar

I would recommend looking at https://williamdurand.fr/2013/06/03/object-calisthenics/

which introduced me to these 9 rules:

  • Only One Level Of Indentation Per Method
  • Don’t Use The ELSE Keyword
  • Wrap All Primitives And Strings
  • First Class Collections
  • One Dot Per Line
  • Don’t Abbreviate
  • Keep All Entities Small
  • No Classes With More Than Two Instance Variables
  • No Getters/Setters/Properties

I think most significant for me was levels of indentation, avoiding else and not abbreviating.

I had a go at a refactor too:

if ($event->isHoliday()) {
    $event->resetEmployeeBalance($this->getCommand($status));
};

with a private method to get the command

and then refactor as @sinnbeck suggested.

so perhaps:


function doSomethingWithEvent($event, $status)
{
    if ($event->isHoliday()) {
        $event->resetEmployeeBalance($this->getReason($status));
    };
};


public function getReason($event, $status)
{
    if ($this->eventIsRejected($event, $status)) {
        return 'keep_balance';
    }
    if ($this->eventIsAccepted($event, $status)) {
        return 'take_balance';
    };

    return null;
}

/**
 * @param $event
 * @param $status
 * @return bool
 */
public function eventIsAccepted($event, $status):bool
{
    return $status === $event::ACCEPTED && !$event->approved_by == null;
}

/**
 * @param $event
 * @param $status
 * @return bool
 */
public function eventIsRejected($event, string $status): bool
{
    return $status === $event::REJECTED;
}
Activity icon

Replied to Deleting From A Json File

@laracoft you don't need the else here either:

    if(!isset($array[$product][$category])){
        throw new \Exception("Can't delete non-exists [$product][$category]");
    }
    else
    {
        unset($array[$product][$category]);
    }

if it throws an exception its not going to execute any more code.

hence why I did

    if(!isset($array[$product][$category])){
        throw new \Exception("Can't delete non-exists [$product][$category]");
    }

    unset($array[$product][$category]);
Activity icon

Replied to Change Logo Jet Stream

@gianmarx the blade files for those lives in

  • resources/views/vendor/jetstream/components/application-logo.blade.php
  • resources/views/vendor/jetstream/components/authentication-card-logo.blade.php
  • resources/views/vendor/jetstream/components/application-mark.blade.php

you can edit and either swap out the svg for another svg or add an image if you want to do that instead.

see https://jetstream.laravel.com/1.x/installation.html#application-logo

Activity icon

Replied to Deleting From A Json File

@laracoft you still need to check you've got the key before deleting

if(!isset($json[$product][$category])){
 throw new \Exception('cant delete');
}

also, as above, when you do this:

  $json = json_decode($file, true);

the variable isn't json any more. In your case its an array so should be named as such. it would be better described as what the data represents, not the its type. eg $data or $products.

Activity icon

Awarded Best Reply on How To Fade In A Div On My Website In 2 Seconds

@lilo

add this:

$('.nav-container').hide();
setTimeout(function() {
   $('#loader').hide();
   $('.nav-container').fadeIn('fast');
}, 5000);

you should also add the following to your css, to hide your container initially, otherwise you'll briefly see the content before the js loads

.nav-container {
display: none;
}
Activity icon

Replied to ErrorException (E_ERROR) Undefined Variable: AttributeValues (View: C:\wamp\www\site\resources\views\site\pages\products.blade.php) And BadMethodCallException

@nacha

There isn't anything obvious in your blade regarding the $attributeValues error.

regarding FilterAttributeValues.php though

 public function __invoke(Builder $query, $value, string $property) : Builder
    {
        return $query->whereHas('attribute_values', function ($query) use ($value) {
            if (is_array($value)) {
                return $query->whereIn('value', $value);
            }

            return $query->where('value', $value);
        });
    }

your whereHas should be using the relationship 'attributeValues'

can you post the stack track for those errors, which should be in your logs.

Activity icon

Replied to Having Several Repositories Attached A Controller

@rffred if your issue with datatables is that it loads a load of data before doing the pagination in the blade (as js) then you'd be worth looking at how livewire does it.

see https://laracasts.com/series/livewire-basics/episodes/6

livewire uses standard Laravel pagination so would render a table much quicker than your 15s benchmark.

Activity icon

Replied to How To Fade In A Div On My Website In 2 Seconds

@lilo

add this:

$('.nav-container').hide();
setTimeout(function() {
   $('#loader').hide();
   $('.nav-container').fadeIn('fast');
}, 5000);

you should also add the following to your css, to hide your container initially, otherwise you'll briefly see the content before the js loads

.nav-container {
display: none;
}
Activity icon

Replied to Deleting From A Json File

@shiva did you solve this?

Sep
24
1 day ago
Activity icon

Awarded Best Reply on CONFUSED ABOUT NODE JS AND PHP.

@dev-rohit I'd suggest you only need to know enough node.js to be able to install and configure node packages.

providing you can install node.js and npm i don't think theres much more you need at this point. If you are writing backend apps in Laravel even that isn't necessary.

Activity icon

Replied to Php Artisan Tinker Throws Parse Error (unexpected T_PAAMAYIM_NEKUDOTAYIM)

@bahjaat have you checked that package’s GitHub page for any issues with the version of Laravel you are running?

I would also check through any recent code changes you’ve made In your application, back to the last time you last ran tinker

Activity icon

Replied to Store Value Globally In Controller

@msslgomez session expiry time is stated is in seconds. So your 36000 is 10 hours (60x60x10)

Your session wouldn’t be very much use if it expired in 36 seconds.

Activity icon

Replied to Laravel From Scratch For Laravel 8

@jwburkhard It’s definitely worth going through if you are new to Laravel.

Also be sure to check the various ‘what’s new in’ series which cover the changes since Laravel 6 and those covering Livewire & Tailwind.

Activity icon

Awarded Best Reply on Linking Table

@ev-genius a note in your link table. Laravel convention recommends not using plurals and putting model names in alphabetical order so ‘programs_exercises’ would be ‘exercise_program’. This will allow you to drop the additional key names on your belongsToMany relationships and reduce some complexity,

To get the extra values off your pivot table you should just specify pivot fields like

return $this->belongsToMany('Role')->withPivot('foo', 'bar');

Activity icon

Replied to Any Idea How I Can Refactor This ? What Is Best Practice ?

@Moktar

I would recommend looking at https://williamdurand.fr/2013/06/03/object-calisthenics/

which introduced me to these 9 rules:

  • Only One Level Of Indentation Per Method
  • Don’t Use The ELSE Keyword
  • Wrap All Primitives And Strings
  • First Class Collections
  • One Dot Per Line
  • Don’t Abbreviate
  • Keep All Entities Small
  • No Classes With More Than Two Instance Variables
  • No Getters/Setters/Properties

I think most significant for me was levels of indentation, avoiding else and not abbreviating.

I had a go at a refactor too:

if ($event->isHoliday()) {
    $event->resetEmployeeBalance($this->getCommand($status));
};

with a private method to get the command

and then refactor as @sinnbeck suggested.

so perhaps:


function doSomethingWithEvent($event, $status)
{
    if ($event->isHoliday()) {
        $event->resetEmployeeBalance($this->getReason($status));
    };
};


public function getReason($event, $status)
{
    if ($this->eventIsRejected($event, $status)) {
        return 'keep_balance';
    }
    if ($this->eventIsAccepted($event, $status)) {
        return 'take_balance';
    };

    return null;
}

/**
 * @param $event
 * @param $status
 * @return bool
 */
public function eventIsAccepted($event, $status):bool
{
    return $status === $event::ACCEPTED && !$event->approved_by == null;
}

/**
 * @param $event
 * @param $status
 * @return bool
 */
public function eventIsRejected($event, string $status): bool
{
    return $status === $event::REJECTED;
}
Activity icon

Replied to LARAVEL INSTALLATION > New Day > New Topic > New Question

@gillesdeb I've never had any joy with system wide installation of Laravel on my mac so I've always done it on a project per project basis with

composer create-project --prefer-dist laravel/laravel myprojectname
Activity icon

Replied to Php Artisan Tinker Throws Parse Error (unexpected T_PAAMAYIM_NEKUDOTAYIM)

@bahjaat you might also be worth clearing your composer cache

composer clearcache

delete your vendor packages, and then run

composer install

that will download brand new copies of your vendor packages rather than loading them from the cache again. That should resolve any issue with the vendor packages.

Activity icon

Replied to Php Artisan Tinker Throws Parse Error (unexpected T_PAAMAYIM_NEKUDOTAYIM)

@bahjaat if you run your application, do you get any errors then?

Activity icon

Replied to Products Related To Categories, But How

@msslgomez i used to sweat on the pluralization but then when using singular it made more sense as the join table is the connective tissue between 2 singular models.

You can of course call the table whatever you like. I'm happy with convention as it means you don't need to specify the table name in your belongsToMany relationship.

Activity icon

Replied to Calculate In View Elapsed Time In Second

@gianmarx its less good, as its more prone to be broken and if you need to use this value elsewhere then you are duplicating code.

Using an Accessor is much DRY'er (DRY = Don't Repeat Yourself).

see https://laravel.com/docs/8.x/eloquent-mutators

Activity icon

Replied to Calculate In View Elapsed Time In Second

@gianmarx yours would also work.

Its best to keep this complexity out of a blade, which is why I've used the getElapsedAttribute accessor on your Poll model.

This way also means you can call it as if it was a field on your model (and helps DRY up your code).

if you do that within the getElapsedAttribute() you can reference

return $this->created_at->floatDiffInSeconds($poll->updated_at);
Activity icon

Replied to Products Related To Categories, But How

@drewdan if you define your relationship between Products and Categories

Product

function categories(){

return $this->belongsToMany(Category::class)
}

and in Category

function products(){

return $this->belongsToMany(Product::class)
}

then you'll be able to get the following

  • all categories this product is in
$product->categories();
  • all products that are in this category.
$category->products();

your relationship has 1 join table between your products & your categories. its not really necessary to make a specific model for this, or define any relationships on that model.

hasManyThrough Eloquent relationship is more complex and uses three database tables.

Upper level table has relationship with many rows of middle level table and middle level table has relationship with many rows of lower level table.

For example, upper level table is shops , middle level table is products and lower level table is orders.

Any shop can have many types of products (electronic, furniture etc). Similarly, products can have more than of one type of order (single order, bulk order etc).

Now, with the use of hasManyThrough() function, we can fetch the records of lower level table orders with model of upper level table shops.

Stolen from here: https://demonuts.com/laravel-hasmanythrough/

Activity icon

Replied to Laravel 7 - Blank Page

@fredowd cool. can you mark as solved?

Activity icon

Replied to Php Artisan Tinker Throws Parse Error (unexpected T_PAAMAYIM_NEKUDOTAYIM)

@bahjaat

T_PAAMAYIM_NEKUDOTAYIM error often relates to a missing double colon or double quote.

::

do you have the rest of what is on line 1 in your error. Is there more of an error in your logs?

Activity icon

Awarded Best Reply on How To Fix Message: "Undefined Index: Product_id"

@nuna then your data2 array doesn't have the 'product_id' in it, which is what your error is telling you.

in that case,

  foreach ($data2 as $value) {
            $data2['product_assigned'][] = getProductName($data2['store_id'], $value);
        };
Activity icon

Replied to How To Fix Message: "Undefined Index: Product_id"

@nuna then your data2 array doesn't have the 'product_id' in it, which is what your error is telling you.

in that case,

  foreach ($data2 as $value) {
            $data2['product_assigned'][] = getProductName($data2['store_id'], $value);
        };
Activity icon

Replied to How To Fade In A Div On My Website In 2 Seconds

@lilo your method tells the loader to fade out immediately and then you leave it for 5s before fading in the content.

if you use

setTimeout(function() {
   $('#loader').hide();
   $('.nav-container').fadeIn('fast');
}, 5000);

you'll see the loader for 5 seconds, and then the timeout will trigger which will hide loader and then fadeIn your nav-container.

Activity icon

Replied to How To Fix Message: "Undefined Index: Product_id"

@nuna what does a dump of $data2 look like, if you dump after

$data2 = $request->except('_token', 'id');

Activity icon

Awarded Best Reply on OnDelete('cascade') Means...

@romain

DELETE CASCADE: When we create a foreign key using this option, it deletes the referencing rows in the child table when the referenced row is deleted in the parent table which has a primary key.

so if we delete user, any rows in other tables referencing user will also get deleted.

which means you are correct in your meaning.

Activity icon

Replied to How To Fix Message: "Undefined Index: Product_id"

@nuna does your error give you a line number where its erroring?

also it looks like you should be calling:

$this->getProductName($data2['store_id'], $value);

not

getProductName($data2['store_id'], $value);

inside your loop, assuming your getProductName method is in the same class as 'postAssignProduct' method.

Activity icon

Replied to OnDelete('cascade') Means...

@romain

DELETE CASCADE: When we create a foreign key using this option, it deletes the referencing rows in the child table when the referenced row is deleted in the parent table which has a primary key.

so if we delete user, any rows in other tables referencing user will also get deleted.

which means you are correct in your meaning.

Activity icon

Replied to Migrations Taking Too Long Time

Speed will depend on dev environment though. I've found running queries against native MySQL on my mac is slower than doing the equivalent in Homestead.

Sometimes I've even ran the query of remote dev box and then copied back the modified database.

I've heard terrible things about doing this native on windows too.

Activity icon

Replied to Migrations Taking Too Long Time

@newbie360 @erikwestlund i was going to say, 1M is a lot of data for dev. I'd be inclined to stick working with faker seeded data locally.

Activity icon

Replied to CONFUSED ABOUT NODE JS AND PHP.

@dev-rohit I'd suggest you only need to know enough node.js to be able to install and configure node packages.

providing you can install node.js and npm i don't think theres much more you need at this point. If you are writing backend apps in Laravel even that isn't necessary.

Activity icon

Replied to Migrations Taking Too Long Time

@shineraj are you migrating and then reseeding?

also how have are you running your dev environment? using native php / MySQL or docker / homestead? mac or pc?

Activity icon

Replied to Migrations Taking Too Long Time

@shineraj is this a migration running on a live environment or locally?

Activity icon

Replied to How To Fade In A Div On My Website In 2 Seconds

@lilo

in jQuery the following should do:

setTimeout(function() {
   $('#loader').hide();
   $('.nav-container').fadeIn('fast');
}, 2000);

timeout using milliseconds so 2000 = 2s.

this is a way using css animations:

<html>
<head>
    <style>
        #loader {
            width: 200px;
            margin-left: auto;
            margin-right: auto;
            background: red;
            height: 200px;
            -webkit-animation: fadeout 2s linear forwards;
            animation: fadeout 2s linear forwards;
        }

        .nav-container{
            opacity: 0;
            display: block;
            height: 500px;
            background: blue;
            -webkit-animation: fadein 1s linear forwards;
            animation: fadein 1s linear forwards;
            animation-delay: 2s;
        }

        @-webkit-keyframes fadeout {
            90% {
                opacity: 1;
            }
            99% {
                opacity: 0;
                height: 200px
            }
            100% {
                opacity: 0;
                height: 0
            }
        }

        @keyframes fadeout {
            90% {
                opacity: 1;
            }
            99% {
                opacity: 1;
                height: 200px
            }
            100% {
                opacity: 0;
                height: 0
            }
        }

        @-webkit-keyframes fadein {
            0% {
                opacity: 0;
            }
            100% {
                opacity: 1;
            }
        }

        @keyframes fadein {
            0% {
                opacity: 0;
            }
            100% {
                opacity: 1;
            }
        }
    </style>
</head>
<body>
<div id="loader">
    loader
</div>
<div class="nav-container">
    PAGE CONTENTS
</div>
</body>
</html>
Activity icon

Replied to Calculate In View Elapsed Time In Second

@gianmarx you need to tell Laravel you are dealing with dates:

if you haven't already, add:

$dates = ['created_at','updated_at'];

Then add an accessor to your Poll model.

public function getElapsedAttribute()
{

    $created_at = $this->created_at;
    $updated_at = $this->updated_at;

    return $updated_at->diffInSeconds($created_at);
}

in your blade:

 {{ $poll->elapsed }}

look at carbon docs to modify to get the granularity you want. https://carbon.nesbot.com/docs/

if you have a long period between your dates you can do

    $days = $created_at->diffInDays($updated_at);
    $hours = $created_at->diffInHours($updated_at->subDays($days));
    $minutes = $created_at->diffInMinutes($updated_at->subHours($hours));
    $seconds = $created_at->diffInSeconds($updated_at->subMinutes($minutes));

    echo CarbonInterval::days($days)->hours($hours)->minutes($minutes)->seconds($seconds)->forHumans();
Activity icon

Replied to Storage Of Site Wide Configuration

@veleous use an .env if its going to change depending on environment or you can hard code it in its own file in config/ if you aren't planning on changing it. doesn't need to live in a DB table.

So, if you create a file at config/services.php that looks like this:

// config/services.php 

return [ 
    'keys' => 
        [     
            'secret' => '123456' 
        ]
];

you will now have access to that config variable using

config('keys.keys.secret')
Activity icon

Replied to Live Video Streaming

@dinni if you are looking to stream one of your sporting events, you could look at something like

boxcast https://www.boxcast.com/solutions/sports-streaming-services

or mux https://mux.com/live

Activity icon

Replied to Linking Table

@ev-genius great.

your three column join table would work too so update to that if its more value.

Activity icon

Replied to How Can I Add A Question Section In Any Product Pages?

@marionkringalpha have a look at this package for the core functionality you need https://github.com/bpocallaghan/faq

Activity icon

Replied to Linking Table

@ev-genius a note in your link table. Laravel convention recommends not using plurals and putting model names in alphabetical order so ‘programs_exercises’ would be ‘exercise_program’. This will allow you to drop the additional key names on your belongsToMany relationships and reduce some complexity,

To get the extra values off your pivot table you should just specify pivot fields like

return $this->belongsToMany('Role')->withPivot('foo', 'bar');