richard

Member Since 4 Years Ago

Nairobi

Software Developer at Nairobi, Kenya

Experience Points 73,080
Experience Level 15

1,920 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 473
Lessons
Completed
Best Reply Awards 30
Best Reply
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.

22 Mar
2 days ago

richard left a reply on How To Validate Two User Record In One Table

You can do this


    public function store(Request $request)
    {
        $data = $this->validate($request, [
            'product_name.*' => [
                'required',
                Rule::unique('products', 'product_name'))->where(function ($query) {
                    return $query->whereUserId(auth()->id);
                }),
            ],
            'other_attributes' => 'required|other_rules'
        ]);

        ...
}

richard left a reply on Why Do I Need To Use Extends Contoller?

The base controller comes with traits such as AuthorizesRequests, DispatchesJobs, ValidatesRequests which brings in more functionality into your controllers. For example, ValidatesRequests allows you to validate request like this:


$this->validate($request, [..rules here..]);

But it is entire optional to extend the Controller class.

richard left a reply on Ajax Incomplete Request Making

Show us the code making the Ajax call

20 Mar
4 days ago

richard left a reply on Helper Function Not Working Within My Package

Yeah, as @tykus has mentioned, you need to provide the full path. "src/Helpers/helper.php". Remember to run the composer dumpautoload thereafter.

richard left a reply on Can I Use Model Function Or Relationship Inside Eloquent?

You can do this in one simple method without the total_cost() method.


$orders = Order::all()->filter(function($order){
    return $order->ceremonies->sum('budget') > request('input');
});

richard left a reply on Helper Function Not Working Within My Package

Hmm. Is the path correct? Confirm it is not in app/Helpers/helper.php

richard left a reply on Helper Function Not Working Within My Package

You need to runcomposer dump-autoload

richard left a reply on Nova Custom Path

That is weird. Do you have /admin path on your routes/web.php file?

richard left a reply on Yajra Get Name Field From Another Table Using Foreign Key Stored In Main Table

You need to eager-load the manufacturers alongside car models

ublic function datatables()
    {
        $datatables = datatables(CarModels::with('manufacturer')->query()) // Set a CarModel belongs to manufacturer relationship
            ->editColumn('actions', function ($car_models) {
                return view('admin.car_models.datatables.actions', compact('car_models'));
            })
            ->rawColumns(['actions']);

        return $datatables->toJson();
    }

and then access it in your JavaScript as manufactuer.name

richard left a reply on Laravel Training

hi my name is Richard and I just rebooted my computer successfully.

richard left a reply on Trying To Get Property Of A Non-object In A Middleware

You need to check the user_type only when their is a logged in user like this:

public function handle($request, Closure $next)
    {
        if($request->user() && $request->user()->user_type == 'customer'){
            return $next($request);
        }

        return redirect('/')->with('error', 'You have not customer access');
    }

richard left a reply on Empty Variable Check In Blade File

Ok. What are you trying to achieve in those if statements?

richard left a reply on Uncaught Error: Syntax Error, Unrecognized Expression:

What do you get with

stop: function () 
            {
              $('.sortable_lessons > li').each(function (i) {
        console.log(module_id)
                // $(this).find('#module_counter_' + module_id).html(i + 1);
              });
            }

richard left a reply on Empty Variable Check In Blade File

What are you trying to achieve in those if statements? Do you mean there are students who do not have names? :)

First of all, you need to do @foreach($students as $student) and not the other way round.

19 Mar
5 days ago

richard left a reply on I Want Query Laravel Model Please

Sure, go ahead and query it. No worries

I want query laravel Model please

18 Mar
6 days ago

richard left a reply on Route Group Prefix No Working

Show us the entire routes/web.php file.

richard left a reply on Chat System - Laravel , Redis And Socket.io

Forget about socket.io and other 3rd party services. Check this awesome solution by Beyond Code and Spatie https://docs.beyondco.de/laravel-websockets/

richard left a reply on Route Group Prefix No Working

There is no way accessing let's say yourapp.test/admin/dashboard will output such an error. Maybe you have hit the wrong route while testing.

richard left a reply on SQLSTATE[23000]: Integrity Constraint Violation

On your database config file, under MySQL change strict to false.

'strict' => false,

15 Mar
1 week ago

richard left a reply on Accessing Token Based API Route Via Vue/Axios

I'd save the token to the local storage when the user logins and loads the page for the first time. Thereafter I will retrieve the token and pass it to axios on the subsequent API request.

richard left a reply on Check If Polymorphic Relation Exists Returns Empty

When you delete a company or a scooter, simply delete the associated notification. I think that solves the problem.

So basically are available notifications have existing companies/scooter

richard left a reply on How To Sum Values Of Duplicate ID's

