kgp43

kgp43

Member Since 4 Years Ago

Experience Points
7,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
74
Lessons
Completed
Best Reply Awards
0
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 2
7,450 XP
Oct
11
1 month ago
Activity icon

Replied to Storage::get() Works Fine, But Storage::download() Does Not. Why Is That?

This works, now sure why:

 return Storage::disk('public')->download($path);
Activity icon

Replied to Storage::get() Works Fine, But Storage::download() Does Not. Why Is That?

I have tried to add it directly in my routes file - just to test. It still tells me the path does not exist - even if it does.

Route::get('/motor/{id}/download/{type}', function($id, $type) {
    
    $motor = App\Motor::find($id);

    if($type == 'datasheet')
        $path = $motor->datasheet;
    
    if($type == 'drawing')
        $path = $motor->drawing;
    
    if($type == 'stepfile')
        $path = $motor->stepfile;
    
    return Storage::download($path);
    
});

using

Storage::get($path)

output the url to the file (/storage/RYLKjGD57Y66r7Ynz8fbtlgXbyE3xhMwSrMAxfcY.pdf)

Activity icon

Replied to Storage::get() Works Fine, But Storage::download() Does Not. Why Is That?

Hi @bobbybouwmann ,

Got a small followup question.

How would the link look like, if I got 3 different downloadable files for each motor? E.g. datasheet, stepfile, drawing?

Will something like this work?

/motor/{id}/datasheet/download/datasheet
/motor/{id}/datasheet/download/stepfile
/motor/{id}/datasheet/download/drawing

What about the controller?

I need to add the function to the Motor controller, i guess. But how do you integrate the "download type" in one function? Something like this maybe (will not work i think):

    # Download
    public function download(Motor $motor, $type) {
        
        if($type == 'datasheet')
            $path = $motor->datasheet;
        
        if($type == 'drawing')
            $path = $motor->drawing;
            
        if($type == 'stepfile')
            $path = $motor->stepfile;
        
        return Storage::download($path);
        
    }
Oct
07
1 month ago
Activity icon

Replied to Storage::get() Works Fine, But Storage::download() Does Not. Why Is That?

Thanks a lot. I know how to handle this now :)

Oct
06
1 month ago
Activity icon

Started a new Conversation Storage::get() Works Fine, But Storage::download() Does Not. Why Is That?

I got a weird problem.

I need to download a PDF file from blade. This is what I use now (it works), but it does not force download:

<a href="{{ Storage::url($configurator->motor->datasheet) }}" class="btn btn-sm btn-light ml-2" role="button">Download</a>

I then changed my coding to this:

<a href="{{ Storage::download($configurator->motor->datasheet) }}" class="btn btn-sm btn-light ml-2" role="button">Download</a>

But now I receive a file does not exist error. Even when the file exist. The symlink has already been created.

Any idea what can be wrong?

, kenneth

Sep
27
1 month ago
Activity icon

Replied to SortBy WhereIn Array

This is great guys! Working flawlessly now! Thanks for the help.

Had to change firstOrFail to first, or the loop would break after the first "fail" :)

Working code if anyone is interested:

            $priority_array = ['B14', 'B5', 'B34', 'B35'];
            
            foreach($priority_array as $element) {
                
                $motor = Motor::query()
                    ->where([
                        ['effect_id', '=', $request->effect_id],
                        ['poles', '=', $request->poles],
                        ['voltage_id', '=', $request->voltage_id],
                        ['active', '=', 1],
                    ])
                    ->whereHas('MotorSize', function (Builder $query) use ($element) {
                        $query->where('mounting', '=', $element);
                    })
                    ->first();
            
                if($motor) {
                    break;
                }
                
            }
Activity icon

Replied to SortBy WhereIn Array

@imawesome Very nice suggestion!

