tokoiwesley

tokoiwesley

Member Since 2 Years Ago

Nairobi

Experience Points 26,720
Experience Level 6

3,280 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 208
Lessons
Completed
Best Reply Awards 8
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.

15 Apr
1 week ago

tokoiwesley left a reply on Laravel Passport Correct Usage

@MIKO55 - You are welcome.

tokoiwesley left a reply on Laravel Passport Correct Usage

@MIKO55 - Yes, it's the solution.

tokoiwesley left a reply on Laravel Passport Correct Usage

Passport::withoutCookieSerialization() instructs Passport to disable cookie serialization.

tokoiwesley left a reply on Laravel Passport Correct Usage

@MIKO55 - You are using Apache so it's possible that the Authorization Header is being blocked by a module in Apache. Some devs who have experienced this issue before recommend adding the following in your .htaccess file;

RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]

Also ensure that the .htaccess file located in the public folder has the following lines;

RewriteCond %{HTTP:Authorization} ^(.+)$
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

tokoiwesley left a reply on Laravel Passport Correct Usage

Could it be an environment setup issue! Which web server and OS are you using?

tokoiwesley left a reply on Laravel Passport Correct Usage

Check whether you have include the CSRF token in your application layout file.

// In your application layout...
<meta name="csrf-token" content="{{ csrf_token() }}">

tokoiwesley left a reply on Laravel Passport Correct Usage

@MIKO55 - What response are you getting?

tokoiwesley left a reply on How To Always Run Multiple Queues At All Time Via Supervisor?

Maybe it's because you are dispatching all the jobs and/or queueable entities in your app to only one queue (the default queue). Is this the case?

14 Apr
1 week ago

tokoiwesley left a reply on Laravel Passport Correct Usage

As I tried to reproduce this issue, I found out was that the X-Requested-With header has already been added in ./resources/js/bootstrap.js. Adding it elsewhere in the code (say app.js) results in the Vue component always returning Unauthenticated. So try deleting the X-Requested-With header addition you made before and test again.

tokoiwesley left a reply on Laravel Passport Correct Usage

@MIKO55 - Well I was assuming you had already run php artisan make:auth! At least you now have the laravel_token cookie, so we can focus on why the Vue component is returning Unauthenticated.

13 Apr
1 week ago

tokoiwesley left a reply on Laravel Passport Correct Usage

@MIKO55 - You seem to be mixing up stuff. After successfully authentication in the Web app, you do not need to manually create a token at all. That's the essence of adding \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class in the web middleware group. It creates the automatically, such that all you need is to make requests to the API endpoints (routes) using axios.

tokoiwesley left a reply on Laravel Passport Correct Usage

@MIKO55 - What tool are you using for your XMLHttpRequests?

10 Apr
1 week ago

tokoiwesley left a reply on Eloquent Methods And Collection Methods

@zaster I have added an edit to my initial reply.

tokoiwesley left a reply on Eloquent Methods And Collection Methods

@SNAPEY - My bad! Thanks for pointing out that mistake.

tokoiwesley left a reply on Displaying Json Encoded Data From A Database Column

Have you tried doing this:

@foreach($property->image as $image)
    echo $image; // http://kizflex.local/properties/11.jpg
    ...
@endforeach

tokoiwesley left a reply on Any Guide Or Chart Library That Allows For Dynamically Updating Chart?

Laracasts' series Real-time Laravel with Socket.io which uses Node, Redis, and Socket.io will be a great place to get you started on the right path to achieving your goal.

09 Apr
1 week ago

tokoiwesley left a reply on Displaying Json Encoded Data From A Database Column

Use the array cast type on your model class so that the json data will be converted to a PHP array when you access it in your app.

tokoiwesley left a reply on Laravel 5.5 PHP Error

It seems like you app is hosted on server with a shared hosting plan. The solution is to get a VPS (from hosting solutions like Digitalocean, Linode, Vultr etc.) which allows for such flexibility - like installing a specific version of PHP.

tokoiwesley left a reply on Would It Be Right To Add .env To .gitignore And Update It Via Vim On The Server?

That is the normal practice and it should be that way. When you start a new Laravel project, .env will already have been added to .gitignore for you.

tokoiwesley left a reply on Eloquent Methods And Collection Methods

They are not the same, however Eloquent collections extend the base Laravel collection object, thus inheriting all the methods provided by the base collection.

When retrieving a record from a table using Eloquent ORM, the resulting object is an Eloquent collection. So you can use Laravel collection methods on Eloquent collections.

tokoiwesley left a reply on Update Model With Dynamic HasMany-relation

