elo

elo

Member Since 3 Years Ago

Experience Points
5,950
Total
Experience

4,050 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
8
Lessons
Completed
Best Reply Awards
0
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 2
5,950 XP
Sep
21
1 month ago
Activity icon

Replied to Changes To Laravel Resource Not Reflecting

I remembered to run php artisan migrate on the staging and it ran successfully. I have also ran php artisan cache:clear but surprisingly the new property is still not showing on the staging server.

Sep
17
1 month ago
Activity icon

Replied to Changes To Laravel Resource Not Reflecting

I am not using varnish if it's the varnish I am thinking of.

Activity icon

Started a new Conversation Changes To Laravel Resource Not Reflecting

Hey guys, I added a new column rollover to an orders table then added the rollover attribute to OrderResource and nova Order resource. On my development system, I am able to see the new attribute from postman so I have pushed the changes to a staging server.

However I can't see the rollover attribute in the response coming from the staging server but I can see in on staging nova.

I have never experienced anything like this before, it looks like the resource was cached or something. Does anyone know how I can fix this sort of issue?

Sep
06
1 month ago
Activity icon

Started a new Conversation Laravel Vendor Does Not Exist And Could Not Be Created On Mac

I am making a switch from windows to mac, so I installed composer globally and pulled laravel project from github. When I run composer install inside the the laravel project I keep getting a run time exception error

[RuntimeException] /Users/developer/mike/code/laravel/vendor does not exist and could not be created.

Please how do I resolve this so that I can install the project dependencies?

Sep
03
1 month ago
Activity icon

Replied to Unable To Run Migrations On Laravel Homestead

Interesting. So after posting the question I decided to try to restart mysql service, then ran the command php artisan migrate again and I was able to migrate successfully.

Problem solved.

Activity icon

Started a new Conversation Unable To Run Migrations On Laravel Homestead

Hey guys, I just set up laravel homestead and loving every bit of what it offers but I have an issue with running migrations. I was able to create a migration file to add new columns to an existing table using php artisan make:migrate command. But when I run php artisan migrate, I get the feedback

Migrating: 2020_09_03_151654_add_columns_to_transfers_table

And nothing else after that. I even left it to run for over 10mins and it still doens't get migrated or throw an error.

Here's the migration file

<?php

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

class AddColumnsToTransfersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('transfers', function (Blueprint $table) {
            $table->integer('otp')->after('bank_code')->nullable();
            $table->boolean('authorized')->after('otp')->nullable()->default('0');
            $table->string('recipient_code')->after('authorized')->nullable();
            $table->boolean('approval_required')->after('recipient_code')->nullable()->default('0');
            $table->unsignedBigInteger('approved_by')->after('approval_required')->nullable();

            $table->foreign('approved_by')->references('id')->on('users')->onDelete('set null');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('transfers', function (Blueprint $table) {
            //
        });
    }
}

The db connection is fine also since I am able to pull data from it with my controllers. What could be the reason for this?

Aug
09
2 months ago
Activity icon

Replied to Trait 'Spatie\Activitylog\Traits\LogsActivity' Not Found

That worked but I ended up with another error. This time I am not able to add a foreign key to the original table structure

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table activity_log add constraint activity_log_user_id_foreign foreign key (user_id) references users (id) on delete set null)

Thanks

Activity icon

Replied to Trait 'Spatie\Activitylog\Traits\LogsActivity' Not Found

Do I need to run composer install considering that the project is currently running even though its staging? I did that on my development system though then pushed it a bitbucket repo that gets pulled into my staging. So should I run composer install on the staging?

Activity icon

Replied to Trait 'Spatie\Activitylog\Traits\LogsActivity' Not Found

I was able to install the package locally with no issues. I have pushed the code to my staging environment which is on a DigitalOcean droplet. It's on my staging that I am having this issue.

Activity icon

Started a new Conversation Trait 'Spatie\Activitylog\Traits\LogsActivity' Not Found

Hi, I am getting the Trait 'Spatie\Activitylog\Traits\LogsActivity' error when trying to run php artisan migrate command.

The complete error is

PHP Fatal error: Trait 'Spatie\Activitylog\Traits\LogsActivity' not found in /path_to_project/app/User.php on line 29

Here's how I am using the Trait in my User model

namespace App;

// others
use Spatie\Permission\Traits\HasRoles;
use Spatie\Activitylog\Traits\LogsActivity;


