mecjos

mecjos

Member Since 2 Years Ago

─░stanbul

Experience Points
3,080
Total
Experience

1,920 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
7
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

Level 1
3,080 XP
Oct
14
6 days ago
Activity icon

Replied to Laravel Appended Accessor Causes Slow Response

It's already eager loading but very slow again.anyway, It seems I will need to remove appended accessor.. Thanks all..

Activity icon

Replied to Laravel Appended Accessor Causes Slow Response

@snapey thanks for your advice.. but I already know which part of code makes slow my response.. I look for a solution for that.. If you know a solution please help... I debugged it already by myself.. It's obvious that appended accessor with relation is problematic..

Activity icon

Replied to Laravel Appended Accessor Causes Slow Response

My app is vue spa and my laravel is an api server.. I guess I can't use debugbar directly for my app.. I don't want to make complecated arrangements for debugging. If you know that problem because of too many query and my usege of appended accessors, could you give alternative solution if you know please?

Oct
12
1 week ago
Activity icon

Replied to Laravel Appended Accessor Causes Slow Response

When I remove appended accessor from model it works normal.. Might be a problem on my appended accessor? I don't think it's because of too many queries.

Oct
11
1 week ago
Activity icon

Started a new Conversation Laravel Appended Accessor Causes Slow Response

Hi. An appended accessor makes very slow the response (about 30 seconds.).. I'll try to explain with codes below..

My problematic eloquent model is :

$machines = Machine::where($condition)->with(['jobs' => function ($query) { $query->orderBy('queue', 'asc');
    },'jobs.part.image', 'jobs.project.customer', 'jobs.state.stateLang', 'operator.image'])->get();

eager loaded project relation in my model jobs.project.customer has appended accesssor as follow:

Project Model:

    protected $appends = ['stats'];

    public function getStatsAttribute()
     {
         return (new ProjectController)->stats($this->id);
     }

I use that attribute to attach project progress for every project record. Actually I don't need that in my problematic collection but it gets. And my function in which I calculated stats is as follow:

public function stats($id)
{
    $totalJobs = 0;
    $totalCompletedJobs = Job::where('project_id', $id)->where('state_id', '!=', 4)->sum('completed');
    foreach (Job::where('project_id', $id)->where('state_id', '!=', 4)->cursor() as $job) {
        $part = Part::find($job->part_id);
        $totalJobs = $totalJobs + $part->quantity;
    }
    return ['totalJobs' => $totalJobs, 'totalCompletedJobs' => (int)$totalCompletedJobs];
}

Is that method wrong to get stats in that appended attribute way? Besides, actually I don't need project stats in that $machine collection, when getting project.customer relation it takes that accessor also. How Can I do that in correct way? Can I cancel appended attribute for once for any query?

Edit: Additionally, this works very fast (around 300ms) on localhost. On shared server it takes about 30 seconds. Is that difference in possible range?

Oct
10
1 week ago
Activity icon

Replied to Too Long Response Time

I tried clockwork.. I found the exact part of code to cause slowness.. Wrote above.. Now my question changed.. Whey appended attribute makes it slow? Is that wrong way ?

Activity icon

Awarded Best Reply on Too Long Response Time

I don't know How can I see raw queries which laravel eloquent use to take data from database.. By the way I found the exact reason of my problem.. My project model has appended attribute as follow:

    protected $appends = ['stats'];


public function getStatsAttribute()
    {
        return (new ProjectController)->stats($this->id);
    }

to take project statistics I calculate completed jobs etc. in ProjectController and append it project model like above. This function makes it slow.. but I don't understand why it's faster on local..

Activity icon

Replied to Too Long Response Time

I have

1 record in project table 114 records in parts table 237 records in jobs table

Activity icon

Replied to Too Long Response Time

I don't know How can I see raw queries which laravel eloquent use to take data from database.. By the way I found the exact reason of my problem.. My project model has appended attribute as follow:

    protected $appends = ['stats'];