Do you know why I get "Undefined variable: element" error? It looks perfect to me.

            $priority_array = ['B14', 'B5', 'B34', 'B35'];
            
            foreach($priority_array as $element) {
                
                $motor = Motor::query()
                    ->where([
                        ['effect_id', '=', $request->effect_id],
                        ['poles', '=', $request->poles],
                        ['voltage_id', '=', $request->voltage_id],
                        ['active', '=', 1],
                    ])
                    ->whereHas('MotorSize', function (Builder $query) {
                        $query->where('mounting', '=', $element);
                    })
                    ->firstOrFail();
            
                if($motor) {
                    break;
                }
                
            }
Sep
26
1 month ago
Activity icon

Replied to SortBy WhereIn Array

Used about 6 hours on this today. Starting to drive to crazy... Most suggestions on Google, tell me to add the sortBy on the model - but the query is never sorted.

I hope someone will be able to help me.

I removed most of the stuff I tried today, since I believe this should work - but it does not. Decided to try to sortBy a new "priority" column. It contain integers.

Motor table:

        Schema::create('motors', function (Blueprint $table) {
            $table->increments('id');
            ...
            $table->string('motor_size_id');
            $table->timestamps();
        });

MotorSize table:

 Schema::create('motor_sizes', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name')->unique();
            $table->string('framesize'); // E.g. 80
            $table->string('mounting'); // E.g. B14
            $table->integer('priority'); // for sorting
            $table->timestamps();
        });

