simioluwatomi

simioluwatomi

Member Since 1 Year Ago

at Freelance

Experience Points 19,020
Experience Level 4

980 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 158
Lessons
Completed
Best Reply Awards 3
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.

05 Mar
2 months ago

simioluwatomi left a reply on Return Null If Relationship Is Not Loaded

I solved it by using a ternary

'data'  => $this->relationLoaded('profile') ? new UserProfileIdentifier($this->profile) : null,

If you have a better solution, please let me know

simioluwatomi started a new conversation Return Null If Relationship Is Not Loaded

I am trying to implement the JSON:API spec but I'm facing a small challenge of how to return null if the result of `$this->whenLoaded(relationship) is false instead of removing the key altogether before being sent as a response.

'relationships' => [
                'profile' => [
                    'data'  => new UserProfile($this->whenLoaded('profile')),
                ],
            ],

Below is the method signature

    /**
     * Retrieve a relationship if it has been loaded.
     *
     * @param  string  $relationship
     * @param  mixed  $value
     * @param  mixed  $default
     * @return \Illuminate\Http\Resources\MissingValue|mixed
     */
    protected function whenLoaded($relationship, $value = null, $default = null)

I have tried doing this

'data'  => $this->whenLoaded('profile', new UserProfile($this->profile), null),

But it always returns a result even when the relationship was not loaded in the controller.

Thanks

23 Feb
3 months ago

simioluwatomi left a reply on How Do I Fetch This Relationship

@CRONIX - You should check the has-many-through example and what I posted to see the subtle differences.

Thanks

simioluwatomi left a reply on How Do I Fetch This Relationship

@RICARDO - I took the example from the has-many-through and adapted it to fit my current database schema. So, this particular what if can't fly.

Thanks

simioluwatomi started a new conversation How Do I Fetch This Relationship

I have this Database structure

countries
    id - integer
    name - string

users
    id - integer
    name - string

posts
    id - integer
    user_id - integer
    country_id - integer
    title - string

Is it possible to get users->countries using the posts relationship? Thanks

14 Feb
3 months ago

simioluwatomi left a reply on Unique Validation On 3 Columns In 1 Table

@borisu That actually is not correct as it gives a Column not found: 1054 Unknown column 'null' in 'where clause' error

It should actually be

'name' => 'unique:table,field,NULL,id,field1,value1,field2,value2,field3,value3'

07 Feb
3 months ago

simioluwatomi left a reply on Problem Testing Passport Password Grant

I think it would be better if you proxied your request like so

$passportRequest = Request::create('oauth/tokent', 'POST', array(
            'grant_type' => 'password',
            'client_id' => env('PASSPORT_CLIENT_ID'),
            'client_secret' => env('PASSPORT_CLIENT_SECRET'),
            'username' => request('username'),
            'password' => request('password'),
            'scope' => '*',
        ));      
     
return Route::dispatch($passprtRequest);

@hardcoderrsl please take note

06 Feb
3 months ago

simioluwatomi left a reply on Laravel Passport And Different Database For Testing.

@vladistick How did you solve this? I'm having the same issue!

02 Jan
4 months ago

simioluwatomi started a new conversation Advice Needed On How To Structure This Vue SPA With Laravel Backend

Happy new year everyone.

I am about starting a laravel project. The project is a multi-sided platform with landing pages for the two kinds of users. User Type A will interact with the system via a sub-domain e.g app.example.com where they will have their own landing page, and auth pages.

But because the web app that they will be logging into is going to be a SPA, I'm confused due to the following requirements

  1. The landing page of User Type A should not be part of the SPA.

  2. If User Type A is logged in to the web app in the sub-domain and they try to visit the TLD, they should be redirected automatically to the web app

So this leaves me with the following questions

a. Where should the SPA begin?

i. Should the SPA be loaded after they sign in? This will give me the convenience of using Laravel to handle all authentication etc.

ii. Should the SPA start with its own authentication pages?

b. If the answer to a(ii) is yes, how do I set up the authentication such that requirement 2 is always met?

Thanks guys

26 Jun
10 months ago

simioluwatomi left a reply on Spatie Media Library Integration

It turns out I was not applying a middleware on the Controller that was why anything Auth related was null.

25 Jun
11 months ago

simioluwatomi started a new conversation Spatie Media Library Integration