public function getStatsAttribute()
    {
        return (new ProjectController)->stats($this->id);
    }

to take project statistics I calculate completed jobs etc. in ProjectController and append it project model like above. This function makes it slow.. but I don't understand why it's faster on local..

Activity icon

Replied to Too Long Response Time

There are machine,jobs,parts,customers,images,states,statelang tables on that query.

Activity icon

Replied to Too Long Response Time

$condition = $userRole === 'employe' ? [['employe_id', Employe::where('user_id', Auth::id())->first()->id]] :
            [['user_id', Auth::user()->parent_user_id]];
        $machines = Machine::where($condition)->with(['jobs' => function ($query) { $query->orderBy('queue', 'asc');
        },'jobs.part.image', 'jobs.project.customer.image', 'jobs.state.stateLang', 'operator.image'])->get();

I use that model to take data.. max 100 records on each table... when I get only

->with('job')->get()

it's normal... could it be couse of too many relations??

Activity icon

Replied to Too Long Response Time

I found... query codes below takes 30 seconds on shared server.. but I don't know why?? Is there any answer?

$machines = Machine::where($condition)->with(['jobs' => function ($query) { $query->orderBy('queue', 'asc');
        },'jobs.part.image', 'jobs.project.customer.image', 'jobs.state.stateLang', 'operator.image'])->get();
Activity icon

Replied to Too Long Response Time

I don't know clockwork.. is there any guide?

Activity icon

Replied to Too Long Response Time

How Can I see which code line how many time takes?

Activity icon

Replied to Too Long Response Time

I fetch similar amount of data on production server.. There might be some costly process in my Dashboard controller stats method..

Activity icon

Replied to Too Long Response Time

382 ms locally, 31.13s on shared server.. This difference doesn't make sense..

Activity icon

Started a new Conversation Too Long Response Time

Hi. I am working on a project planing and tracking app. I want to show some stats on dashboard (percentage of completed, pending and canlled job). In my project structure I have project model, part model related with projects and job model related with parts. Part can be more than one as quantity and there is several type of jobs which one part can has. Briefly, I use following codes to get stats on dashboard and it takes 33 seconds on shared server. It's faster on local.

$jobs = Job::where('user_id', Auth::user()->parent_user_id)->get();
       $totalJobs = 0;
       foreach (Job::where('user_id', Auth::user()->parent_user_id)->where('state_id', '!=', 4)->get() as $job) {
           $part = Part::find($job->part_id);
           $totalJobs = $totalJobs + $part->quantity;
       }
       $completed = $jobs->where('state_id', '!=', 4)->sum('completed');
       $completedPercentage = round(($completed/$totalJobs)*100, 0);
       $pending = $jobs->where('state_id', 1)->count();
       $pendingPercentage = round(($pending/$totalJobs)*100, 0);
       $cancelled = $jobs->where('state_id', 4)->count();
       $cancelledPercentage = round(($cancelled/$jobs->count())*100, 0);
       $userRole = User::with('roles')->where('id', Auth::id())->first()->roles->first()->name;
       $condition = $userRole === 'employe' ? [['employe_id', Employe::where('user_id', Auth::id())->first()->id]] :
           [['user_id', Auth::user()->parent_user_id]];
       $machines = Machine::where($condition)->with(['jobs' => function ($query) { $query->orderBy('queue', 'asc');
       },'jobs.part.image', 'jobs.project.customer.image', 'jobs.state.stateLang', 'jobs.part.cads', 'operator.image'])->get();
       $dashboardData = [
           'stats' => collect([
               'totalJobs' => $totalJobs,
               'completed' => ['number' => $completed, 'percentage' => $completedPercentage],
               'pending' => ['number' => $pending, 'percentage' => $pendingPercentage],
               'cancelled' => ['number' => $cancelled, 'percentage' => $cancelledPercentage]]),
           'machines' => $machines
       ];
       $collected = collect($dashboardData);
       return New DashboardCollection($collected);