Motor model:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Motor extends Model
{
    
    ....
    
    public function MotorSize()
    {
        return $this->belongsTo('App\MotorSize')->orderBy('priority', 'ASC');
    }

Configurator store controller/method:

public function store(Request $request)
    {
        
        $validatedData = $request->validate([
            'effect_id' => 'required|numeric',
            'motor_size_id' => 'required|numeric',
            'poles' => 'required|numeric',
            'voltage_id' => 'required|numeric',
        ]);
        
        if($request->motor_size_id == 0) {
            
            # Sorting is done by the model
            # We only need the first result
            # The priority sorting on the model, makes sure we get the result we need
            
            $motor = Motor::query()
                ->where([
                    ['effect_id', '=', $request->effect_id],
                    ['poles', '=', $request->poles],
                    ['voltage_id', '=', $request->voltage_id],
                    ['active', '=', 1],
                ])
                ->whereHas('MotorSize', function (Builder $query) {
                    $query->whereIn('mounting', ['B14', 'B5','B34', 'B35']);

                })
                ->firstOrFail();
                
        }else{
        
            # Find a motor matching the requirements submitted by the user
            $motor = Motor::query()
                ->where([
                    ['effect_id', '=', $request->effect_id],
                    ['motor_size_id', '=', $request->motor_size_id],
                    ['poles', '=', $request->poles],
                    ['voltage_id', '=', $request->voltage_id],
                    ['active', '=', 1],
                ])
                ->firstOrFail();
            
        }
        
        //dd($motor);
        
        $conf = new Configurator;
        $conf->motor_id = $motor->id;
        $conf->wormgear_id = $motor->wormgear_id;
        $conf->save();
        
        # Redirect
        return redirect()->route('configurator.show', $conf->id);
        
    }

Why is my $motors not sorted by $motors->MotorSize->mounting('priority')? Isnt that what the model is doing right now? Or am i missing something?

I find it extremely hard to correct this, when there is no errors :(

Sep
25
1 month ago
Activity icon

Replied to SortBy WhereIn Array

@ftiersch Hi,

I have tried both suggestions, but the result is still the same (see reply above).

WIthin a with() call:

            $motor = Motor::with(['MotorSize' => function ($query) {
                $query
                    ->whereIn('mounting', ['B14', 'B5','B34', 'B35'])
                    ->orderBy('priority', 'ASC');
            }])->firstOrFail();

Do you know why I got these problems?

Activity icon

Replied to SortBy WhereIn Array

Hmm.. i have tried to add it on the model itself. I created a "priority" column to the model.

Have modified my Motor model:

    public function MotorSize()
    {
        return $this->belongsTo('App\MotorSize')->orderBy('priority', 'ASC');
    }

No change. It still pull the first table entries and not ordering using orderBy priority.

            $motor = Motor::query()
                ->where([
                    ['effect_id', '=', $request->effect_id],
                    ['poles', '=', $request->poles],
                    ['voltage_id', '=', $request->voltage_id],
                    ['active', '=', 1],
                ])
                ->whereHas('MotorSize', function (Builder $query) {
                    $query->whereIn('mounting', ['B14', 'B5','B34', 'B35']);

                })
                ->firstOrFail();

Have also tried something like this: (still no luck)

$query->where(function ($query) {
    $query->where('mounting', 'like', 'B14');
})
->orWhere(function($query) {
    $query->where('mounting', 'like', 'B35');   
})
->orWhere(function($query) {
    $query->where('mounting', 'like', 'B34');   
})
->orWhere(function($query) {
    $query->where('mounting', 'like', 'B5');    
});

@imawesome : Not sure how to do that. Do you have a link or something else, so I can read up on it?

Any input will be more than welcome.

Activity icon

Started a new Conversation SortBy WhereIn Array

I got this query:

    .....
            $motor = Motor::query()
                ->where([
                    ['effect_id', '=', $request->effect_id],
                    ['poles', '=', $request->poles],
                    ['voltage_id', '=', $request->voltage_id],
                    ['active', '=', 1],
                ])
                ->whereHas('MotorSize', function (Builder $query) {
                    $query->whereIn('mounting', ['B5', 'B14', 'B34', 'B35']);
                })
                ->firstOrFail();

The query works fine, but not the way i want :p

The problem is this part:

$query->whereIn('mounting', ['B5', 'B14', 'B34', 'B35']);

How can I make it, so it look for "B5" first, then "B14", "B34" and last "B35"? (the order of the array items). There will only be 1 result of each.

As of now, it will get the first model created (motor), as long the property is matching one of the values in the whereIn array.

Activity icon

Replied to How To Use "centralized ID" For My Tables?

@snapey That is probably the best solution for me.

As some of you commented - there must be a better way to handle this. Going to think it over and try to find a better solution/setup :)

Activity icon

Started a new Conversation How To Use "centralized ID" For My Tables?

Hi,

I got some tables with products.

Is it possible to create an "autogenerated ID" ($table->bigIncrements('id')) for each entry into the different tables, from the same "pool of numbers"?

So, if I query all tables and output all results on one page, then all IDs will be different? Not two alike.

Not sure if that is possible.

Activity icon

Replied to How To Do Relationship Query Of A Model To A Model

Ahh... that was it! Works now :D

Thanks for your help!

Activity icon

Replied to How To Do Relationship Query Of A Model To A Model

@tykus

I have tried to run your code, but receive this error:

Argument 1 passed to App\Http\Controllers\ConfiguratorController::App\Http\Controllers\{closure}() must be an instance of App\Http\Controllers\Builder, instance of Illuminate\Database\Eloquent\Builder given, called in /home

I modified my relationship in my Motor model, as suggested:

    public function MotorSize()
    {
        return $this->belongsTo(MotorSize::class, 'motor_size_id');
    }

Used Google and found this related to the error: https://stackoverflow.com/questions/45330626/laravel-argument-1-passed-to-hasoneormanysave-must-be-an-instance-of-model-a

They tell to pass an array objects to the method.

Not sure how to do that and if that will fix it.

Activity icon

Replied to How To Do Relationship Query Of A Model To A Model

Hi @tykus ,

Thanks for the reply.

I already got this relationship in my Motor model:

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

What is the difference between this one and the one you posted?

Activity icon

Started a new Conversation How To Do Relationship Query Of A Model To A Model

Hi,

I got 3 models : Configurator, Motor and MotorSize.

Motor can be added to Configurator using BelongsTo. MotorSize can be added to Motor using BelongsTo.

The relations above works nice (i have added some tables below).

The problem is: I need to get all motors that have a MotorSize property/column named "mounting" with a value of "B14" (not sure if the terminology is correct)

I have tried different things, but nothing works. This is my latest attempt:

$motor = Motor::query()
    ->whereHas('motor_size_id', function (Builder $query) {
        $query->where('mounting', 'like', '%B14');
    })->first();

I receive this error:

Call to undefined method App\Motor::motor_size_id()

Maybe these tables will help to understand what i'm trying to do :)

        Schema::create('configurators', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('motor_id');
            $table->string('gear_id');
            $table->timestamps();
        });

        Schema::create('motors', function (Blueprint $table) {
            $table->increments('id');
            ...... bla bla
            $table->string('motor_size_id');
            ..... bla bla
            $table->timestamps();
        });

        Schema::create('motor_sizes', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name')->unique();
            $table->string('framesize'); // E.g. 80
            $table->string('mounting'); // E.g. B14
            $table->timestamps();
        });

