muzafferdede

muzafferdede

Developer at Taiwan

Member Since 4 Years Ago

Experience Points
52,450
Total
Experience

2,550 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
508
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 11
52,450 XP
Mar
30
1 week ago
Activity icon

Replied to Error While Trying To Run Npm Watch, Possible Incompatibility?

SassError: Incompatible units rem and px.
    ╷
729 │ $nav-link-height:                   $font-size-base * $line-height-base + $nav-link-padding-y * 2 

it's says you have incompatible units calculation. Make sure the math is correctly done with right units. and use (##+##) * (##/##) kind of operations for priority

Mar
10
4 weeks ago
Activity icon

Replied to Question Mark In Raw Sql Query Cause Problem

DB::select('*')->from('event')->where('event.repeat_every->daysInWeekRepeat','mon')
Mar
09
4 weeks ago
Activity icon

Replied to Question Mark In Raw Sql Query Cause Problem

consider using sub queries

Activity icon

Replied to Laravel - Composer Update To 7.0 - Now 500 Error

Have you consider to look at storage/logs/ and see what it says there ?

Activity icon

Replied to Need Help Converting Complex MySQL Query

as far as i know you can't do it that way because it's requires 2 queries. You should try to use whereColumn query i think will give you what you need. You can compare columns instead of values

Feb
25
1 month ago
Activity icon

Started a new Conversation Need Help For A Query To Be Solved.

Hi, i am trying to figure out the right query to achieve a Total Targets, Total Sales summary table.

#Relitionships

- A `store` has many `sales`
- A `store` has many `targets`

- A `target` belongs to a `store`
- A `sale` belongs to a `store`

#stores table

| id | name    |
|----|---------|
| 1  | Store A |
| 2  | Store B |

#targets table


| id | store_id | apply_date | amount |
|----|----------|------------|--------|
| 1  | 1        | 2020/01/01 | 100    |
| 2  | 2        | 2020/01/01 | 150    |
| 3  | 1        | 2020/02/01 | 300    |
| 5  | 2        | 2020/01/01 | 400    |
| 6  | 1        | 2020/03/01 | 250    |

#sales table

| id | store_id | sale_date  | sub_total |
|----|----------|------------|-----------|
| 1  | 1        | 2020/01/25 | 1000      |
| 2  | 1        | 2020/01/26 | 2300      |
| 3  | 2        | 2020/01/02 | 120       |
| 4  | 1        | 2020/02/11 | 2340      |
| 5  | 2        | 2020/03/22 | 4022      |

I have a date filter applied to the query which filters the sales sale_date by range. What i am trying to do is sum targets amount multiple by days in date range. And sum sub_total of the sales within the date range. But targets amount might differer depending on the sale_date. So if a sale made within the selected ranges, i need to add 1x of the targets amount into sum of targets amount.

So as in the example data i provided, Store A has 3 sales and Store B has 1 sale within the date range. I don't have a problem with the sum of the total_sales but i have issue with the sum of targets amount. I need to sum targets amount within the date range (month) for each store as

  • 2x 100 + 1x 200 = 500 for Store A
  • 1x 150 = 150 for Store B

My Query is something like this now, which i know it's not the way to achieve. But i give as sample what i have in my hands now.

$query =Store::query();

$query->select(
   'stores.name',
   DB::raw('sum(targets.amount) as total_targets'),
   DB::raw('sum(sales.sub_total) as total_sales'),
)
->join('sales', function ($sale) {
   $sale->on('sales.store_id', 'stores.id');
})
->join('targets', function ($target) {
    $target->on('targets.store_id', 'stores.id');
})
->whereBetween('sales.sale_date','2020/01/01 00:00:00','2020/02/15 23:59:59')
->groupBy('stores.id', 'stores.name');

what output result i expect:

| name    | total_targets | total_sales |
|---------|---------------|-------------|
| Store A | 500           | 5760        |
| Store B | 150           | 120         |

Hope it is clear enough and i am looking forward for your help. Thanks.

Activity icon

Replied to AddSelect Not Working As I Think It Should

Did. you figure out this issue?i am facing the same thing. In laracast Jeff's sample, it's can detect the column but why in our cases it's says unknown column? As in your sample DB::table('inspections') you are starting your query with this table so it's should be possible to reference the columns in addSelect.

Feb
10
1 month ago
Activity icon

Replied to Simple Way Of Deep WhereHas

This is a laravel nova filter i am trying to make it work for multiple cases where there might be some queries has to be done to parent first like, i have a sale which is belongs to a store. And this sale has many sale_items. To find out which sale_item is belongs to which store, i have to first do a whereHas('sale') then on that i can filter the by store. But i also use same filter on other resources which has store_id on them. So i can just do my query as $query->where('store_id',$value). I know it's a bit weird to do so and i believe there is easier way to do so, so i ask if there is easier way to do it.