Currently, in a project of mine, users upload heavy audio files to the application. Because of the file sizes (~ 150MB) each, I decided to upload directly to s3 using pre-signed URLs. This has been working fine so far.

However, I discovered the Spatie Media Library package last week and decided it play with it. I have used the library to replace all image uploads and I'm loving it. However, uploading to s3 is becoming a pain.

This is the method that performs the file upload. When written like this, it actually uploads a file to the tmp folder in the Storage directory.

public function create(Request $request)
    {
        if ($request->hasFile('filepond')) {
            $file = $request->file('filepond');
            return Storage::put('tmp', $file);
        }
        return response()->json('false');
    }

However, the version below does not work with the Spatie Media Library

public function create(Request $request)
    {
        $user = User::find(auth()->id());
        if ($request->hasFile('filepond')) {
            //This does not work
            $user->addMediaFromRequest('filepond')->toMediaCollection('logos', 's3');
            //This also does not work            
            $user->addMedia($request->file('filepond'))->toMediaCollection('logos', 's3');
            return response()->json('true');
        }
        return response()->json('false');
    }

With both throwing the

Call to a member function addMedia() on null {"exception":"[object] (Symfony\\Component\\Debug\\Exception\\FatalThrowableError(code: 0): Call to a member function addMedia() on nul

or

Call to a member function addMediaFromRequest() on null {"exception":"[object] (Symfony\Component\Debug\Exception\FatalThrowableError(code: 0): Call to a member function addMediaFromRequest() on null

Please help... Thanks

10 Jun
11 months ago

simioluwatomi left a reply on How To Abstract Storage Disk Choice For Local And Production Environment

Create an env variable FILESYSTEM_DRIVER=any_of_your_storage_disks. This env variable would be different in development and production.

07 May
1 year ago

simioluwatomi left a reply on Sub-domain Middleware

@byjinx Thanks a lot. Your answer pointed me in the right direction. To extend your answer, I ended up putting the if(auth()->check()) in a middleware and applying the middleware on all TLD routes.

04 May
1 year ago

simioluwatomi started a new conversation Sub-domain Middleware

I have an application with sub-domains. Normally, the auth middleware protects logged in users from accessing areas protected by the guest middleware. This works fine in my application but I want to extend it further.

Users log in at a sub-domain URL app.example.com/login which takes them to their dashboard. But I discovered that while logged in, users can still visit the TLD example.com. The only time they are redirected to the dashboard is when they visit any of the sub-domain routes protected by the guest middleware.

How do I redirect a user that is logged in at the sub-domain to their dashboard anytime they visit the TLD?

02 May
1 year ago

simioluwatomi left a reply on Getting Laravel Sub-domain Routes To Play Nicely With Ngrok

I finally got this to work but instead of using Ngrok, I used xip.io. Ngrok changes url every time a session is started if you are a free user, xip.io does not. Because I'm a Windows user, I switched dev environments from Laragon (laragon.org) to Valet-windows (https://github.com/cretueusebiu/valet-windows). I believe these steps can be ported all laravel valet regardless of operating system.

  • Get your computer's IPV4 address. If you don't know how, please use Google. If your network router assigns IP address dynamically, your IPV4 address would change every time the router restarts. To solve this, configure the router to reserve an IP address for your computer.
  • Do not hardcode your TLD into your routes. Instead, use an env variable to resolve it like I did above. Change env('APP_URL') to http://your_local_ip_address.xip.io
  • cd project_folder
  • valet link your_local_ip_address.xip.io
  • valet link {subdomain}. Run this for each of the sub-domains your project has.
  • Do not add entries for {subdomain}.your_local_ip_address.xip.io to your hosts file. Somehow, valet handles everything else.

Enjoy

01 May
1 year ago

simioluwatomi left a reply on Getting Laravel Sub-domain Routes To Play Nicely With Ngrok

@arukomp Thanks a lot. But the problem with that is I would actually need to be copying ngrok_generated-url a lot. Ngrok sessions only last for 7 hours maximum and each time the project is shared, a new URL is generated.

30 Apr
1 year ago

simioluwatomi started a new conversation Getting Laravel Sub-domain Routes To Play Nicely With Ngrok

I'm using sub-domain routing in a project which has 3 sub-domains api.example.test, app.example.test and admin.example.test. Sample route group code is below

Route::group(['namespace' => 'Web\Auth', 'domain' => 'app.' . env('APP_URL')], function () {
    // more code here
});

where env('APP_URL') = http://example.test

I made all necessary changes to my hosts file to make the sub-domains play nicely on my machine. Everything was working well when I used Postman to test all API routes. But now, I need to share the project to be publicly available so that the Android client can connect to the API routes.

When I share using Ngrok, all I get is the 404 page. No routes work. I thought it weird because I expected to be getting the Whoops error page since env('APP_DEBUG') = true. To get the error and its stacktrace, I decided to log it like so

if ($exception instanceof NotFoundHttpException) {
    Log::error('NotFoundHttpException Route: ' . Request::url());
    Log::error($exception);
}

Then I modified the routes of the homepage to

Route::group(['namespace' => 'Web'], function () {
    // more code here
});

Now, the homepage and all its routes work. The only challenge is that all sub-domain routes point to {subdomain}.example.test instead of {subdomain}.ngrok_generated_url. So when I click the subdomain links, I'm actually visiting the project on my machine instead of the one made available by ngrok.

  1. How do I resolve this?
  2. How do I make the NotFoundException display the Whoops package error instead of the 404 page?

Thanks for your help

20 Apr
1 year ago

simioluwatomi left a reply on Recommended Learning Strategy

It all depends on the person's knowledge of Php. When I signed up to Laracasts, my Php knowledge was still at beginner level so I had to brush up on my Php skills first before deep diving into Laravel itself.

I would suggest the following series in addition to what @rin4ik has suggested based on that experience

Pick two from this section or all if you want (PhpStorm + Sublime or VS Code or both)

18 Apr
1 year ago

simioluwatomi left a reply on I Might Not Understand The Fundamentals

Questions

  1. How many bosses does a user have; one or many?
  2. How many users can someone be a boss over; one or many?
  3. How many bosses are there in a department; one or many?

If I were you, I would structure things this way a. A user would have a boss (manager) b. A boss (manager) would have many bosses c. A boss (manager) would then have a boss (Head of Department) d. A boss (Head of Department) would have many bosses (managers) under him or her e. All bosses (HODs) would then report to the CEO (superuser).

Of course, you can remove the HODs if they don't suit your design...

simioluwatomi left a reply on Base64 To Upload Image

I'm guessing the base64 image is profileImg. Use this

$profileImg= Image::make(base64_decode(preg_replace('#^data:image/\w+;base64,#i', '',$data['profileImg'])))->stream();
Storage::put(path/to/folder, $profileImg, 'public');
17 Apr
1 year ago

simioluwatomi left a reply on How To Use Local Filesystem For Development But S3 For Production

@martinbean This is a L5.4 project migrated to L5.5. The corresponding line is

'default' => 's3', 

The reason why I'm giving the best answer to @Nash is because he answered first.

Thanks!!!!!

simioluwatomi started a new conversation How To Use Local Filesystem For Development But S3 For Production

Please, how can I use my local filesystem for development and S3 for production? My application is going to be handling large file uploads (between 100 - 150MB) but it is currently configured to use s3 as its default even in development.

I would need to upload a lot of files for testing purposes so I have decided it will be better to have different filesystem settings based on the app environment. How do I go about this?

My config/filesystem.php currently looks like this


'default' => 's3',

    'cloud' => env('FILESYSTEM_CLOUD', 's3'),

      'disks' => [

        'local' => [
            'driver' => 'local',
            'root' => storage_path('app'),
        ],

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

        's3' => [
            'driver' => 's3',
            'key' => env('AWS_KEY'),
            'secret' => env('AWS_SECRET'),
            'region' => env('AWS_REGION'),
            'bucket' => env('AWS_BUCKET'),
        ],

    ]
22 Mar
1 year ago

simioluwatomi left a reply on The Leaderboard

@tykus are you furreal???? See my life!!!!!!!!!!!!!!!!

simioluwatomi left a reply on How To Send The Verification Email ?

Why not use mailtrap for testing purposes first? Visit mailtrap.io to get started

simioluwatomi left a reply on Hosting Web App On A Server And Create API To Interact With Android App (iOS Future)

Build first, scale later. Most of the optimizations we have planned in our heads at the beginning of a project are unnecessary as those challenges are not mission critical.

I'm not in any way saying you should not follow best practices when building your project but do not focus on scaling when it is not yet a headache for you.

For the API, I would suggest using passport for Authentication and Postman for testing. You could bundle the API and WEB parts of the application into one project and use the different routes\web and routes\api files to differentiate them.

If I were you, I would separate my Controllers based on the part of the application they would serve.

simioluwatomi left a reply on The Leaderboard

Though a very good idea, the leaderboard does not take into account some few exceptions. For instance, I'm a Nigerian and internet is quite expensive over here.

Meaning I download the videos using IDM and watch offline. When I realised I was not getting points for that, I felt somehow.

Anyway, kudos to those who are at the top; we coming for ya!

13 Feb
1 year ago

simioluwatomi left a reply on Database Transaction Or Query->save() ?

you could have something that looks like the following

try {
    .........
    $queryOne->save;
    ........
    $queryTwo->save;

    DB::commit();
            return back()->with(toastr()->success('Query one and two saved.', 'Success'));

} catch (Exception $e) {
            return back()->with(toastr()->error('Query one and querytwo not saved.', 'Error'));
        }

This overly simplifies all the if else statements you would write checking which query saved or did not

simioluwatomi left a reply on Write This As One Method

It will be really cool if I could have it as just one Form request class but that Form Request class would become messy. Because each of those Form request classes are already adding extra parameters to the request based on if else conditions...

I think I'm gonna go with @biishmar's reply... Thanks guys

@arthurvillar I would really love to see that implementation

12 Feb
1 year ago

simioluwatomi started a new conversation Write This As One Method

I have two methods that do practically the same thing; uploading an image to S3. However, they have different arguments and the only different thing about the arguments is the Form Request class. I'm thinking there should be a way to write this so that its one single method.

Thank you for your time

/**
     * @param StoreMessageRequest $request
     * @param $s3
     * @return string
     */
    public function uploadAlbumArt(StoreMessageRequest $request, $s3)
    {
        $albumArtName = md5($request->albumArtName . microtime()) . '.jpg';
        $albumArt = Image::make(base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $request->albumArtImage)))->stream();
        $albumArtPath = 'albumarts/' . $albumArtName;
        $s3->put($albumArtPath, (string)$albumArt, 'public');
        return $albumArtPath;
    }

    /**
     * @param UpdateMessageRequest $request
     * @param $s3
     * @return string
     */
    public function updateAlbumArt(UpdateMessageRequest $request, $s3)
    {
        $albumArtName = md5($request->albumArtName . microtime()) . '.jpg';
        $albumArt = Image::make(base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $request->albumArtImage)))->stream();
        $albumArtPath = 'albumarts/' . $albumArtName;
        $s3->put($albumArtPath, (string)$albumArt, 'public');
        return $albumArtPath;
    }