I recommend you eliminate the foreach() loops by storing the description as json data. I have illustrated the changes below:

attributes migration:

$table->jsonb('description');

Car model:

public function attribute()
{
    return $this-hasOne(Attribute::class, 'car_id', 'id');
}

Attribute model:

/**
  * The attributes that should be cast to native types.
  *
  * @var array
  */
protected $casts = [
        'description' => 'array',
];

Then I would rewrite the update method like this:

public function update(Request $request)
{
    try {
    $car = Car::findOrFail($request->car_id);
    } catch (ModelNotFoundException $e) {
        // Handle exception
    }

    $car->attribute->update(['description' => $request->input('data.attributes')]);

    $car->update(['title' => $request->input('data.title')]);
}
08 Apr
2 weeks ago

tokoiwesley left a reply on Invalid Credential On Getting Access Token

Add this to your User model:

public function findForPassport($username)
{
    return $this->where('mobile', $username)->first();
}

tokoiwesley left a reply on Laravel Eloquent Followers Relationship

@CALLUMCARLSTROM - I've testes the latest solution by @snapey. It works and is the simplest.

tokoiwesley left a reply on Laravel Eloquent Followers Relationship

@snapey your latest solution removes all the complex stuff from my solution. I didn't know it's possible to use a pivot table joining users table to users table. Thanks!

07 Apr
2 weeks ago

tokoiwesley left a reply on Laravel Eloquent Followers Relationship

@CALLUMCARLSTROM - No it won't restrict. The follower method gives you the follower record that belongs to a given user while the followers method gives you the users following the given user.

06 Apr
2 weeks ago

tokoiwesley left a reply on Laravel Eloquent Followers Relationship

Since each User is basically a Follower (can follow another user) and a User can have multiple followers while at the same a Follwer can follow multiple users, I have a working solution for you that I have tested;

users
    id
    name
    username

followers
    id
    user_id

follower_user
    follower_id
    user_id

The follower_user pivot table migration:

Schema::create('follower_user', function (Blueprint $table) {
    $table->bigInteger('follower_id')->unsigned(); // Assuming you have bigIncrements on followers table
    $table->bigInteger('user_id')->unsigned(); // Assuming you have bigIncrements on users table

    $table->foreign('follower_id')
        ->references('id')
                ->on('followers')
                ->onDelete('cascade');

    $table->foreign('user_id')
                ->references('id')
                ->on('users')
                ->onDelete('cascade');

$table->primary(['follower_id', 'user_id']);
});

Here is how your eloquent relationships will look like;

User model class:

public function follower()
{
    return $this->hasOne(Follower::class, 'user_id', 'id');
}

public function followers()
{
    return $this->belongsToMany(Follower::class);
}

Follower model class:

public function user()
{
    return $belongsTo(User::class, 'user_id', 'id');
}

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

tokoiwesley left a reply on Policies When Using Passport

Ensure that the you have a valid access token when you call the endpoint with that particular middleware declaration.

tokoiwesley left a reply on Composer Keeps Installing Package

What's the name the composer package?

tokoiwesley left a reply on Browser Notifications Without 3rd Party Service

Yes, you will need a socket.io server ([laravel-echo-server]), Redis and a socket.io client that executes in the browser. How to use Laravel with Socket.IO tutorial will get you started on that path.

tokoiwesley left a reply on How To Mail Exceptions

When an exception is thrown, the code following it will not be executed, and PHP will try to find the matching "catch" block. So, your mail statement should fall in the "catch" block. Example:

try {
    $data = $request->validate([
        'client_id' => 'required|integer',
        'first_name' => 'required|string',
        'middle_name' => 'nullable|string',
        'last_name' => 'nullable|string',
        'dob' => 'nullable|string',
    ]);

    $dependent = Dependent::create($data);

    return response($dependent, 201);
} catch(\Exception $e) {
    Mail::to('[email protected]')->send({Exception});

    return response($e->getMessage(), 422);
}

tokoiwesley left a reply on How To Get Auto Increment Value

@SNAPEY - this works but if the user does not create a record , for example he just checks the page, then the system would create a record for him and that record is going to be stored with no data

It makes more sense to create the record and immediately display the ID to the user (on the response) as @cronix suggests. That's what I would go with.

tokoiwesley left a reply on Send Push Notification To Android ?

To achieve this you need a socket.io server (laravel-echo-server) alongside your laravel app and a socket.io client implemented in your android app.

The How to use Laravel with Socket.io tutorial will help set you on the right path with what you are trying to achieve. It doesn't cover mobile apps though, just a web app socket.io client example.