Feb
09
1 month ago
Activity icon

Started a new Conversation Simple Way Of Deep WhereHas

I have a case where i need to query multiple level of whereHas method on the model, which i need to loop through an array to figure out the how deep it will go. As in the example:

public function apply(Request $request, $query, $value)
{
    return $query->whereHas('sales', function ($sale) use ($value) {
        $sale->whereHas('stores', function($store) use ($value) {
             $store->where('id',$store);
        });
    });
}

i would like to achieve this using a loop something like dynamic as:

$this->parents = ['sale','store'];
...

return $query->when($this->parents, function ($query, $parent) use ($value) {
    $query->whereHas($parent[0].'s', function ($parent1) use ($value) {
        $parent1->whereHas($parent[1].'s', function ($parent2) use ($value) {
            $parent2->where('id', $value);
        });
    });
}, function ($query) use ($value) {
    $query->where('id', $value);
});

any easy way to achieve this? Thank you

Feb
02
2 months ago
Activity icon

Started a new Conversation Laravel Nova Event Listener

Hi,

How do we listen an event outside of Nova component?I have a custom card which i would like show sum of some columns in a lens table after filter change event and react on that.


Nova.$on('change',function()
{
    alert('filter changed');
});

But i can't get it work. Or these filter events are not globally broadcasted to other components?

Jan
03
3 months ago
Activity icon

Awarded Best Reply on Any Suggestions To Improve This Piece Of Code?

Cool, That is what i needed. I use it this way:

    public function applyFiltersToModel($request, $model)
    {
        $request->range = optional($request)->range ?? 3600;
        $model = $model instanceof Builder ? $model : (new $model)->newQuery();

        $requestFilters = collect($request->all())->filter(function ($value, $key) {
            return class_exists($key);
        });

        foreach ($requestFilters as $filter => $value) {
            $model = resolve($filter)->apply($request, $model, $value);
        }

        return $model;
    }

i already validated requestFilters if class exists so then i can just apply it as you said from the service container without recalling it. Thanks.

Activity icon

Replied to Any Suggestions To Improve This Piece Of Code?

Cool, That is what i needed. I use it this way:

    public function applyFiltersToModel($request, $model)
    {
        $request->range = optional($request)->range ?? 3600;
        $model = $model instanceof Builder ? $model : (new $model)->newQuery();

        $requestFilters = collect($request->all())->filter(function ($value, $key) {
            return class_exists($key);
        });

        foreach ($requestFilters as $filter => $value) {
            $model = resolve($filter)->apply($request, $model, $value);
        }

        return $model;
    }

i already validated requestFilters if class exists so then i can just apply it as you said from the service container without recalling it. Thanks.

Activity icon

Replied to Any Suggestions To Improve This Piece Of Code?

hmm, decision has to be made in this trait, i can't decide it in the filter because filter is applied multiple resource. What i am looking for is a way to compare 2 arrays and if match call that filter. BTW filters has some parameters passed at __construct so i have to call all the matches $this->filters() in $requestFilters array.

Jan
02
3 months ago
Activity icon

Replied to Any Suggestions To Improve This Piece Of Code?

could you give me a sample code?

Jan
01
3 months ago
Activity icon

Started a new Conversation Any Suggestions To Improve This Piece Of Code?

Hi, i am not too happy with the way foreach works now. Is there any suggestions you guys can give me to improve it? I believe there could be many collection ways to do it. All i am trying to do is compare 2 arrays and if they match, call the method. Here is the code:

public function applyFiltersToModel($request, $model)
    {
        $request->range = optional($request)->range ?? 3600;
        $model = $model instanceof Builder ? $model : (new $model)->newQuery();

        $requestFilters = collect($request->all())->filter(function ($value, $key) {
            return class_exists($key);
        });

    // requestFilters will return array of filters such as 
    // 'App\Nova\Filters\Store' => 5
    // 'App\Nova\Filters\Date' => '2020-01-01'
    

    //$this->filters() will return array of filters such as
    // 0 => 'App\Nova\Filters\Store'
    // 1 => 'App\Nova\Filters\Date'

        foreach ($this->filters() as $filter) {
            foreach ($requestFilters as $requestFilter => $value) {
                if ($filter instanceof $requestFilter) {
                    $model = $filter->apply($request, $model, $value);
                }
            }
        }

        return $model;
    }

    public function filters()
    {
        return [
            new Store('sale'),
            new Date('sale_date', 'sale'),
        ];
    }

As you can see, i am trying to find out if the request contains any filter, if it's does, i call apply method of that filter.

Nov
23
4 months ago
Activity icon

Replied to How To Group Relation Column In Nova Metrics

could you be more specific?

Activity icon