09 Feb
1 year ago

simioluwatomi left a reply on I Know This Has A Lot Of Code Smell, Please Help Refactor

@CJJ Thank you so much! I use VS Code and PhpStorm but I usually only use PhpStorm for refactoring. I had installed the php-cs-fixer extension for VS Code but couldn't get it to work so I uninstalled it. Your comment made me go back to the VS Code series and I finally got it working!!!

And I have also downloaded Php The Right Way; can't wait to dig into it! Gracias!!! I should learn testing soon too...

simioluwatomi left a reply on I Know This Has A Lot Of Code Smell, Please Help Refactor

@bobbybouwmann @davidnn, this is what I have now, any further suggestions?

public function update(UpdateMessageRequest $request, $id)
    {
        $message = Message::find($id);
        $ministry = auth()->user();
        $id = $ministry->id;
        $s3 = Storage::disk('s3');
        $oldPreacher = Preacher::where('title', $message->preacher->title)->where('name', $message->preacher->name)->first();
        $newPreacher = Preacher::where('title', $request->preachertitle)->where('name', $request->preacher)->first();
        if ($request->has('seriestitle')) {
            $newSeries = Series::where('ministry_id', $id)->where('title', $request->seriestitle)->first();
        }
        if (!is_null($message->series)) {
            $oldSeries = Series::where('ministry_id', $id)->where('title', $message->series->title)->first();
        }
        if ($request->has('albumart')) {
            $albumArtPath = $this->uploadAlbumArt($request, $s3);
            $s3->delete($message->album_art_path);
        }
        if ($request->has('preacheravatar')) {
            $preacherAvatarPath = $this->uploadPreacherImage($request, $s3);
        }

        DB::beginTransaction();
        try {
            
            if ($newPreacher && $oldPreacher->isNot($newPreacher)) {
                if ($oldPreacher->messages_preached > 0) {
                    $oldPreacher->messages_preached--;
                }
                $message->preacher()->dissociate($oldPreacher);
                $newPreacher->messages_preached++;
                $message->preacher()->associate($newPreacher);
                $oldPreacher->save();
                $newPreacher->save();
            } else if (empty($newPreacher)) {
                $preacher = $this->createPreacher($request, $s3, $preacherAvatarPath);
                $message->preacher()->associate($preacher);
                $preacher->save();
            }

            if ($oldSeries && (empty($request->input('seriestitle')))) {
                if ($oldSeries->message_count > 0) {
                    $oldSeries->message_count--;
                }
                $message->series()->dissociate($oldSeries);
                $oldSeries->save();
            } else if ($newSeries && $oldSeries && $newSeries->isNot($oldSeries)) {
                if ($oldSeries->message_count > 0) {
                    $oldSeries->message_count--;
                }
                $message->series()->dissociate($oldSeries);
                $newSeries->message_count++;
                $message->series()->associate($newSeries);
                $oldSeries->save();
                $newSeries->save();
            } else if ($oldSeries && empty($newSeries) && $request->has('seriestitle')) {
                if ($oldSeries->message_count > 0) {
                    $oldSeries->message_count--;
                }
                $message->series()->dissociate($oldSeries);
                $oldSeries->save();
                $series = $this->updateSeries($request, $s3, $albumArtPath, $message);
                $series->ministry()->associate($ministry);
                $message->series()->associate($series);
                $ministry->profile->series_count++;
                $series->save();
            }
           

            $this->updateMessage($request, $message, $s3, $albumArtPath);
            $message->ministry()->associate($ministry);
            $message->save();

            $this->updateTags($request, $message);

            DB::commit();
            return back()->with(toastr()->success('Your message has been updated.', 'Success'));
        } catch (Exception $e) {
            return back()->with(toastr()->error('Your message was not updated. Please try again.', 'Error'));
        }
    }