There is something wrong in my code.. How can I make it faster..

Thank you.

Sep
09
1 month ago
Activity icon

Replied to Using Condition In Promise

@boubou thanks for your reply.. Maybe it will work but I can't put my condition into switch.. My response.data returns an object and it has three object arrays, one is when status is ok db record object and others if exist some warnings about records.. I mean I need to put something like follows in switch;

response.data.someWarnings.length > 0 

how Can i do this?

Activity icon

Started a new Conversation Using Condition In Promise

Hi. I want to use condition for promise response.. How Can I use conditions in promise? My codes are as follows. That doesn't work...

this.$store.dispatch('CreateJob', params).then(response => {
        if (response.warnings.length > 0) {
          this.$q.notify({
            type: 'negative',
            message: 'Some warnings.',
            position: 'top',
            timeout: 2000
          })
        }
      }).then(response => {
        if (response.someOtherWarning.length > 0) {
          this.$q.notify({
            type: 'negative',
            message: 'Some other warnings.',
            position: 'top',
            timeout: 2000
          })
        }
      }).then(response => {
        if (response.job.length > 0) {
          this.$q.notify({
            type: 'positive',
            message: 'Well done.',
            position: 'top',
            timeout: 2000
          })
        }
      }).catch(error => {
        this.$q.notify({
          type: 'negative',
          message: error.response.data.message,
          position: 'top',
          timeout: 2000
        })
      })

dispatch('createJob') runs a promise..

Jul
19
3 months ago
Activity icon

Replied to Determining Eloquent Related Model Foreign Key

@snapey by the way... there is another way.. Actually relatedKey , in following doc, argument is the one I desire.

https://github.com/laravel/framework/blob/7.x/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php#L149

Activity icon

Awarded Best Reply on Determining Eloquent Related Model Foreign Key

I found a solution ...

first determined the primary key on top of the User model..

protected primaryKey = 'id'    // default primary key

then I changed it in relation method...

public function modules () {
        $this->primaryKey = 'parent_user_id';
        return $this->belongsToMany('App\Module', 'user_modules', 'user_id');
    }

Determine the foreign_key again because it tries to add 'user_' prefix to new primary key as default.

Activity icon

Replied to Determining Eloquent Related Model Foreign Key

@snapey I only need parent_user_id in modules function.. in other ralations it must be id.. I can't change column's name.. that works, thank you.

Activity icon

Replied to Determining Eloquent Related Model Foreign Key

I found a solution ...

first determined the primary key on top of the User model..

protected primaryKey = 'id'    // default primary key

then I changed it in relation method...

public function modules () {
        $this->primaryKey = 'parent_user_id';
        return $this->belongsToMany('App\Module', 'user_modules', 'user_id');
    }

Determine the foreign_key again because it tries to add 'user_' prefix to new primary key as default.

Activity icon

Replied to How To Change Primary Key Of Related Model In BelongsToMany Relationship ?

add primary key to model

class User extends Authenticatable
{