tokoiwesley left a reply on How To Debug A Query

What database are you using? Also, it will be helpful to share the error message in detail - as it appears.

tokoiwesley left a reply on Problem With Notifications.

Check the MentionedInComment class. You must be having somewhere in its code or from a method it uses a dd() statement that returns the html you've shared and halts execution at that point.

tokoiwesley left a reply on Laravel Cross-app Communication

Laravel Passport is the right tool for the job. It is a full OAuth 2.0 server implementation built on top of the League Oauth2 Server. Out of the box you get support for Authorization code grant, Implicit grant, Client credentials grant, Resource owner password credentials grant and Refresh grant.

Apart from monolithic apps, Laravel Passport still works well on a micro-services architecture. All you need is to figure out how to split up your monolithic app such that you end up with one service as the authorization server and the rest of the services as resource servers - thus you will not call the Passport::routes() method within the boot method of the AuthServiceProvider of these resource servers.

tokoiwesley left a reply on Migration Json Field

You have two options to solve this;

  1. Upgrade MariaDB to at least v10.2.7 or a higher version to get JSON data type support.

  2. Use a workaround. Change the json column $table->json('permissions')->nullable() to text...

$table->text('permissions')->nullable();
02 Apr
2 weeks ago

tokoiwesley left a reply on Post Request With Data Causes Cors Issue Even With Middleware

@TRUETAURUS - You are welcome. You can mark this question as solved by indicating the best answer/reply.

29 Mar
3 weeks ago

tokoiwesley left a reply on Post Request With Data Causes Cors Issue Even With Middleware

I'll recommend you use the laravel-cors package to handle CORS headers support in your app. It always works - out of the box - with loose constraints, but allows you to modify the constraints as much as you like.

28 Mar
3 weeks ago

tokoiwesley left a reply on Record The Relationship Between 3 Tables.

You have defined One To Many relationships for your model classes. Why not use Many To Many relationships instead? I think the pivot tables should solve your issue.

tokoiwesley left a reply on Foreign Key Constraint Incorrectly Formed.

What error are you getting?

tokoiwesley left a reply on Post Request With Data Causes Cors Issue Even With Middleware

Try disabling CSRF protection on the api route group in App\Http\Middleware\VerifyCsrfToken

protected $except = [
    'api/*'
];

tokoiwesley left a reply on FormRequest Validation Error In Laravel 5.5

Instaead of using ValidationFormRequest class, you can create a manual validator.

tokoiwesley left a reply on "Personal Access Client Not Found. Please Create One. " In Laravel Passport

Have you run this command in the test environment?

php artisan passport:client --personal

tokoiwesley left a reply on How To Use Auth::user With Postman

APIs use token based authentication. Have you considered using Laravel Passport.

I suggest the use of a Password Grant for what you are trying to implement.

tokoiwesley left a reply on How To Add Admin User In My Application

@BELHEDI - Additionally, you can add your admin user in the migrations (as shown below) such that the user records will always be created when you run the migrations.

The Admin can then reset their password (immediately after all migrations have been run) in a production environment and you are good to go.

CreateUsersTable:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('first_name');
            $table->string('last_name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });

        DB::table('users')->insert([
            'first_name' => 'John',
            'last_name' => 'Doe',
            'email' => '[email protected]',
            'password' => bcrypt('secret'),
        ]);
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

CreateAdminsTable:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateAdminsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('admins', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedInteger('user_id');
            $table->timestamps();
        });

        DB::table('admins')->insert([
            'user_id' => 1,
        ]);
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('admins');
    }
}
27 Mar
3 weeks ago

tokoiwesley left a reply on How To Add Admin User In My Application

You can read more about Eloquent Model relationships here. Below is an example of the four model classes with the respective relationships.

The User model class:

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'first_name', 'last_name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function admin()
    {
        return $this->hasOne(Admin::class, 'user_id', 'id');
    }

    public function teacher()
    {
        return $this->hasOne(Admin::class, 'user_id', 'id');
    }

    public function student()
    {
        return $this->hasOne(Admin::class, 'user_id', 'id');
    }
}

The Admin model class:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Admin extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'user_id', // table columns with admin details
    ];

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }
}

The Teacher model class:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'user_id', // table columns with student details
    ];

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }
}

The Student model class:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Teacher extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'user_id', // table columns with teacher details
    ];

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }
}

tokoiwesley left a reply on How To Add Admin User In My Application

@BELHEDI - Right, am going to give you code snippet examples below...