class User extends Authenticatable
{
    use HasApiTokens, Notifiable, HasRoles, LogsActivity; // line 29 in actual code

    ...

    protected static $logName = 'User profile';

    protected static $logAttributes = ['*'];

    protected static $logOnlyDirty = true;
 
    public function activityLog()
    {
        return $this->hasMany('App\ActivityLog');
    }

   // other stuff

In other to display user activities in Laravel Nova backend, I created a customer ActivityLog model and copied the contents of Spatie\ActivityLog\Models\Activity into it. The ActivityLog model looks like this

<?php

namespace App;

use Illuminate\Support\Collection;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Support\Arr;
use Illuminate\Database\Eloquent\Model;
use Spatie\Activitylog\Contracts\Activity as ActivityContract;

class ActivityLog extends Model implements ActivityContract
{
    // copied contents from Spatie\Activitylog\Models\Activity here
}

I don't know why I still get this error even after running composer dum-autoload. What have I done wrongly?

Aug
08
2 months ago
Activity icon

Replied to Schedule Task Exist Before Completing Task

Thanks for drawing my attention to eager loading the users at the initial query. Yes I checked before the first task ran and they did meet the condition.

Aug
07
2 months ago
Activity icon

Started a new Conversation Schedule Task Exist Before Completing Task

Hey guys, I have this weird scenario where a scheduled task exist before completing in a laravel 6 project.

My intention is to have a couple of rows updated in my database if certain conditions is met with this code

$schedule->call(function () {

            // get due contributions
            Contribution::where('status', 'due')->chunk(20, function ($dueContributions) {

                foreach ($dueContributions as $contribution) {

                    // get contribution own
                    $user = $contribution->user;

                    // get usr wallet balance
                    $walletBalance = $this->getWalletBalance($user);

                    if ($walletBalance >= $contribution->contribution)
                        $this->autoWalletDebit($contribution, $user, $walletBalance);
                }
            });

            Log::notice('Wallet auto contribution complete.');
        })->everyFiveMinutes()->description('Automatic wallet thrift contribution.');

I noticed from my telescope that the task runs but ends almost immediately. So before running the first time, there were 56 rows that met this condition. After running the first time, only 16 rows were updated, the second time only 7 rows were updated.

I have no clue why this is the case or how else to make it run completely before exisitng. Can anyone tell me why or how to fix it?

Aug
05
2 months ago
Activity icon

Replied to Paginate While Returning Array Of Api Resource Objects To The Resource Collection

Worked for me, many thanks.

I simply chained response()->getData(true) to my collection like this

ModelResource::collection($model)->response()->getData(true)
Jul
16
3 months ago
Activity icon

Replied to Env Config Not Being Read When Schedule Task Runs

Hi @snapey thanks for always answering my questions. I have learnt alot from your answers on my questions and others too. Is it possible to use laravel helpers inside .env files?

Activity icon

Replied to Env Config Not Being Read When Schedule Task Runs

Thanks. That fixed it for me.

Activity icon

Started a new Conversation Env Config Not Being Read When Schedule Task Runs

Hello guys, I want to copy some user data from my laravel application to a google sheet at a particular time. I have added the package https://packagist.org/packages/revolution/laravel-google-sheets to my project. I tested the setup by calling an endpoint and the data was appended to the google sheet.

Since the data I will be copying to sheets will be large and the need to do this at a particular time, I have created a schedule task to handle this process. When I run the task I get an error that the file that stores the credentials does not exist

InvalidArgumentException : file "../storage/credentials.json" does not exist at C:\project_path\vendor\google\apiclient\src\Google\Client.php:928

The file is saved in my storage directory and the path is configured in .env file as GOOGLE_SERVICE_ACCOUNT_JSON_LOCATION=../storage/credentials.json

I need help fixing this as running it via api call will timeout.

Jul
02
3 months ago
Activity icon

Replied to Granting Admin Access To User Dashboard View

Let me give this a try

Activity icon

Started a new Conversation Granting Admin Access To User Dashboard View

Hey guys, I have built an API application using laravel and I am using the route middleware to ensure that an authenticated user is restricted to viewing only their personal dashboard and profile

Route::middleware('auth:api')->group(function () {

    Route::get('dashboard', 'API\[email protected]');

    Route::get('profile', 'API\[email protected]');

});

All works well as intended. However I want to an admin to have access to the user dashboard and profile view as if it's the user who has logged in. I have integrated https://docs.spatie.be/laravel-permission/v3/introduction/ package which I am using to control access on the backend.

How can I go about granting the admin access so that the admin can see exactly what the user is seeing on their dashboard?

Jun
16
4 months ago
Activity icon

Replied to Laravel Nova Access Restriction Vie Gate Does Not Work

Check your APP_ENV value. If it is still set to local the gate will have no effect. So you should change it to maybe staging or production as the case maybe then run php artisan config:cache. That should trigger the authorization using gate.

Jun
06
4 months ago
Activity icon

Replied to Retrieving Uploaded Image Files In Laravel

Oh right. If I set the default disk in the env file then this would work

Storage::putFileAs('profile_images', $request->image, $image);
Jun
05
4 months ago
Activity icon

Awarded Best Reply on Retrieving Uploaded Image Files In Laravel

I have been able to resolve the issue. The way I was accessing the image path in my UserResource was correct but when I uploaded the image, it didn't have the public visibility so I changed the way I was uploading the file to storage by specifying the disk like this

Storage::disk('public')->putFileAs('profile_images', $request->image, $image);
Activity icon

Replied to Retrieving Uploaded Image Files In Laravel

I have been able to resolve the issue. The way I was accessing the image path in my UserResource was correct but when I uploaded the image, it didn't have the public visibility so I changed the way I was uploading the file to storage by specifying the disk like this

Storage::disk('public')->putFileAs('profile_images', $request->image, $image);
Activity icon

Started a new Conversation Retrieving Uploaded Image Files In Laravel

I am working on a laravel 6.x api application. I want users to be able to upload a profile and when successful, get back the path to the image which can then be displayed on the frontend. So this is how I have set it up

First I edited the public driver configuration in config/filesystems.php like this

'public' => [
            'driver' => 'local',
            'root' => 'storage/',
            'url' => env('APP_URL').'/storage',
            'visibility' => 'public',
        ],

Then I am uploading the user profile image using this function

public function setProfileImg(Request $request)
{
    // validate request data
    ...

    // store authenticated user profile
    try {
        $user = auth()->user();

        if ($user->profile_image) {

            // delete old image from storage
            Storage::disk('public')->delete($user->profile_image);
        }

        // set profile image name
        $image  = now()->timestamp . '.' . $request->image->extension();

        // update user profile image
        $user->update(['profile_image' => 'profile_images/' . $image]);

        // store image file
        Storage::putFileAs('profile_images', $request->image, $image);

        $data = new UserResource($user);

        return $this->successResponse($data, 'Profile image updated.');
    } catch (Exception $ex) {
        return $this->serverError('Unable to save profile image.');
    }
}

And in the UserResource I am setting the profile image path like this

'profile_imgae'     => ($this->profile_image) ? asset('storage/' . $this->profile_image) : null

which looks like this http://localhost:8000/storage/profile_images/1591391659.jpeg but it is returning a 404 error not found response. What will be the right way to retrieve the image path?

Activity icon

Started a new Conversation How To Use Join Statements In Nova Partition Metric

I have two tables project_types & projects, each project has a project_type_id. So in my partition metric I want to display the count of each project type from the projects table. What I have done is simply grouping the projects by the project_type_id and it works but I don't get the project_type name.

return $this->count($request, Project::class, 'project_type_id');

Preview partion metric here - https://i.imgur.com/TQR3AiO.png

How would I do it so that the actual name of the project type is displayed instead of the project type id?

Activity icon

Replied to Laravel Task Completes But OnFailure Is Fired

Right. That was what I ended up doing, simply log a message inside the closure. Thanks for always helping out.

Activity icon

Replied to Laravel Task Completes But OnFailure Is Fired

Here's what I did and the onFailure hook still gets fired

$schedule->call(function () {

            Project::orderBy('id')
                ->chunk(10, function ($projects) {

                    foreach ($projects as $project) {
                        $title = empty($project->title) ?
                                $project->project_type->name . ' - ' . $project->local_government->name :
                                $project->title;

                        $target = ($project->total_unit * $project->price_per_unit);

                        $project->update([
                            'title'     => $title,
                            'target'    => $target
                        ]);
                    }
                });

                return true;
            })->dailyAt('09:01')->description('Project title & target update.')
                ->onSuccess(function () {
                    Log::notice('Project title & target update successful.');
                })
                ->onFailure(function () {
                    Log::error('Task failed.');
                });

Did I miss something still?

Jun
04
4 months ago
Activity icon

Replied to Laravel Task Completes But OnFailure Is Fired

From documentation https://laravel.com/docs/6.x/scheduling#task-hooks it seems like task hooks can only be used with commands and not closures. I stand to be corrected

Activity icon

Started a new Conversation Laravel Task Completes But OnFailure Is Fired

I have a simple task to perform and what to be able to see the status of the task. So here's what I have done

$schedule->call(function () {

            Project::orderBy('id')
                ->chunk(10, function ($projects) {

                    foreach ($projects as $project) {
                        $title = empty($project->title) ?
                                $project->project_type->name  :
                                $project->title;

                        $target = ($project->total_unit * $project->price_per_unit);

                        $project->update([
                            'title'     => $title,
                            'target'    => $target
                        ]);
                    }
                });
        })->dailyAt('01:00')
            ->description('Project title & target update.')
            ->onSuccess(function () {
                Log::notice('Project title & target update successful.');
            })
            ->onFailure(function () {
                Log::error('Project title & target update failed.');
            });

The task runs successfully and I was able to confirm this from the updates done on the projects table but onFailure still gets fired and error is logged. What is the proper way to use onSuccess & onFailure hooks?

Activity icon

Awarded Best Reply on Class 'Ixudra\\Curl\\Facades\\Curl' Not Found

Running composer update fixed the issue.

Activity icon

Replied to Class 'Ixudra\\Curl\\Facades\\Curl' Not Found

Running composer update fixed the issue.

Activity icon

Replied to Use Of Undefined Constant JSON_INVALID_UTF8_SUBSTITUTE - Assumed 'JSON_INVALID_UTF8_SUBSTITUTE'

Turns out that the update of the php version wasn't successful and that was the reason for the error. Updated to php version 7.4 and app works fine now.

Jun
03
4 months ago
Activity icon

Replied to In ProviderRepository.php Line 208: Class Not Found

I was facing similar issue and here's what worked for me. I simply ran composer update then composer dump-autoload and that got ride of the error.

Activity icon

Started a new Conversation Use Of Undefined Constant JSON_INVALID_UTF8_SUBSTITUTE - Assumed 'JSON_INVALID_UTF8_SUBSTITUTE'

I upgraded a laravel 5.8 application to 6.x and it runs fine on my development system which is running php 7.2.4. I deployed the app on a vps and changed the php version to 7.2 as well. When I try to access the application nova or telescope package, I get the exception error notice

Use of undefined constant JSON_INVALID_UTF8_SUBSTITUTE - assumed 'JSON_INVALID_UTF8_SUBSTITUTE'

in vendor/laravel/framework/src/Illuminate/Log/LogManager.php on this line return tap(new LineFormatter(null, $this->dateFormat, true, true), function ($formatter) { of the method below

/**
     * Get a Monolog formatter instance.
     *
     * @return \Monolog\Formatter\FormatterInterface
     */
    protected function formatter()
    {
        return tap(new LineFormatter(null, $this->dateFormat, true, true), function ($formatter) {
            $formatter->includeStacktraces();
        });
    }

But I am able to reach the api routes successfully. What is the issue and how should I handle this

May
20
5 months ago
Activity icon

Replied to Class 'Ixudra\\Curl\\Facades\\Curl' Not Found

Not yet. Project is a laravel 6.x version. I will look into though, thanks.

Activity icon

Started a new Conversation Class 'Ixudra\\Curl\\Facades\\Curl' Not Found

I am working on a laravel project and using this curl package https://github.com/ixudra/curl

Everything works fine on my dev system but I am getting a Class 'Ixudra\\Curl\\Facades\\Curl' not found error on the staging after pushing to my git repo.

Here's my composer.json content

"require": {
        "php": "^7.2",
        "doctrine/dbal": "^2.10",
        "ejarnutowski/laravel-api-key": "^1.0",
        "fideloper/proxy": "^4.0",
        "filp/whoops": "^2.7",
        "ixudra/curl": "^6.19",
        "laravel/framework": "^6.2",
        "laravel/nova": "*",
        "laravel/passport": "^8.4",
        "laravel/telescope": "^3.5",
        "laravel/tinker": "^2.0",
        "tymon/jwt-auth": "dev-develop"
    },

What could be the reason for this error?

May
14
5 months ago
Activity icon

Replied to Laravel .env Variable In Controller

Thanks. Helped me at my first attempt.

Activity icon

Started a new Conversation Unable To Read Attributes Of A Guzzle Response

I am using guzzle to consume an external endpoint in a laravel app inside a controller. When the response status is okay, I want to be able to read attributes of the response and use it further in the controller. So this is how I am approaching it

public function createdDedicatedAccount($user)
    {
        $client = new Client(['verify' => false]);

        $secretKey = 'secret_key';
        $url = 'target_url';
        $headers = [
            'Authorization' => 'Bearer ' . $secretKey,
            'content-type'  => 'application/json'
        ];

        $response = $client->request('POST', $url, [
            'headers' => $headers,
            'json' => ['customer' => 24105660]
        ]);

        if ($response->getStatusCode() === 200) {
            Log::info('Dedicated account assigned.');

            $dedicatedAccount = $response->getBody()->getContents();
            Log::info('dedicated_account: ' . $dedicatedAccount);
            Log::info('account_number: ' . $dedicatedAccount->data->account_number);

            return $dedicatedAccount ->data->customer;
        }
    }

From my logs I can see dedicated_account is logged as an object but account_number is not logged neither is $dedicatedAccount->data->customer returned because an exception error is thrown

Trying to get property 'data' of non-object

Below is the log showing the response object

[2020-05-14 15:14:35] local.INFO: Dedicated account assigned.  
[2020-05-14 15:14:35] local.INFO: dedicated_nuban: {
  "status": true,
  "message": "NUBAN successfully created",
  "data": {
    "bank": {
      "name": "Providus Bank",
      "id": 25,
      "slug": "providus-bank"
    },
    "account_name": "/TEST TEST",
    "account_number": "9930894189",
    "assigned": true,
    "currency": "NGN",
    "metadata": null,
    "active": true,
    "id": 89624,
    "created_at": "2020-03-30T10:13:13.000Z",
    "updated_at": "2020-05-14T14:14:37.000Z",
    "assignment": {
      "integration": 103612,
      "assignee_id": 24106114,
      "assignee_type": "Customer",
      "expired": false,
      "account_type": "PAY-WITH-TRANSFER-RECURRING",
      "assigned_at": "2020-05-14T14:14:37.214Z",
      "expired_at": null
    },
    "customer": {
      "id": 24106114,
      "first_name": "Test",
      "last_name": "Test",
      "email": "[email protected]",
      "customer_code": "CUS_u0g8u3e2z3ln66l",
      "phone": null,
      "metadata": null,
      "risk_action": "default"
    }
  }
}  
[2020-05-14 15:14:35] local.ERROR: Trying to get property 'data' of non-object {"exception":"[object] (ErrorException(code: 0): Trying to get property 'data' of non-object at

What am I doing wrong and what's the right way to handle this?

May
04
5 months ago
Activity icon

Replied to Laravel Image Upload Not Displaying

Yes I can actually see that the link exist. It shows on the folder too that its linked. The pain ...

Activity icon

Replied to Laravel Image Upload Not Displaying

I created the symlink by running the command php artisan storage:link

Activity icon

Started a new Conversation Laravel Image Upload Not Displaying

I have deployed a laravel application which is using the Nova admin for backend management on Bluehost VPS account. I have creates a symlink between storage and public as recommend in the laravel documentation.

I have set up a resource for uploading images like so

Avatar::make('Image')->onlyOnIndex(),

Image::make('Image')->disk('public')
->path('item-category')->required()->hideFromIndex()

I am using the public disk for storage with the filesystem disk configuration like so

'public' => [
            'driver' => 'local',
            'root' => storage_path('app/public'),
            'url' => env('APP_URL').'/storage',
            'visibility' => 'public',
        ],

On my local system, I am able to see the actual image displayed but on the staging the image is uploaded successfully but does not display because the image is not found when request is made for the image

Request URL:https://staging.example.com/storage/item-category/QCfcNCbZ0idd69muyL0Ux7X95NYj1Y0GgVSvYi0k.png

I can confirm that the image is stored in the db table, and inside staging/storage/app/public/item-category

Why does this same configuration work on my local dev system but not on the staging server? Spent the best part of my morning trying to figure this out.