    protected $primaryKey = 'id';

then change it in relation method:

public function directories () {
	$this->pirmaryKey = 'provider_id';

 // and determine the foreign_key becaues it will try to 'user_' prefix to new primaryKey to create default primary key.
return $this->belongsToMany(\App\Models\Provider::class, 'directories', 'user_id', 'provider_id');
}

that's all..
Activity icon

Replied to Determining Eloquent Related Model Foreign Key

@snapey thank you.. I read the docs but the thing I want a bit different.. In my situation, user_id is foreign key in user_modules table. As default id column of users table pairs user_id in modules table.. I want to pair parent_user_id column in users table with user_id in modules table.. as if parent_user_id column is primarykey.

Activity icon

Started a new Conversation Determining Eloquent Related Model Foreign Key

Hi... I have a Module model related with User model.. I have a following relationship in User model:

public function modules () {
        return $this->belongsToMany('App\Module', 'user_modules');
    }

In this relationship laravel searchs User model's id in Module model as user_id.. I have parent_user_id column in users table and I want User model's parent_user_id as a foreignKey in Module model.. How can I do that?

Jun
28
3 months ago
Activity icon

Started a new Conversation Assigning More Than One Selectbox V-model To Data

Hi, I have list and each item has selectbox as follows..

<q-list>
	<q-item>
		<q-select :options="options" v-model="selection"></ q-select>
	</q-item>
	<q-item>
		<q-select :options="options" v-model="selection"></ q-select>
	</q-item>
</q-list>

How Can I use v-model for each select-box separately. In current situation when I choose one it affects all of them. I can make it by creating component for each item but if it's possible I want to solve it easier way.

Activity icon

Replied to MapWithKeys() Collection Method Problem

@snapey it gives collection. there is another mistake that I couldn't find.

Jun
27
3 months ago
Activity icon

Replied to MapWithKeys() Collection Method Problem

@snapey an object array as follows ;

[
{"id":1,"user_id":1,.................},
{"id":2,"user_id":1,.................},
......
......
]
Activity icon

Started a new Conversation MapWithKeys() Collection Method Problem

Hi, I have a model with jobs properties as follows,,

$machineJobs = Machine::find($request->machine)->jobs;

When I try to apply mapWithKeys() collection method o this query I get error "Invalid argument supplied for foreach()".. Where is my problem?

$machineJobs->mapWithKeys(function ($item) {
                return $item['queue'];
            });

Activity icon

Replied to Using Global Variable In Eloquent Model Query

@deepu07 Thank you.. That worked.

Activity icon

Started a new Conversation Using Global Variable In Eloquent Model Query

Hi. I am trying to use a variable where is outside of model query inside it as following codes but it doesn't work. Normally I can use it inside function by making global..

public function setPriority ($id) {
        $affectingJob = Job::find($id);
        $machine_id = 1;
        $affectedJobQueue = Job::where([['state_id', 1],['user_id', Auth::user()->parent_user_id]])->with(['order' => function ($query) {
            global $machine_id;
            $query->where('machine_id', $machine_id);
        }])->get()->min('queue');

what's the problem in my code??

Jun
04
4 months ago
Activity icon

Started a new Conversation A Life Cycle Or Data Getting Method Error

Hi. I am using quasar frame work for my project and I am getting an error while getting quasar table data from vuex state while routing.. I think I have a getting sequence or life cycle error but I couldn't solve it. My codes as follows. I will try to explain.

my quasar table

 <q-table :data="pageContent" :columns="columns" row-key="id" @row-click="rowClicker" selection="multiple" :selected.sync="selectedItems">

I fetch page content with mounted () hook and attach it to a vuex state as follows ;

mounted () {
    const params = { url: '/employes' }
    this.$store.dispatch('GetList', params)
    this.getDeptList()
  }

Vuex state

const state = {
  pageContent: []
}
export default state

I watch pageContent state with a mapstate in computed method ;

computed: {
    ...mapState(['pageContent']),
}

when I refresh page this structure works well but when I route to another page new page still trying to get older state object and table gives error..

ailed for prop "data". Expected Array, got Object 

found in

---> <QTable>
       <QCardSection>
         <QCard>
           <QPage>
             <Anonymous>
               <AppMain> at src/pages/components/AppMain.vue
                 <QPageContainer>
                   <QLayout>
                     <MainLayout> at src/layouts/MainLayout.vue
                       <App> at src/App.vue
                         <Root>

I think vuex works slow. I need to sequence this actions. It tries to load table data before vuex set the state.. I tried to fetch action in beforeCreate hook but it's same. I need to load page dom after vuex set the pageContent state..

Is this possible or what do you suggest to get data? Or, which structure should be used to fetch data from database? Is setting page content to a vuex state a correct method?

Thank you