Sep
22
1 month ago
Activity icon

Replied to Getting A Weird Result When Retrieving Data On Show Page

Ye, that was it!

Thanks a lot :D

Activity icon

Started a new Conversation Getting A Weird Result When Retrieving Data On Show Page

Hi,

I got a weird problem. Not sure what is causing it.

I got this in my controller:

    public function show(Configurator $configurator)
    {
        $conf = Configurator::firstOrFail($configurator);
        return view('configurator.show', compact('conf'));
    }

If i do this:

<h1>{{ $conf }}</h1>

I receive this:

{"\"{\"\"id\"\":22,\"\"motor_id\"\":\"\"1\"\",\"\"wormgear_id\"\":\"\"1\"\",\"\"created_at\"\":\"\"2019-09-22 15:55:01\"\",\"\"updated_at\"\":\"\"2019-09-22 15:55:01\"\"}\"":"{\"id\":22,\"motor_id\":\"1\",\"wormgear_id\":\"1\",\"created_at\":\"2019-09-22 15:55:01\",\"updated_at\":\"2019-09-22 15:55:01\"}"}

If I do

{{ $conf->id }}

I get a blank result (no errors or anything).

Any of you know what is causing this problem?

Jul
17
4 months ago
Activity icon

Started a new Conversation Nova, How To Save Product Features In Separate Table?

Hi,

I'm using Nova to add and modify product data.

Currently I have a tables/models for each product type (each type got a lot of features that I need to use), but a user on this forum suggested, that I make one product table, and then added the features in a separate table - I kinda love that idea. Makes other stuff A LOT easier for me.

I'm not sure how to make that work with Nova though. Not sure what "route" to go.

Lets say I have the following tables:

products
id
name
products_features
id
product_d
property
value

The properties always have the same "names", but the values are of cause different. Each product-type have about 10 features that needs to be saved.

Seems like a simple task, but i'm lost for ideas. How would you handle it?

Hope one of you might be able to point me in the right direction :)

, Kenneth

Activity icon

Replied to Pivot Table For 3 Models?

@tray2 Thats not a bad idea at all.

Going to look into that for an upcoming project. Never tried that before though.

Activity icon

Replied to Pivot Table For 3 Models?

@davidpetrov Thanks, will look into that. Each product (motor or gear) can have many prices from many suppliers.

Activity icon

Started a new Conversation Pivot Table For 3 Models?

Hi,

I got 3 models: motors, gears and suppliers.

I would like to attach purchase-prices to my products (motors and gears) from a supplier. Any suggestions how to do that?

Can i create some kind of pivot table like this?

motor_id (nullable)
gear_id (nullable)
supplier_id

Also, each product (motor or gear) can have many prices from many suppliers.

Then use motor_id or gear_id when needed (will only be one of them)?