Thanks for our time

08 Feb
1 year ago

simioluwatomi left a reply on Notifications Stopped Working After Integrating Jrean Library For User Verification

I have used Jrean's package before but not with Spark. Are you calling the UserRegistered event?

Show some code please...

simioluwatomi left a reply on Auth Problems

After giving each form input a name, you should dd($request) to see if the request hits your controller and confirm the name of the inputs you are getting. I sometimes make mistakes while typing form names and wonder why my form is not submitting properly

simioluwatomi left a reply on Upload Large Files

I would not put such heavy files in local for any reason... S3 solves that problem nicely. Uploading to S3 is another issue entirely though

simioluwatomi left a reply on Laravel 5.5: Additional Attribute For Forgot Password Form

First off, the $credentials variable is what is used to get the user from the database. So you need to modify it to look for the user based on the conditions you want. You don't need to touch any other thing

simioluwatomi left a reply on Phpstorm Theme In Laravel Series Let's Build A Forum With Laravel And TDD

I haven't seen the series but I suggest you take a look at Dayle Rees themes for PhpStorm... https://github.com/daylerees/colour-schemes

simioluwatomi left a reply on Asset Save To Local And Then S3

Where exactly are you not making a headway? Are the files not being uploaded at all to local storage? Or are they not being uploaded to s3?