Replied to What Is The Best Way To Show Summary Of Table With Laravel Nova?

Hi, i have tried using metrics but i am not sure how to apply resource filters on metrics. I use lenses because i am summarizing a model resource. So lens has filters needs to be applied then i can summarize it and show it in a way. I wish there was an option to show a table result using actions but i guess there is not yet such a way.

Nov
21
4 months ago
Activity icon

Started a new Conversation What Is The Best Way To Show Summary Of Table With Laravel Nova?

Hi, i am trying to show summary of the total of values as mentioned here

It's shouldn't be so difficult i guess but i can't find a way. I am trying to achieve this using lens. I need to show total of column values in someway.

Please let me know if you have any idea. Thanks

Nov
20
4 months ago
Activity icon

Replied to Access Model Data In A Nova Card

+1

Did you sort it out?

Activity icon

Replied to Using Metrics With Relations

i end up use like so for one of my metrics. you can use eloquent. i was defining as SaleItem::class but then i changed it and now i could filter out with the way i want. you can also use with() method to eager load your relations


return $this->count($request, SaleItem::where('salable_type', Token::class)->with('salable'), 'salable_id', 'token_type')->label(function ($value) {
            return  $value . ' Token';
        });
Nov
19
4 months ago
Activity icon

Started a new Conversation How To Group Relation Column In Nova Metrics

hi, i am trying to group Partition metrics by relation but i am not sure how to select relation table column name, what i am trying to do is:


    public function calculate(NovaRequest $request)
    {
        return $this->count($request, SaleItem::where('salable_type', Product::class), 'salable.name', 'quantity');
    }

i got error unknow salable.name colmun name error.

What is the correct way to do so?

Activity icon

Replied to Using Metrics With Relations

+1 Did you find any solution?

Nov
02
5 months ago
Activity icon

Replied to How To Re-construct A Class In Single Process?

Thanks for the replay,

Unfortunately i figure out that was not the only problem i was having. There was other instance needed to be re-construct like middlewares, routes, request, etc.. So couldn't renew one by one manually, so i found another path which is making requests with new kernel instance. So each time i am done with the request in loop, i can terminate it.

private function handleRequest($data, ConnectionInterface $connection)
    {
        if ($params = $this->initRequest($data, $connection)) {
            $app = require app()->basePath() . '/bootstrap/app.php';
            $kernel = $app->make(Kernel::class);
            $request = Request::create('/api', 'POST', $params);
            $response =  $kernel->handle($request);
            if (!empty($response)) {
                $response = json_decode($response->getContent());
                $clients = $response->data->devices ?? [$this->getConnectionToken($connection)];
                if (isset($response->data->devices)) {
                    unset($response->data->devices);
                }
                $this->sendDataTo($response, $clients);
            }
            $kernel->terminate($request, $response);
        }
    }

The down side of this approach is i need to build a new kernel each time i need to do a request.

The up side of this approach is that now i can use service providers to add singletons and use them as i wish in anywhere. Considering that this application wont handle too many requests, i think it's the best way i can find so far.

Nov
01
5 months ago
Activity icon

Started a new Conversation How To Re-construct A Class In Single Process?

Hi, Is there any way i can reconstruct my controller classes after some method calls?

Because i am doing some logic in "while" loop and i need to re instance some classes to update its properties during same process.

for now i am doing it with


    public function status()
    {
        $this->__construct();
        return $this->successful($this->device);
    }
public function register()
    {
        $this->__construct();
        $device = Device::updateOrCreate(
            [
                'serial_number' => $this->request->serial_number,
            ],
            [
                'name' => $this->request->serial_number,
                'type' => $this->request->type,
                'properties' => $this->request->properties,
            ]
        );

        return $device->save() ? $this->successful($device) : $this->failed(15);
    }

    public function activate()
    {
        $this->__construct();
        $device = Device::whereActivationCode($this->request->activation_code)
            ->whereSerialNumber($this->request->serial_number)
            ->first();

        if (!$device) {
            return $this->failed(9);
        }

        if ($device->activated) {
            return $this->failed(10);
        }

        $store = Store::whereUid($this->request->uid)->first() ?? $device->store;
        if (!$store) {
            return $this->failed(0);
        }

        $device->store()->associate($store);
        $device->activated = now();
        $device->api_token = Str::uuid();
        $device->save();

        return $this->successful($device);
    }

as you can see, all my methods has to re-construct to renew its properties. I can't kill the process because i am listening a socket for new events. Because of this, application only can boot 1 time. I am not sure how can i renew the existing instances in the application container. I would like to use service provider to achieve it. And update the singleton anytime new events causes.

any advice? Thanks.

Oct
30
5 months ago
Activity icon

Started a new Conversation How To Include Host Ip Adress In Artisan Command With Supervisor

