SangminKim

SangminKim

Member Since 4 Years Ago

Experience Points 16,820
Experience Level 4

3,180 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 182
Lessons
Completed
Best Reply Awards 0
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.

23 Mar
3 months ago

SangminKim left a reply on Using Asset() But Images Are Not Visible

@EDOC - Yeah, you're absolutely right. Thanks a lot!

SangminKim left a reply on Using Asset() But Images Are Not Visible

@EDOC - ```


So, this is what i have now. So should this be something like this?


If so, why would it be working without appending storage on valet ?

SangminKim started a new conversation Using Asset() But Images Are Not Visible

Hello,

I've been working on building a laravel application on my local and everything was fine. When I pushed it to the dev server running on Gentoo linux, the images started not showing up.

For example,

http://newdev.formulad.com/events/March2019/RgOHIX4ShweYhgElX6Jq.jpg

This is the image path I'm getting from asset() but it's getting 404 error. If I add storage/ in the path...

http://newdev.formulad.com/storage/events/March2019/RgOHIX4ShweYhgElX6Jq.jpg

Then this is visible.

I've run the command line php artisan storage:link.

Checked out to see if filesystem configs are wrong... but they're identical.


'disks' => [

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

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

        's3' => [
            'driver' => 's3',
            'key' => env('AWS_ACCESS_KEY_ID'),
            'secret' => env('AWS_SECRET_ACCESS_KEY'),
            'region' => env('AWS_DEFAULT_REGION'),
            'bucket' => env('AWS_BUCKET'),
        ],

    ],

Also tried dumping autoload using composer and clearing cache using artisan.

What am I missing? What makes the difference? Any ideas?

Thanks :(

24 Feb
4 months ago

SangminKim left a reply on Grouping By 15 Days( 1 ~ 15 ) / ( 16 ~ End Of Month ).

@roborobok It works! Awesome!

Would it be possible to have some sort of flag in Select whether it's 1~15 or 15 and up?

21 Feb
4 months ago

SangminKim started a new conversation Grouping By 15 Days( 1 ~ 15 ) / ( 16 ~ End Of Month ).

Hi everyone,

I have a query that groups billing information by month. However, I'd like to tweak it so that the query retrieves billing information by 15 days - i.e. ( 1 ~ 15 ) / ( 16 ~ end of month ).

$billings = Billing::select(\DB::raw("YEAR(billing_date) as year,
                                            MONTH(billing_date) as month,
                                            SUM(subtotal + extra_fee) as subtotal,
                                            SUM(gst) as gst, SUM(pst) as pst,
                                            SUM(subtotal) as total"))
                            ->groupBy(\DB::raw("YEAR(billing_date)"))
                            ->groupBy(\DB::raw("MONTH(billing_date)"))
                            ->orderBy('year', 'desc')
                            ->orderBy('month', 'desc')
                            ->get();

What would be the best way to do it with eloquent?

Thanks.

30 Jan
4 months ago

SangminKim left a reply on Sendgrid] MAIL_FROM_ADDRESS Never Change

@CRONIX - @cronix Completely missed that part. Thanks a lot.

SangminKim left a reply on Sendgrid] MAIL_FROM_ADDRESS Never Change

@cronix Argggg... figured it out... i was running a supervisor to monitor queues and some of the instances were using old env data I was using while some were using up-to-date env... restarting it solved the issue.

Thanks for your help tho. Mind if I ask you said "Also, the only place you should ever use env() is from within config files." ?

SangminKim left a reply on Sendgrid] MAIL_FROM_ADDRESS Never Change

@cronix Yup. That's the very first things I checked... Well, perhaps sendgrid has its own caching system or something... who knows. I will wait for a few hours to see if it works.

Thanks.

SangminKim left a reply on Sendgrid] MAIL_FROM_ADDRESS Never Change

@cronix

Hmmm... this is very odd.

It sometimes sends email an email using ENV varabiel([email protected]) and sometimes doesnt. Hmmm...

SangminKim left a reply on Sendgrid] MAIL_FROM_ADDRESS Never Change

Nvm... still some emails display gmail as from email...

SangminKim left a reply on Sendgrid] MAIL_FROM_ADDRESS Never Change

@cronix Thanks I will check it out.

Funny thing is, I've tried sending an email to an address that has never received one before... and it correctly display [email protected] as From address!

The email addresses that have received emails from [email protected](which I previously had as MAIL_FROM_ADDRESS) at least once display the from url as [email protected]

Do you think email applications might be remembering the initial from address and displaying it instead of the updated one?

SangminKim started a new conversation Sendgrid] MAIL_FROM_ADDRESS Never Change

Hmmm... this is driving me nuts... has anyone used sendgrid before?

MAIL_ENCRYPTION=tls
MAIL_FROM_NAME=KMOVE
[email protected]

I have this in my .env file, cleared config cache, and authenticated the domain using sendgrid's authentication service...

but Sendgrid sends email as [email protected] (client's email address) for some reason. I thought my env file had been cached... but it won't change no matter what. I checked every page in sendgrid to see if it's manually stored... but that's not the case.

php artisan config:clear
php artisan cache:clear
composer dump-autoload

what else can I try?

27 Jan
4 months ago

SangminKim left a reply on Sending Out +300 Emails Using Mail:queue

Thanks, I ended up using database queue and monitoring it with supervisor instead of using sync - https://laravel.com/docs/5.7/queues#connections-vs-queues

SangminKim started a new conversation Sending Out +300 Emails Using Mail:queue

Hi Laravel users,

I'm building an application sending out notification emails to users every 3~4 months. I'm currently using Mail queue.

// foreach user
     // generate a custom message for this user
     Mail::to( $mail_to )->queue( new SendApproval( $subject, $general_message ) );

// return to success page

However, I have a few concerns with this:

  1. Would it cause a serious CPU / RAM usage and possible crash the server?

  2. Mail::queue crashes, the rest won't be running. I will prevent it by having try and catch... but is there a better way?

  3. It doesn't leave any logs... how do you do log and check if every email is successfully sent out?

  4. I know there are some third party API solutions for this... do you have any other better solutions than relying on laravel?

I'm currently using Sendgrid for sending out emails.

Thanks.

24 Jan
5 months ago

SangminKim left a reply on Logging Single Vs Daily In Laravel 5.7

Sigh... a typical PEBKAC issue... I had another LOG_CHANNEL variable set to stack in the env... and config wasn't being cleared properly for some reason...

Thanks.

SangminKim left a reply on Logging Single Vs Daily In Laravel 5.7

@SNAPEY - Weird... I will give it another shot. Thanks for confirming it :)

SangminKim started a new conversation Logging Single Vs Daily In Laravel 5.7

Hello everyone, I'm trying to log things daily as my application runs but I've noticed something weird...

With laravel 5.5 or lower, it was very easy. Setting APP_LOG in env o daily was all. Then, Laravel created log files daily using names something like yyyy-mm-dd-log...

With laravel 5.6 and higher, it seems things are little different.


LOG_CHANNEL=daily

I've added the code above to my env file then cleared and cached config. However, laravel doesn't seem to create daily log files but log everything in laravel.log. So, I've opened up logging.php under config folder... then found the following code

        'single' => [
            'driver' => 'single',
            'path' => storage_path('logs/laravel.log'),
            'level' => 'debug',
        ],

        'daily' => [
            'driver' => 'daily',
            'path' => storage_path('logs/laravel.log'),
            'level' => 'debug',
            'days' => 7,
        ],

So... it seems like both single and daily are using the same laravel.log file... is this how the recent laravel supposed to log?

What should I do if I want Laravel to log things daily like before (yyyy-mm-dd format)?

Thanks.

16 Jan
5 months ago

SangminKim left a reply on BelongsToMany For More Than 2 Foreign Keys?

@SNAPEY - Thank you for the reply.

An event can have many registered jobs and one job can be registered for many events. The same for corporation. An event can have many corporations attending and one corporation can attend many events. Isn't it many-to-many relationship?

SangminKim started a new conversation BelongsToMany For More Than 2 Foreign Keys?

Hi everyone! I have four tables:

Event  - id, name

Corporation - id, name

Job - id, corporation_id, name

RegisteredJob - id, event_id, corporation_id, job_id.

As you can see, RegisteredJob table has three foreign keys - representing jobs registered for a job fair event. I think I should use belongsToMany for relationships... but the example Laravel documentation is using only two tables.

Has anyone tried belongsToMany with 3 foreign keys? Did it go well or did you find it tricky with all these pivot where... pivot sync... and etc?

If belongsToMany is particularly for two tables with many-to-many relationships... Should I refactor RegisteredJob table something like the following?

Event  - id, name

Corporation - id, name

Job - id, corporation_id, name

// New table storing corporations attending an event.
RegisteredCorporation - id, event_id, corporation_id.

RegisteredJob - id, registered_corporation_id, event_id, job_id.

The reason why I'm keeping three foreign keys is that it reduces the amount of codes I need to write... for example,

// To find a corporation name and an event name... I need to use nested with functions...
$registered_job = RegisteredJob::with('registered_corporation.corporation')->with('registered_corporation.event')....

// With one table with three foreign keys... I can simply use..
$registered_job = RegisteredJob::with('corporation', 'event')....



To recap ::

1. Is belongsToMany good for a table with more than 3 foreign keys?

2. If not, should I refactor registered job table cuz my datbase schema has an issue in the first place?


Thanks
11 Jan
5 months ago

SangminKim left a reply on SaveMany Refering To A Wrong Table

@SNAPEY - Ahhhhh, I see.... that was my fault there...

public function corporates_attending_events(){
        return $this->belongsToMany(EventCorporate::class, 'event_corporate', 'event_id', 'id');
    }

    public function add_corporate( $corporate ){
        $method = ( $corporate instanceof Corporate ) ? 'save' : 'saveMany';
        $this->corporates_attending_events()->$method( $corporate );

    }

I've changed the codes like this and now it's displaying a different error message.

Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: event_corporate.corporate_id (SQL: insert into "event_corporate" ("event_id", "id") values (1, 1))

The corporate id is still not being passed... is it another relationship issue?

Thanks

SangminKim left a reply on SaveMany Refering To A Wrong Table

One more thing I noticed is... if I use create / createMany instead, it is pointing to a correct table :O

Using create / createMany can be a solution but I'd like to stick with save/saveMany since I do not need to convert the attributes to arrays

SangminKim started a new conversation SaveMany Refering To A Wrong Table

Hi there, I have three tables with relationships:

Event - id / title / etc... Corporate - id / name / etc... EventCorporate - id / event_id / corporate_id.

And each model looks like the following:

class Event extends Model
{
    protected $fillable = [
        'title',
        ...
    ];

    public function corporates_attending_events(){
        return $this->hasMany(EventCorporate::class);
    }

    public function add_corporate( $corporate ){
        $method = ( $corporate instanceof Corporate ) ? 'save' : 'saveMany';
        $this->corporates_attending_events()->$method( $corporate );

    }

    // and more codes...
}


class Corporate extends Model
{
    protected $fillable = [
        'name',
        'description',
        'link',
        'thumbnail',
        'is_active'
    ];

    // and more codes...
}


class EventCorporate extends Model
{

    protected $table = 'event_corporate';

    protected $fillable = [
        'event_id',
        'corporate_id',
        'is_active'
    ];

    public function event(){
        return $this->hasOne(Event::class);
    }

    public function corporate(){
        return $this->hasOne(Corporate::class);
    }

    // and more codes...
}

When I run the following unit test for Event:

public function it_adds_a_coporate_to_the_event()
    {
        $event = create_an_event();
        $corporate = factory(Corporate::class)->create();
        $event->add_corporate($corporate);
        $this->assertEquals(1, $event->corporates_attending_events->count());
    }

The unit test fails with the following error message:

Illuminate\Database\QueryException: SQLSTATE[HY000]: General error: 1 no such column: event_id (SQL: update "corporates" set "event_id" = 1, "updated_at" = 2019-01-11 21:26:08 where "id" = 1)

The first thing I instantly noticed is that add_corporate(...) in Event motel is trying to update a wrong table.

Did I set the relationships incorrectly?

The source code is from Jeffrey's tutorial ( https://laracasts.com/series/phpunit-testing-in-laravel/episodes/6 ). For those who cannot access laracasts, the source files are here (https://github.com/laracasts/Hands-On-Testing-Workflow)

Thanks!

26 Jul
11 months ago

SangminKim left a reply on Laravel Socialite

It seems like they force you to use https now..

23 Jul
11 months ago

SangminKim left a reply on Htmlspecialchars() Error After Validation Fails

Hmmm... regular html doesn't work either... Arrggg... I will keep digging..

SangminKim left a reply on Htmlspecialchars() Error After Validation Fails

Thanks! Will give it another shot!

SangminKim left a reply on Htmlspecialchars() Error After Validation Fails

My apologies. I should have clarified it better.

It's not the messages[]'s rules causing the problem (it doesn't have any rules yet). If any other rules break, then redirection with old inputs breaks the page.

SangminKim left a reply on Htmlspecialchars() Error After Validation Fails

I tried that but didn't work unfortunately.

While waiting for someone's reply, I noticed that old(.....) returns an array of inputs. Trying to build the input boxes out of this.

SangminKim started a new conversation Htmlspecialchars() Error After Validation Fails

Hello, everyone!

I'm getting "ErrorException in helpers.php line 519: htmlspecialchars() expects parameter 1 to be string, array given" error message whenever my form fails a validation. The error is from the following array:

{{ Form::text('messages[]', null, ['class'=>'form-control', 'placeholder'=>'Tab Header']) }}

If I delete the line, the form works perfectly. If I change it to non-array, it works perfectly.

After a few experiments, I started thinking that the page breaks when it's the messages[] 's turn to fill out old inputs after validation failure...

Did anyone have a similar issue? How did you guys handle this problem?

Thanks,

18 Jul
11 months ago

SangminKim left a reply on Queue Appends Emails To To List.

Sigh... this was because the $message was outside of the loop. The loop kept adding a new recipient to the message and queuing it... Putting it inside the loop fixed the issue.

SangminKim started a new conversation Queue Appends Emails To To List.

// Get the list of emails
$recipient_emails = request()->recipient_email;
// Delete all the white spaces first
$emails = str_replace(' ', '', $recipient_emails);
// Store each of them in an array
$emails_in_array = explode(',', $emails);


// If there is at least one email
if ( count( $emails ) > 0 ) {

    // Prepare a message to send
    $message = (new InvititationEmail())
        ->subject("You're invited !")
        ->replyTo(getenv('MAIL_REPLY_TO'), getenv('MAIL_REPLY_TO_NAME'))
        ->onQueue('emails');

    // for each email
    foreach( $emails_in_array as $email ){

    // If it's a valid one
        if( filter_var($email, FILTER_VALIDATE_EMAIL) ) {
            // queue it!
            Mail::to($email)->queue($message);
        }
    }
    
}

Hi,

What you see above is from my source code. What it does is

  1. get a list of emails using comma us a delimiter. i.e) [email protected], [email protected], [email protected], and so on.

  2. prepare a message to send

  3. loop through the emails, and queue emails one by one.

However, the problem is the Mail::queue appends recipients for some reason. In other words, each loop goes something like this:

1st loop ) Queue an email for [email protected] 2nd loop ) Queue an email for [email protected], [email protected] 3nd loop ) Queue an email for [email protected], [email protected], [email protected]

And here is what I have confirmed so far:

  1. $email in the loop is a single email address.
  2. the 2nd & 3rd payload data in jobs table has multiple recipients for some reason.

Am I missing something here? :/

13 Jul
11 months ago

SangminKim left a reply on Queue:work Not Responding

The mails are not being sent but it's a different story. At least Laravel is trying to.

Thanks!

SangminKim left a reply on Queue:work Not Responding

Oh! A previous developer used emails instead of default. Changing the values to default and queue:work --once start changing attempts values!

That's interesting.

SangminKim left a reply on Queue:work Not Responding

Hmmmmm... it still says nothing...

[email protected] ~/dev_site/dev $ php artisan queue:work --once
[email protected] ~/dev_site/dev $ php artisan queue:work --once
[email protected] ~/dev_site/dev $ php artisan queue:work --once

SangminKim left a reply on Queue:work Not Responding

This is what .env looks like and the credentials are correct.

APP_ENV=local
APP_KEY=base64:(Key Here)
APP_DEBUG=true
APP_LOG=daily
APP_LOG_LEVEL=info
APP_LOG_MAX_FILES=30
APP_URL=http://localhost
APP_TIMEZONE=UTC

BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=database

MAIL_DRIVER=smtp
MAIL_HOST=smtp.sendgrid.net
MAIL_PORT=587
MAIL_USERNAME=(Username Here)
MAIL_PASSWORD=(Password Here)
MAIL_ENCRYPTION=tls


And this is what config/mail.php looks like.


'driver' => env('MAIL_DRIVER', 'smtp'),
    'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
    'port' => env('MAIL_PORT', 587),
    'from' => [
        'address' => env('MAIL_FROM_ADDRESS', '[email protected]'),
        'name' => env('MAIL_FROM_NAME', 'Example'),
    ],
    'encryption' => env('MAIL_ENCRYPTION', 'tls'),
    'username' => env('MAIL_USERNAME'),
    'password' => env('MAIL_PASSWORD'),
    'sendmail' => '/usr/sbin/sendmail -bs',

I've waited 15~20mins but still no response :/

SangminKim started a new conversation Queue:work Not Responding

[email protected] ~/dev.ca/dev $ php artisan queue:work
^C
[email protected] ~/dev.ca/dev $ php artisan queue:work
^C
[email protected] ~/dev.ca/dev $ php artisan queue:work
^C
[email protected] ~/dev.ca/dev $ php artisan queue:work
^C
[email protected] ~/dev.ca/dev $ php artisan queue:work
^C
[email protected] ~/dev.ca/dev $ php artisan queue:work

The laravel site (5.3.31 on linux server) i'm working on is using sendgrid smpt and it can send password reset email to users very well. However, the mails in queue doesn't get fired. There are a bunch of queue emails in jobs table but queue:work command simply does nothing. Zero attempts.

https://stackoverflow.com/questions/23980979/laravel-not-sending-email-and-not-giving-errors/51132498#comment89609270_51132498

I tried what people suggest but still no luck.

Has anyone had the same issue?

03 Jul
11 months ago

SangminKim left a reply on Backend Structure For CMS With Multi Layouts For Pages

https://css-tricks.com/different-cmss-handle-content-blocks/

Hmmmm.. found this article but not really helpful.. too abstract for me :/

02 Jul
11 months ago

SangminKim left a reply on Backend Structure For CMS With Multi Layouts For Pages

Changed the thread title not to mislead people...

SangminKim started a new conversation Backend Structure For CMS

Hello everyone,

I'm brainstorming to come up with a good solution for the problem I'm currently facing. I'm building a cms that allows you to CRUD pages such as home page, sub pages, contact pages and etc.

The problem is they have all different contents( you can call them sections, blocks, widgets, and so on) with different layouts. For example, a front page can have banner images, call to action buttons, social media links, sliders while other pages do not. Sub pages can be a single column, double columns, or even triple columns with/without a header image.

A good thing is no html / javascript codes are required to be inserted. As long as they can change the images and texts, my client will be happy.

So, I've created a table named 'pages' and it has the following fields for now:

id language title slug content, template is_public created_at updated_at

And I'm planning to store all those different blocks/contents in content field as an object... so it looks like the following:

{
  "content": {
    "front_page_template" : {
      "header_image":{
        "image" : "url here",
        "text" : "blah"
      },
      "call_to_action":{
        "image" : "url here",
        "link" : "url here",
        "text" : "Call us today!"
      }
    },
    "single_column_template" : {
      "has_header" : false,
      "content" : {
        "column" : "blah"
      }
    },
    
    "double_column_template" : {
      "has_header" : false,
      "content" : {
        "left_column" : "blah",
        "right_column" : "blah"
      }
    },
    
    "triple_column_template" : {
      "has_header" : false,
      "content" : {
        "left_column" : "blah",
        "middle_column" : "blah",
        "right_column" : "blah"
      }
    }
  }
}

and when displaying the page, my PageController will check which template is currently selected and grabs corresponding content from content field. I think this will work as long as I name the keys properly and keep them consistent.... However, I also see some potential issues.

Firstly, it's more NoSql style rather than relational. It's violating a golden rule of Database Design - all the data stored in DB must be atomic and represent one thing only.

Secondly, each template stores their own contents... in other words, contents in common might get duplicated. (which is kinda related the issue #1)

Thirdly, There will be a problem when it comes to searching certain strings in the future because contents that are not currently in active status will be checked as well (fortunately, the site doesn't really need searching features)

Fourthly, I feel like one controller(PageController) and its create/edit page has too much responsibility. The way I implemented its create/edit page is that all the input/select/check boxes are hidden in the first place and selecting a template toggles the only forms needed for the select template. Then, when you hit save button, the controller go though all the fields, restructure them in an array, then encode it as json to store in database. It would be great if I can make the controller less responsible...

I'm trying to come up with a better idea to make it happen... but I'm not sure how.

Have you built a similar site before? How did you approach and solve the problem?

Please share your exprience for me.

Thank you so much.

01 Jun
1 year ago

SangminKim left a reply on A Relationship From HasMany Returns Null

using belongsTo fixed the issue. sigh.

SangminKim left a reply on A Relationship From HasMany Returns Null

I double checked that the ids in tables are stored correctly.

SangminKim started a new conversation A Relationship From HasMany Returns Null

Hi Laravel masters,

I have two models - Page and Navigation - and they are to be connected via relationships. Navigations are basically menu items linked to pages and each menu item can have sub menu items.

Here are models I have (They're simpl

namespace App;

use Illuminate\Database\Eloquent\Model;

class Navigation extends Model
{
    protected $fillable = [
        'page_id',
        'parent_id',
        'order',
        'is_public'
    ];

    public function page(){

        return $this->hasOne('App\Page', 'id');

    }


    public function child_menus(){

        return $this->hasMany('App\Navigation', 'parent_id');

    }

}
class Page extends Model
{
    protected $fillable = [
        'language',
        'title',
        'slug',
        'content',
        'featured_image',
        'slide_images',
        'template',
        'is_public'
    ];
}

And to generate a navigation I added the following codes to AppServiceProvider

        view()->composer('*', function($view){
            $navigations = Navigation::with('page')
                            ->with(['child_menus' => function( $query ){
                                $query->with('page')->orderBy('order', 'ASC');
                            }])
                            ->where('parent_id', '<', 1)
                            ->orderBy('order', 'ASC')
                            ->get();
            $view->with('custom_navs', $navigations);
        });
``

However, this doesn't work for some reason. Page relationships under child_menus return null. So I tried this.


        $navigations = Navigation::with('page')
                        ->with(['child_menus.page' => function( $query ){ //changed
                            $query->orderBy('order', 'ASC');
                        }])
                        ->where('parent_id', '<', 1)
                        ->orderBy('order', 'ASC')
                        ->get();

It doesn't work as well because page doesn't have 'order' field to be sorted by. Being confused, I tried this:

$navigations = Navigation::with('page') ->with(['child_menus' => function( $query ){ $query->orderBy('order', 'ASC'); }]) ->with('child_menus.page') // changed ->where('parent_id', '<', 1) ->orderBy('order', 'ASC') ->get();



And it still returns null !




"child_menus" => Collection {#521 ▼
          #items: array:1 [▼
            0 => Navigation {#525 ▼
              #fillable: array:4 [▶]
              #connection: null
              #table: null
              #primaryKey: "id"
              #keyType: "int"
              #perPage: 15
              +incrementing: true
              +timestamps: true
              #attributes: array:7 [▶]
              #original: array:7 [▶]
              #relations: array:1 [▼
                "page" => null   <---- WHY!!!?
              ]
              #hidden: []




Am I doing something wrong here?


Thanks!
03 May
1 year ago

SangminKim started a new conversation Different Php Version In Valet

Hello,

My valet seems to use php 5.6.36 while running php -v in terminal returns 7.2.5. Where and how can I change the php version that Valet uses?

➜  ~ php -v
PHP 7.2.5 (cli) (built: Apr 26 2018 12:05:41) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
    with Zend OPcache v7.2.5, Copyright (c) 1999-2018, by Zend Technologies
➜  ~ which php
/usr/local/bin/php
➜  ~ brew services list
Name    Status  User Plist
dnsmasq started root /Library/LaunchDaemons/homebrew.mxcl.dnsmasq.plist
mysql   started gt   /Users/gt/Library/LaunchAgents/homebrew.mxcl.mysql.plist
nginx   started root /Library/LaunchDaemons/homebrew.mxcl.nginx.plist
php     started root /Library/LaunchDaemons/homebrew.mxcl.php.plist
[email protected] stopped
[email protected] stopped
[email protected] started gt   /Users/gt/Library/LaunchAgents/[email protected]
➜  ~
From phpinfo() ...


Configuration File (php.ini) Path   /usr/local/etc/php/5.6
Loaded Configuration File   /usr/local/etc/php/5.6/php.ini
Scan this dir for additional .ini files /usr/local/etc/php/5.6/conf.d
Additional .ini files parsed    /usr/local/etc/php/5.6/conf.d/ext-xdebug.ini, /usr/local/etc/php/5.6/conf.d/php-memory-limits.ini


Core
PHP Version 5.6.36

Thanks!

11 Dec
1 year ago

SangminKim started a new conversation Best Way To Count Already Eager Loaded Data With Certain Values.

Hi, I have three models: Project, Milestone (belongs to Project), Task (belongs to Milestone). Using eager loading, I could load all the milestones and their tasks. Now, What I wanna do is to count all the finished/unfinished tasks under each milestone and display on a page using foreach.

I could come up with two different solutions for this:

  1. Loop and count whatever needs to be counted in a controller and pass it to a view.

This works but lots of nested loops will be created. If there's a way to filter eager loaded values, this method is kinda wasting time.

  1. Give a model some sort of way to filter values.

I looked up scope prefix but it filters rows in 'database' not already queried rows. I thought about using

public function finished(){
    return $this->is_finished == 1;
}

and doing something like the following on the milestone level

//...

count( $project->milestone->tasks->finished )

//...

Still haven't tried this method yet but still not sure if it's the best.

are there any other better ideas out there that I haven't realize?

16 Sep
1 year ago

SangminKim started a new conversation Any Good Single Image Uploader?

Hi,

Im currently using closify(http://www.itechflare.com/closify/theme/) which works pretty well. This has preview, image cropping(by repositioning the image), trashing it... and etc.

The only problem with this plug-in is that it's old and outdated. And It seems I cannot make it responsive even if the documentation says it has a responsive option.

The uploader I'm looking for will be used only for uploading a user's avatar image. Nothing else.

Do you know any good plugin out there?

If it works somewhat like facebook. It will be awesome!

Commercial plugins are okay

Thanks, heros!

05 Sep
1 year ago

SangminKim left a reply on Best Way To Dynamically Load Partial Blade.

Hmmmm... i wish it to be more in-depth session regarding the issue i had... but it seems it's handling things in general... still useful tho.

04 Sep
1 year ago

SangminKim left a reply on Best Way To Dynamically Load Partial Blade.

@tisuchi No tisuchi!! That's a perfect one! Thanks!!