This is how I'd do. I don't know your use case, but this will give you a hint

class ActivityPoint extends Model
{
    
}

class User extends Model
{
    public function points()
    {
        return $this->hasMany(ActivityPoint)
    }

    public function totalPoints()
    {
        return $this->points->sum('points');
    }
}
// Collection of users
$users = User::all();

foreach($users as $user)
{
    echo $user->name . " has " . $user->totalPoints() . " points."
}

// Single User
$user = User::findOrFail(1);
echo $user->name . " has " . $user->totalPoints() . " points."

richard left a reply on How To Sum Values Of Duplicate ID's

Do you want a Collection of users or just 1 user?


$user = App\User::findOrFail(id_of_that_particular_user);

$points = ActivityPoint::where('points', $reports->points)->where('user_id', $user->id)->sum('points');
13 Mar
1 week ago

richard left a reply on Forge's Db.sh.swp File

I already deleted it. Thanks

10 Mar
2 weeks ago

richard started a new conversation Forge's Db.sh.swp File

There is this file .db.sh.swp which is taking crazy space on my /home/forge folder?

What is its purpose and can I delete it?

forge

richard started a new conversation Forge's .db.sh.swap File

There is this file .db.sh.swap which is taking crazy space on my /home/forge folder?

What is its purpose and can I delete it?

forge

23 Feb
1 month ago

richard started a new conversation Attaching A Resource With BelongsToMany

I have 2 models (JobAdvert and Category) with a BelongsToMany relationship. I have added an Actionable trait to both models to record the actions. When I attach a model on the other resource it doesn't record any action. It records only when you detach the resource.

For example, I have attached 4 categories and detached 1. Only detach is recorded in the actions.

Is this an expected behavior or a bug?

nova

07 Feb
1 month ago

richard started a new conversation Display Timestamps For PODCASTS

Thanks for the great Work, Jeff.

I think it'd be great to display the time the podcasts were added/uploaded.

They look just odd without the timestamps.

04 Jan
2 months ago

richard left a reply on Return Items Separated Out By Date

Try this

@foreach ($latest as $date => $product)

//output the product details

@endforeach

16 Nov
4 months ago

richard left a reply on Nova Support

@mick79 Maybe you can try something like this

$builder = User::query()->whereHas('orders', function($query) use(date1, date2){
    // your logic to count the number of orders per given period of time
    $query->whereBetween('created_at', [$date1, $date2]);
});

return $this->countByDays($request, $builder);
13 Nov
4 months ago

richard left a reply on Nova Support

What's the challenge you are having? Maybe members of this forum might be in a position to fix your problem

09 Nov
4 months ago

richard started a new conversation Generate Table Of Contents Using Dompdf/dompdf Library

I want to generate a table of contents using dompdf library. I have found this code and it seems not to function as expected.

Has someone encountered this problem before?

25 Oct
4 months ago

richard left a reply on Mapping Values In A Multi Dimensional Array