Which is it?

06 Feb
1 year ago

simioluwatomi left a reply on I Know This Has A Lot Of Code Smell, Please Help Refactor

Thanks guys. I had commented the code that I was going to extract some lines to their own methods even before @bobbybouwmann pointed them out. The reason I posted the whole method without refactoring first was because I wanted suggestions other than the normal "extract to method" refactoring that is very visible even to untrained eyes.

@davidnn this is just a method in the controller and not the whole controller, so why should I go your route? I'm not saying your suggestion is bad, I just want to understand the idealogy it. Please throw more light on that.

I'm officially starting my first code review. Thanks once again

02 Feb
1 year ago

simioluwatomi started a new conversation I Know This Has A Lot Of Code Smell, Please Help Refactor

A little background so to this,

I have a Message model, it has a belongsTo relationship with Ministry, Preacher and Series models. The Ministry, Preacher and Series models have a hasMany relationship with it. However, the Message Series relationship can be nullable because not all messages belongsTo a Series.

Below is the method I have written to update a message; I hate its length and I know it needs a lot of refactoring, but I don't know where to start.

Thanks for your help. If you need more context, please ask. Thanks once again

public function update(UpdateMessageRequest $request, $username, $id)
    {
        $message = Message::find($id);
        $ministry = Auth::user();
        $id = $ministry->id;
        $s3 = Storage::disk('s3');

        $oldPreacher = Preacher::where('title', $message->preacher->title)->where('name', $message->preacher->name)->first();
        $newPreacher = Preacher::where('title', $request->input('preachertitle'))->where('name', $request->input('preacher'))->first();
        if ($request->has('seriestitle')) {
            $newSeries = Series::where('ministry_id', $id)->where('title', $request->input('seriestitle'))->first();
        }
        if (!is_null($message->series)) {
            $oldSeries = Series::where('ministry_id', $id)->where('title', $message->series->title)->first();
        }
        if ($request->has('albumart')) {
//extract to method
            $albumArtName = md5($request->input('albumArtName') . microtime()) . '.jpg';
            $albumArt = Image::make(base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $request->input('albumArtImage'))))->stream();
            $albumArtPath = 'demo/albumarts/' . $albumArtName;
            $s3->put($albumArtPath, (string)$albumArt, 'public');
            if ($s3->exists($message->album_art_path)) {
                $s3->delete($message->album_art_path);
            }
        }
        if ($request->has('preacheravatar')) {
//extract to method
            $preacherAvatarName = md5($request->input('preacherAvatarName') . microtime()) . '.jpg';
            $preacherAvatar = Image::make(base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $request->input('preacherAvatarImage'))))->stream();
            $preacherAvatarPath = 'demo/preacheravatars/' . $preacherAvatarName;
            $s3->put($preacherAvatarPath, (string)$preacherAvatar, 'public');
        }

        DB::beginTransaction();
        try {            
            
            // Update Preacher
            if ($newPreacher && $oldPreacher !== $newPreacher) {
                if ($oldPreacher->messages_preached > 0) {
                    $oldPreacher->messages_preached--;
                }
                $message->preacher()->dissociate($oldPreacher);
                $newPreacher->messages_preached++;
                $message->preacher()->associate($newPreacher);
                $oldPreacher->save();
                $newPreacher->save();
            } else if (!$newPreacher) {
//extract to method
                $preacher = new Preacher;
                $preacher->title = $request->input('preachertitle');
                $preacher->name = title_case($request->input('preacher'));
                $title = strtolower(preg_replace('/\s+/', '', $request->input('preachertitle')));
                $name = strtolower(preg_replace('/\s+/', '', $request->input('preacher')));
                $preacher->slug = $title . $name;
                $preacher->avatar = $s3->url('demo/preacheravatars/' . $preacherAvatarName);
                $preacher->avatar_path = $preacherAvatarPath;
                $message->preacher()->associate($preacher);
                $preacher->save();
            }

            if ($oldSeries && (empty($request->input('seriestitle')))) {
                if ($oldSeries->message_count > 0) {
                    $oldSeries->message_count--;
                }
                $message->series()->dissociate($oldSeries);
                $oldSeries->save();
            } else if ($newSeries && $oldSeries && $newSeries !== $oldSeries) {
                if ($oldSeries->message_count > 0) {
                    $oldSeries->message_count--;
                }
                $message->series()->dissociate($oldSeries);
                $newSeries->message_count++;
                $message->series()->associate($newSeries);
                $oldSeries->save();
                $newSeries->save();
            } else if ($oldSeries && !$newSeries && $request->has('seriestitle')) {
                if ($oldSeries->message_count > 0) {
                    $oldSeries->message_count--;
                }
                $message->series()->dissociate($oldSeries);
                $oldSeries->save();
                $series = new Series;
                $series->title = title_case($request->input('seriestitle'));
                if ($request->has('albumart')) {
                    $series->album_art = $s3->url('demo/albumarts/' . $albumArtName);
                    $series->album_art_path = $albumArtPath;
                } else {
                    $series->album_art = $message->album_art;
                    $series->album_art_path = $message->album_art_path;
                }
                $series->ministry()->associate($ministry);
                $message->series()->associate($series);
                $ministry->profile->series_count++;
                $series->save();
            }
            //Update message
            $message->title = title_case($request->input('title'));
            $message->date_of_message = Carbon::createFromFormat('d-m-Y', $request->input('date'))->format('Y-m-d');
            if ($request->has('albumart')) {
                $message->album_art = Storage::disk('s3')->url('demo/albumarts/' . $albumArtName);
                $message->album_art_path = $albumArtPath;
            }
            $message->ministry()->associate($ministry);
            $message->save();
            
            if ($request->has('tags')) {
                $message->retag(explode(',', $request->input('tags')));
            }

            DB::commit();
            $notification = array(
                'message' => 'Your message has been updated.',
                'alert-type' => 'success'
            );
            return back()->with($notification);
        } catch (Exception $e) {
            $notification = array(
                'message' => 'Your message was not updated. Please try again.',
                'alert-type' => 'error'
            );
            return back()->with($notification);
        }
    }