Hi i am trying to make my supervisor config file gets ip address of host using this way:

[program:socket-server]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/atm/artisan socket-serve --host=$(hostname -I)
autostart=true
autorestart=true
user=laxan
numprocs=1
redirect_stderr=true
stdout_logfile=/var/www/atm/storage/logs/socket-server.log

as you can see i reference the host ip adress using $(hostname -I)

when i run this command in termina, it's works and finds the ip adress correctly but running with supervisor gives me error which says i cant use $(hostname -I) in the string because of the format error. How can i reference ip address of host in command?

Thanks

Oct
24
5 months ago
Activity icon

Replied to Laravel Sockets - Need Advice

did you checkout reactphp?

Activity icon

Started a new Conversation TCP Socket Connection Between Laravel And Socket Server Using Reacthphp

I have posted in reactphp github but maybe someone here would be interested to give me some idea. if you quickly checkout this github post.

Basically i am trying to make a socket server and client with laravel.

I have done almost 90% of what i want to do but i am stock with a logic issue and can't figure it out.

To make it more clear:

  • There is a Remote Socket server (Laravel App) (running as daemon)
  • There is a Local Socket Client (Laravel App) (running as daemon)
  • Socket Client did connect to Socket Server using php artisan command and said "hi"
  • Socket Server got this message and said "hi back"

Until here every thing is fine. My issue starts when:

Let's say sometime in future one of the API request needs to send a request to Socket server and get response from it. How can i reference the existing connection from API controller to send it a write command ?

Should i use service providers? i don't know... :(

Oct
16
5 months ago
Activity icon

Replied to Any Difference Between Defining Relationships With 'App\Model' And Model::class

Thanks for the answers. Yeah, there is not much difference between them. I found some detailed explanation.

` When you have ::class in your code, what actually happens is that PHP takes the name of the class you've specified and generates the fully-qualified namespaced classname as a string. So yes, this does indeed mean that you're getting the computer to do more work than if you'd just supplied a string.

However, it does this at compile time. This means that it will only ever do it once, and it happens outside of the bounds of your program runtime. Therefore your Benchmark performance timer won't take it into account -- in fact when your code runs, it just sees a string, which means that what you're actually benchmarking is the program doing virtually exactly the same thing in both scenarios. Any difference in timing between the two is an artifact and can be ignored.

The other important point about it being done at compile time is that if you have OpCache enabled then it will only ever have to convert the string once, the first time you run it, which means that there's even less of a difference between the two.

The ::class syntax wasn't added to the language for performance reasons; it was added because it helps with code quality, readability and maintainability. And frankly, those factors are almost always far more important than micro-optimised performance.

Further clarification on bencharking Since it's done at compile time, you can't get an accurate benchmark for it from inside of the PHP program.

If you really want to benchmark it, your best option would be to write a shell script with a timer and call the program from there. You'll need to have a separate PHP program for each variation. But even then, any benchmark results you get will be somewhat artificial and unlikely to be useful in any meaningful way. You'll get different results depending on whether you run multiple loops in a single instance of the program or have the loop in the shell script. You'll also get different results if you have OpCache enabled.

But ultimately, you really shouldn't even be thinking about whether to benchmark this -- it's a syntax nicety; it doesn't affect performance. Or if it does, the effect is so tiny that it's not worth thinking about.

The secret of good performance tuning is to find the biggest bottlenecks in your code, and deal with them first. Not the smallest. `

Activity icon

Started a new Conversation Any Difference Between Defining Relationships With 'App\Model' And Model::class

I would like to know benefits or reasons when defining relationships or any other class reference definitions. For example

between

    public function profile()
    {
        return $this->belongsTo('App\Profile');
    }

and

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

Replied to Newly Created Model Returns Only Few Attributes

i went with $account->refresh() and it worked. Thanks. Nice to know it was default behavior

Activity icon

Started a new Conversation Newly Created Model Returns Only Few Attributes

i am trying to make a new Account using create method with default values in migration but when i try to return the newly created account, only few attributes are returning with the instance.

        $account = Account::create();

            $this->card->activate($account, $this->device->store);
            return Response::success($account));

this returns

{
  "updated_at": "2019-10-16 06:59:46",
  "created_at": "2019-10-16 06:59:46",
  "id": 12
}

if i do this which is what i need as return

$account = Account::create();

$this->card->activate($account, $this->device->store);
return Response::success($account->find($account->id));

then i get

  {
    "id": 12,
    "profile_id": null,
    "membership": "anonymous",
    "tokens": 0,
    "tickets": 0,
    "points": 0,
    "created_at": "2019-10-16 07:04:41",
    "updated_at": "2019-10-16 07:04:41",
  }

all attributes has default value in db so newly created model should have all those default values. I don't know why model instance returns only id and timestamps from create method. am i missing something?