simioluwatomi

simioluwatomi

at Freelance

Member Since 2 Years Ago

Experience Points
19,140
Total
Experience

860 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-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-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-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist 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 4
19,140 XP
Sep
26
3 weeks ago
Activity icon

Replied to Validation That Calls An External API

That is the problem. The calls to the external service must be made because those calls are the validation. sigh

Activity icon

Started a new Conversation Validation That Calls An External API

So I have a method to validate some inputs. Pretty straightforward but it gets complicated

After validating that the user fills the form properly, I have to call an external API to validate the same input against that service. I'm wondering if someone has done this before and which way to go about this.

Form request or custom validator or both? I just need pointers. Thanks

public function validatexxxxxxxx(Request $request)
    {
        $request->validate([
            'forminput1'          => ['required'],
            'forminput2'  => ['required'],
        ]);

        $clientDetailsRequest = $this->client->get("/api/clients/{$request->input('forminput1')}", ['http_errors' => false]);

        $clientDetails = json_decode($clientDetailsRequest->getBody(), true);

        if ($clientDetailsRequest->getStatusCode() === 200) {
            return redirect()
                ->route('clients.show', ['key' =>$clientDetails['customKey']])
                ->with('message', [
                    'status' => 'info',
                    'body'   => 'Client with forminput1 already exists',
                ]);
        }

        $forminput1= (new Client())->get(
            config('xxxxx.mobile_base_url')."/validation/xxxxxxxx/{$request->input('forminput1')}",
            [
                'headers' => [
                    config('xxxxxx.xxxxxxxx') => config('xxxxxxx.'),
                ],
            ]
        );

        $body = json_decode($forminput1->getBody(), true);

        if ($body['status'] === 'fail') {
            return back()->with('message', [
                'status' => 'danger',
                'body'   => 'Provide a valid forminput1',
            ]);
        }

        if ($body['data']['basic_data']['xxxxxxx'] !== $request->input('forminput2') || $body['data']['basic_data']['xxxxxxxx'] !== $request->input('forminput2')) {
            return back()->with('message', [
                'status' => 'danger',
                'body'   => 'Provide forminput2 tied to the forminput1',
            ]);
        }

        // redirect to another page with a success response;
    }
Sep
01
1 month ago
Activity icon

Replied to Laravel Eloquent Group By

Thanks! Exactly what I wanted.

Activity icon

Started a new Conversation Laravel Eloquent Group By

So I have Post and Category models with a one-to-many relationship between them. How do I group posts by their categories?

I need the data to be formatted like so

{

"data": {

"Category 1 name": ["Post title 1", "Post title 2"],

"Category 2 name ": ["Abeokuta North", "Egbado South"]

}

}

I have done

$categories = \App\Models\Category::with(['post' => function ($query) {
    $query->orderBy('title');
}])->orderBy('name')->get();

$output = $categories->map(function ($category) {
    return [
        $category->name => $category->post->pluck('title'),
    ];
});

But I always get the data nested in an array index like so which is one level deeper than I want to go.

{
  "data": [
    {
      "category 1": [
        "Post 1 title",
        "Post 2 title",
        "Post 3 title",
        
      ]
    },
    {
      "category 2": [
        "Post 1 title",
        "Post 2 title",
        "Post 3 title",
        
      ]
    },
    
  ]
}

Thanks for your help

Mar
05
7 months ago
Activity icon

Replied to Return Null If Relationship Is Not Loaded

I solved it by using a ternary

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

If you have a better solution, please let me know

Activity icon

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

Feb
23
7 months ago
Activity icon

Replied to 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

Activity icon

Replied to 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

Activity icon

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

Feb
14
8 months ago
Activity icon

Replied to 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'

Feb
07
8 months ago
Activity icon

Replied to 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

Jan
02
9 months ago
Activity icon

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

Jun
26
1 year ago
Activity icon

Replied to Spatie Media Library Integration

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

Jun
25
1 year ago
Activity icon

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 null 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

Jun
10
1 year ago
Activity icon

Replied to 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.

May
07
1 year ago
Activity icon

Replied to 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.

May
04
1 year ago
Activity icon

Started a new Conversation Sub-domain Middleware

I have an application with sub-domains. Normally, the auth middleware prevents 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?

May
02
1 year ago
Activity icon

Replied to 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 to 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

May
01
1 year ago
Activity icon

Replied to 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.

Also, this results in a Tunnel {subdomain}.ngrok_generated_url not found error

Apr
30
1 year ago
Activity icon

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

Apr
20
1 year ago
Activity icon

Replied to 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)

Apr
18
1 year ago
Activity icon

Replied to 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...

Activity icon

Replied to 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');
Apr
17
1 year ago
Activity icon

Replied to 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!!!!!

Activity icon

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',    

    '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'),
        ],

    ],
    
Mar
22
1 year ago
Activity icon

Replied to The Leaderboard

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

Activity icon

Replied to How To Send The Verification Email ?

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

Activity icon

Replied to 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.

Activity icon

Replied to 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!

Feb
13
1 year ago
Activity icon

Replied to Database Transaction Or Query->save() ?

you could have something that looks like the following

try {
//    some code
    $queryOne->save;

// some other code

    $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

Activity icon

Replied to 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

Edit

This is what I ended up writing.

    /**
     * @param $request
     * @param $s3
     * @return string
     */
    public function uploadAlbumArt($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;
    }
Feb
12
1 year ago
Activity icon

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;
    }
Feb
09
1 year ago
Activity icon

Replied to 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...

Activity icon

Replied to I Know This Has A Lot Of Code Smell, Please Help Refactor

@bobbybouwmann @davidnn, this is what I have now, any further suggestions? Thanks for your time

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'));
        }
    }
Feb
08
1 year ago
Activity icon

Replied to 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...

Activity icon

Replied to 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

Activity icon

Replied to 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

Activity icon

Replied to Laravel 5.5: Additional Attribute For Forgot Password Form

First off, the $credentials variable is what is used to get the user. So you should modify it to suit your needs.

Activity icon

Replied to Phpstorm Theme In Laracasts 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

Activity icon

Replied to 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?

Feb
06
1 year ago
Activity icon

Replied to 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

Feb
02
1 year ago
Activity icon

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);
    }
}
Dec
16
1 year ago
Activity icon

Replied to 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.

Activity icon

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?

Sep
29
2 years ago
Activity icon

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 The message may not belong to a series. Meaning the series title field was left blank when it was created.

If a series title is now supplied by the user, Check if the series exists. If it does, associate the message with it, increment its messages_count. If not, create series and associate message with it. If the field is left blank again; do nothing.

The message already belong to a series. If a new series title is entered during for the update; Dissociate message from the series it belonged to; Decrement messages_count of that series. If the new series supplied by the user exists in the database, Increment its messages_count.

If the new series does not exist, Create series

If the series title field is blank, Dissociate message from the series it belonged to Decrement messages_count of that series.

I have written the code below for this purpose but does not do what I want to do especially number 2. 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 (empty ($request->input('seriestitle')))
        {
            $message->series()->dissociate($oldSeries);
            $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 ((!$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

Aug
29
2 years ago
Activity icon

Replied to Amazon S3 Upload ACL

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

Aug
04
2 years ago
Activity icon

Replied to Where Are You All From?

Lagos, Nigeria!!!

Aug
03
2 years ago
Activity icon

Replied to Query Builder Help

It works. Thank you