16 Dec
1 year ago

simioluwatomi left a reply on Unsupported Grant Type

That was a mistake... They shouldn't be.

However, I believe that somehow, adding additional info to a request validated in a form request somehow messes them up.

E.g: This works

class RegisterController extends Controller
{    

    public function register(Request $request)
    {
        $this->validate($request, 
        [
            'username' => 'required|alpha_num|min:6|max:30|unique:users',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6|confirmed',
            'firstname' => 'required|string|max:255',
            'lastname' =>'required|string|max:255',
            'telephone' => 'required|phone:AUTO',
            'gender' => 'required|string|max:1'
        ]);

        $user = User::create([
            'email'             =>      $request->email,
            'username'          =>      $request->username,
            'password'          =>      bcrypt($request->password),
        ]);

        UserProfile::create([
            'user_id'           =>      $user->id,
            'firstname'         =>      $request->firstname,
            'lastname'          =>      $request->lastname,
            'telephone'         =>      $request->telephone,
            'gender'            =>      $request->gender,
            'city'              =>      $request->city,
            'country'           =>      $request->country,
        ]);
        
        $params = 
        [
            'grant_type' => 'password',
            'client_id' => env('CLIENT_ID'),
            'client_secret' => env('CLIENT_SECRET'),
            'username' => request('email'),
            'password' => request('password'),
            'scope' => '*',
        ];
        $request->request->add($params);        
        $proxy = Request::create('oauth/token', 'POST');
        return Route::dispatch($proxy);        
    }

But this throws the unsupported grant type error

class RegisterController extends Controller
{  