I'm kinda lost for ideas here :(

Jul
07
4 months ago
Activity icon

Replied to Nova: Add Value To Database Based On Form Inputs

Ohhh.... this is working:

$event->product->save();
Activity icon

Replied to Nova: Add Value To Database Based On Form Inputs

I got most of it working. Can how log the changes to my "description field", but running into trouble when i try to save it to my database.

$event->save() does not work. Not sure what else to use.

model:

namespace App;

use Illuminate\Database\Eloquent\Model;

use App\Events\NewProduct;

class Product extends Model
{
    
    /**
     * The event map for the model.
     *
     * @var array
     */
    protected $dispatchesEvents = [
        'created' => \App\Events\NewProduct::class,
    ];
    
}

event:

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

use App\Product;

class NewProduct
{
    use Dispatchable, InteractsWithSockets, SerializesModels;
    
    public $product;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(Product $product)
    {
        $this->product = $product;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('channel-name');
    }
}

Listener:

namespace App\Listeners;

use App\Events\NewProduct;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class ProductDescription
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  NewProduct  $event
     * @return void
     */
    public function handle(NewProduct $event)
    {
        $event->product->description = 'This is a test description';
        //app('log')->info($event->product);
        $event->save();
    }
}

Most of the stuff I have read, they only explain how to output to log. Not sure how to save it to the model though :/

Jul
06
4 months ago
Activity icon

Replied to Nova: Add Value To Database Based On Form Inputs

Thanks! Will look into that :)

Jul
05
4 months ago
Activity icon

Replied to Nova: Add Value To Database Based On Form Inputs

Hmm... I dont think that will work.

I would like to create a default product description, based on selected feaetures from the form. Then be able to edit the product description after creation. So the description is only prefilled upon first creation, then modified in the form after.

This to make some kind of the "standard product description", which can be edited later.

Not sure if that makes sense.

, Kenneth

Jul
04
4 months ago
Activity icon

Started a new Conversation Nova: Add Value To Database Based On Form Inputs

How can I make it, so a cell in my database get a value based on some form input values, that I have submitted in Nova?

Example:

I got 3 input fields that are saved to my database: input1, input2, input3 I then want to automatically add those values to a "description" column in my table (database), value of the column will be "input1 + input2 + input3". So the column is "prefilled" with content submitted by the create form.

Any help would be welcome :)

Jun
23
4 months ago
Activity icon

Replied to Only List Active Resources In Select Menu?

Found the solution I think.

Added this to Nova->Resource.php

public static function relatableBrands(NovaRequest $request, $query)
    {
        return $query->where('active', 1);
    }
Jun
22
4 months ago
Activity icon

Replied to Only List Active Resources In Select Menu?

But filters only apply to the "index" page of the resource, right? Not the create page. My menu is on the create page.

Activity icon

Replied to Only List Active Resources In Select Menu?

I feel so dump, completely lost :(

Do you know where I can read up on that?

I got two resources: Motor and Brand When creating a new Motor resource, then the menu (Select) should only list the active ones.

Nova -> Motor.php

...
    public function fields(Request $request)
    {
        return [
            
            # Brand
            BelongsTo::make('Select a Brand', 'brand', 'App\Nova\Brand'),
            
        ];
    }
...

Motor model:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Motor extends Model
{
    public function Brand()
    {
        return $this->belongsTo('App\Brand');
    }
}

No controllers or routes - Nova handles all that.

Activity icon

Replied to Only List Active Resources In Select Menu?

Thank you very much for the reply. In that file do I add that? Not sure where to add it :(

Activity icon

Started a new Conversation Only List Active Resources In Select Menu?

Hi,

How can I make it so only active resources are listed in my Select menu within Nova? It got menu working etc, but it list all resources and not just the active ones.

I have searched the Nova documentation, but cant find anything about it :(

Any of you know how to filter those or what to search for (terms)? Kinda blank :(