I have managed to get the code working, but it is very ugly :(

$map = $mappings->map(function($v) use ($items) {
        if(is_array($v)) {
            return collect($v)->map(function($v) use ($items){
                if(is_array($v)) {
                    return [
                        'code' =>  $v['code'],
                        'label' =>  $v['label'],
                        'amount' =>  $items->filter(function($i) use ($v){ return starts_with($i->code, $v['code']);  })->sum('amount'),
                        'nodes' => collect($v['nodes'])->map(function($v) use ($items){
                            if(is_array($v)) {
                                return [
                                    'code' =>  $v['code'],
                                    'label' =>  $v['label'],
                                    'amount' =>  $items->filter(function($i) use ($v){ return starts_with($i->code, $v['code']);  })->sum('amount'),
                                    'nodes' => collect($v['nodes'])->map(function($v) use ($items){
                                
                                        if(is_array($v)) {
                                            return [
                                                'code' =>  $v['code'],
                                                'label' =>  $v['label'],
                                                'amount' =>  $items->where('code', $v['code'])->sum('amount'),
                                            ];
                                        }
                                        return $v;
                                    
                                    })
                                ];
                            }
                            return $v;
                        })
                    ];
                }
                return $v;
            });
        }
        return $v;
    });

Can anyone refactor it using some magic array_walk_recursive. I will appreciate

tip: The code should work with any depth of nested array. Mine is fixed to a certain depth

richard started a new conversation Mapping Values In A Multi Dimensional Array

I have this array

$array = [
            'code' => '',
            'label' => 'Assets',
            'nodes' => [
                [
                    'code' => '1.1.2',
                    'label' => 'Current Assets',
                    'amount' => 0.00,
                    'nodes' => [
                        [
                            'code' => '1.1.2.230',
                            'label' => 'Cash and cash equivalents',
                            'amount' => 0.00,
                            'nodes' => [
                                [
                                    'code' => '1.1.2.230.1',
                                    'label' => 'Bank Balances',
                                    'amount' => 0.00,
                                ],
                                [
                                    'code' => '1.1.2.230.2',
                                    'label' => 'Cash in hand',
                                    'amount' => 0.00,
                                ],
                            ],
                        ],
                    ],
                ],
            ],
        ];

and I would like to update the amount based on the data from a table. The amount is basically the sum of all entries grouped by the code number. The parent's amount can be calculated based on the code. (e.g The total current assets amount will be the sum of all entries that has the code starting with 1.1.2, and so on)

My question, when I do this I get an error Trying to get property 'code' of non-object


$newArray = collect($array)->map(function($m) {
        [
            'code' => $m->code,
            'label' => $m->label,
            'amount' => 1.00, // for testing
            'nodes' => $m->nodes,
        ];
    });

How can I fix this?

21 Oct
5 months ago

richard left a reply on Updating A Product Fails

You need to pass a _method called PUT or PATCH.

Like this

    <form method="post" action="{{action('[email protected]', $id)}}">
        @csrf
    @method('PUT')
22 Aug
7 months ago

richard left a reply on How To Use Npm Package After Install Into Laravel

@topvillas I guess @zzfortezz meant he wants to use it WITH Laravel.

24 Jun
9 months ago

richard started a new conversation Vagrant SSH Issue On Laravel Homestead

I am facing a challenging configuring laravel/homestead. I am stuck at vagrant ssh authentication issue. I have googled around but I cannot fix it. I have tried all the answers in this thread https://stackoverflow.com/questions/22922891/vagrant-ssh-authentication-failure/23554973 but I am unsucessful. I'm running Box v6.0.1, Vagrant 2.1.1 and Homestead v7.8.0.

I would mind someone help me via Teamviewer pls

13 Jun
9 months ago

richard started a new conversation Sync Data In Polymorphic Relationship

I have 3 tables.

#statuses
- id
- name

# stageable
- id
- client_file_id
- status_id
-stageable_id
-stageable_type

#modules
- id
- name

The Modules are 'stageable' meaning they can statuses like Not Started, Completed, etc

I have the following code in models

<?php

namespace App;

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

    public function status()
    {
        return $this->morphToMany(Status::class, 'stageable')->withTimestamps();
    }

}

I want to save the model status.

I have tried


$module->status()->sync(new Status([
     'client_file_id' => 1
]));

I get the error from DB that client_file_id cannot be null.

Any idea how to sync the data? I don't want to manually attach and detach them.

02 Feb
1 year ago

richard left a reply on Taylor Otwell Cancelled My Account Without Asking Me

@JeffreyWay May really need to customize his script to delete all the junk content on this forum.

08 Jan
1 year ago

richard left a reply on Getting Bad Gateway

Where are you getting it? Inside your house? In your car?

28 Dec
1 year ago

richard left a reply on Call Function From Parent Template In Vue.js

Hi AFOYSAL,

You were almost there.

In Vue, the parent-child component relationship can be summarized as props down, events up. The parent passes data down to the child via props, and the child sends messages to the parent via events. Read more from the official documentation

Check this fiddle for the solution.

04 Dec
1 year ago

richard left a reply on Seed Error In Laravel 5.5

Share your Address model

30 Nov
1 year ago

richard left a reply on Listing Grouped Data In Table Rows

Found a solution.


new Vue({
  el: "#app",
  data:{
    users: [
      {country: 'USA', name: 'Taylor'},
      {country: 'UK', name: 'Tony'},
      {country: 'USA', name: 'Mary'},
      {country: 'JAPAN', name: 'Jane'},
      {country: 'JAPAN', name: 'Moses'},
      // More users from different countries in the world
    ]
  },
  computed:{
    byCountry(){
      return this.users.reduce((acc, user) => {
        (acc[user.country] = acc[user.country] || []).push(user.name)
        return acc
      }, {})
    }
  }
})
<div id="app">
  <table>
    <tr>
        <th>Country</th>
        <th>User</th>
    </tr>
    <template v-for="people, country in byCountry">
      <tr>
        <td colspan="2">{{country}}</td>
      </tr>
      <tr v-for="person in people">
        <td></td>
        <td>{{person}}</td>
      </tr>
    </template>    
  </table>
</div>

richard left a reply on Create Model For Existing Table

Depends on what you want to do with the data. You may want to custom setters and getters, add relationships, etc. It all depends on your workflow mate....

richard left a reply on Adding Users Count To Team In Vue

Please share some code so that we can see how you are doing it