    public function register(StoreUserRequet $request)
    {       

        $user = User::create([
            'email'             =>      $request->email,
            'username'          =>      $request->username,
            'password'          =>      bcrypt($request->password),
        ]);

        UserProfile::create([
            'user_id'           =>      $user->id,
            'firstname'         =>      $request->firstname,
            'lastname'          =>      $request->lastname,
            'telephone'         =>      $request->telephone,
            'gender'            =>      $request->gender,
            'city'              =>      $request->city,
            'country'           =>      $request->country,
        ]);
        
        $params = 
        [
            'grant_type' => 'password',
            'client_id' => env('CLIENT_ID'),
            'client_secret' => env('CLIENT_SECRET'),
            'username' => request('email'),
            'password' => request('password'),
            'scope' => '*',
        ];
        $request->request->add($params);        
        $proxy = Request::create('oauth/token', 'POST');
        return Route::dispatch($proxy);        
    }    
}

So the question now is how to add additional data to a form after validation that would not throw this error.

simioluwatomi started a new conversation Unsupported Grant Type

I am trying to generate a user token with my API using Laravel Passport. I want the token generated immediately a user registers but I keep getting an unsupported grant type error in Postman.

class RegisterController extends Controller
{
    private $client;
        
    public function __construct()
    {
        // Find the password grant client by id
        $this->client = Client::find(2);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param array  $request
     * @return \App\Models\User
     */

    public function register(StoreUserRequet $request)
    {
        $user = User::create([
            'email'             =>      $request->email,
            'username'          =>      $request->username,
            'password'          =>      bcrypt($request->password),
        ]);

        UserProfile::create([
            'user_id'           =>      $user->id,
            'firstname'         =>      $request->firstname,
            'lastname'          =>      $request->lastname,
            'telephone'         =>      $request->telephone,
            'gender'            =>      $request->gender,
            'city'              =>      $request->city,
            'country'           =>      $request->country,
        ]);

        $params = [
            'grant_type' => 'password',
            'client_id' => '$this->client->id',
            'client_secret' => '$this->client->secret',
            'username' => $user->email,
            'password' => $user->password,
            'scope' => '*',
        ];


        $request->request->add($params);
        $proxy = Request::create('oauth/token', 'POST');
        return Route::dispatch($proxy);

If I send manually using the same credentials in Postman, I get the access token. What could be the problem?

29 Sep
1 year ago

simioluwatomi started a new conversation What Is Wrong With This Flow

A message belongs to a series, and a series has many messages. However, not all messages belong to a series. Think of it like albums and tracks; a track can be a single or it can be part of an album; it can't be both. So, while creating a new message, the series title field can be null. To also avoid duplicating a series many times in the database; I have a messages_count column that increments if the series exists in the database.

But now, I need to update a message and there are many possibilities I think about

  1. The message may not belong to a series. Meaning the series title field was left blank when it was created. a. If a series title is now supplied by the user, i. Check if the series exists. If it does, associate the message with it, increment its messages_count. ii. If not, create series and associate message with it. b. If the field is left blank again; do nothing.

  2. The ````messagealready belong to aseries. a. If it is and a new series title is entered during for the update; i. Dissociatemessagefrom theseriesit belonged to; ii. Decrementmessages_countof that series. b. If the new series supplied by the user exists in the database, i. Increment itsmessages_count. c. If the new series does not exist, i. Create series d. If the series title field is blank, i. Dissociatemessagefrom theseriesit belonged to ii. Decrementmessages_count``` of that series.

I have written the code below for this purpose but does not do what I want to do especially number 2aii. What I'm I missing?

$message = Message::find($id);

$series = Series::where('ministry_id',  $id)->where('title', $request->input('seriestitle'))->first();
            if($series)
            {
                if (!is_null($message->series))
                {
                    $oldSeries = Series::where('ministry_id',  $id)->where('title', $message->series->title)->first();
                    if ($series->title == $oldSeries->title)
                    {
                        $series->message_count = $oldSeries->message_count;
                    }                    
                    else
                    {
                        if ($oldSeries->message_count >= 1) {
                            $oldSeries->message_count--;
                            $message->series()->dissociate($oldSeries);
                            $series->message_count++;                    
                        }
                    }
                    $oldSeries->save();
                    $series->save();
                }
        else if (empty ($request->input('seriestitle')))
                    {
                        $message->series()->dissociate($oldSeries);
                        $oldSeries->message_count--;
                    }                
            }

            
            
            else if ((!$series) && !empty ($request->input('seriestitle')))
            {
                $series                     =     new Series;
                $series->title              =     title_case($request->input('seriestitle'));                                
                $series->ministry()->associate($user);
                $user->profile->series_count++;
                $series->save();
            }

Thanks guys

29 Aug
1 year ago

simioluwatomi left a reply on Amazon S3 Upload ACL

@theotherdy you just saved me from 2 hours of writing bucket policies

04 Aug
1 year ago

simioluwatomi left a reply on Where Are You All From?

Lagos, Nigeria!!!

03 Aug
1 year ago

simioluwatomi left a reply on Query Builder Help

It works. Thank you

01 Aug
1 year ago

simioluwatomi left a reply on Query Builder Help

Ok. Now I understand. But how should the code now be written? I meant this

public function showseries(Series $series)
{
    return [$series, $series->messages];
}

simioluwatomi started a new conversation Get This JSON Response

Ministry model

public function messages()
    {
        return $this->hasMany(Message::class);
    }

public function series()
    {
        return $this->hasMany(Series::class);
    }

public function profile()
    {
        return $this->hasOne(Profile::class);
    }

I have this method that fetches all messages. The issue is that I want the result to also return the profiles of the ministry. What I'm I missing?

    {
        return Message::with('ministry', 'preacher', 'series')->get();
    }

Also, I have this N + 1 problem with a method

public function showseries(Series $series)
    {
        return [$series, $series->messages];
    }
```.

This query returns the series, and the messages in the series twice but performs an extra query. 
28 Jul
1 year ago

simioluwatomi left a reply on Get A Single Resource By Its User

I just needed to pass the username as a parameter of the method. Thank you loads