TobiasS

TobiasS

Member Since 5 Months Ago

Experience Points
21,360
Total
Experience

3,640 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
200
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 5
21,360 XP
Aug
31
2 weeks ago
Activity icon

Started a new Conversation Sum Column In Has Many Through Relation

Hi!

I would like to sum a column in a table where the ralation is has many through.

What I try to accomplish

$total_service = Auth::user()->events()->where('completed', '1')->with('periods')->sum('periods.months_service');

But i get an error SQLSTATE[42S22]: Column not found: 1054 Unknown column 'periods.months_service' in 'field list'

A workaround would be

 $total_services = Auth::user()->events()->where('completed', '1')->with('periods')->get('id', 'months_service')->pluck('periods')->collapse()->pluck('months_service')->toArray();

And sum the array, but it would be elegant to be able to accomplish it in eloquent.

(I use accessor)

 public function getMonthsServiceAttribute($value)
    {
        if ($value == null) {
            return;
        }
        return number_format($value, 2, ',', '');
    }

so as soon as I call ->get(); the numbers will be formated from eg 2.5 to 2,5 and there is a problem accomplish math in php.

Is there a way to use eloquent ->sum('column_name in has many through'); to get the sum of the column?

Thx in advance

Aug
24
3 weeks ago
Activity icon

Replied to Decimal Comma Instead Of Dot (localization)

Thx for your answers! They helped me in the right direction.

I ended up using Eloquent: Mutators Accessor.

https://stackoverflow.com/questions/59138359/laravel-crud-decimal-change-dot-to-comma-in-the-form

Aug
23
3 weeks ago
Activity icon

Replied to Decimal Comma Instead Of Dot (localization)

I’m storing months and they do not need to be full months. Eg 11,5 or 3,25

I use decimal 3 , 2 for table layout.

In the views I then need to format the data with eg str replace

But how should I handle the input? Laravel validation, store to MySQL. I need to manipulate the input data in some way replacing ‘,’ with ‘.’ Before creating the database record. What would be “best practice “ to do this manipulation on all fields before storing to database?

Thx in advance

Activity icon

Started a new Conversation Decimal Comma Instead Of Dot (localization)

Hi!

Is there a laravel way of localization of decimal numbers. At the moment everything works perfect for me using '.' (eg 4.5)

From input field -> validation -> SQL database create record

But when using ',' (what I want to use) (eg 4,5) I get SQLSTATE[HY000]: General error: 1366 Incorrect decimal value: '4,00' for column 'months_service' at row 1 (SQL: insert into

Do I need to manually make a sting replace on all the fields where I use ',' to '.' Or is there an easier more elegant way?

Thanks in advance!

Aug
05
1 month ago
Activity icon

Replied to Make Local Development Case Sensitive?

Thanks for your replies!

Activity icon

Started a new Conversation Mail Server Advice

Hi!

I have deployed my app to a DigitalOcean’s droplet. So far so good, possible to log in and so on.

But, how should I handle email?

It’s a small app so I just need a email to be able to send mail when a user register, forget password.

One [email protected] (possible for users to send mail/feedback) And one for newsletters

In total 3 mail addresses.

Any advice on setup? I run Ubuntu 20.04 on DigitalOcean

Postfix? Mailgun? Other Mailprovider?

Thx in advance!

Activity icon

Started a new Conversation Make Local Development Case Sensitive?

Hi!

I just managed to deploy a project to a ubuntu webserver.

There is a problem with case sensitive. Linux is case sensitive mac case insensitive.

How do I make my local development case sensitive or can I make my production case insensitive?

I found a guide regarding making Mac case sensitve https://m.dotdev.co/dealing-with-case-sensitivity-related-errors-in-web-development-509a442e6d96

But I also saw some issues with Valet and case sensitive.

I would like my development environment and production to be as close as possible.

Any suggestion how to accomplish this?

Thanks in advance!

Jul
28
1 month ago
Activity icon

Replied to Seeding For PEST Test

@sergiu17 Yes I have the Seeders classes inside database/seeds/ folder.

@jgravois I have created the seeders

It works perfect using the "normal" laravel/phpUnit test

<?php
namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;
use DepartmentSeeder;

/** @test */
public function test_seed()
      {
          $this->seed(DepartmentSeeder::class);

But when I try with PEST Target class [Illuminate\Database\Seeder\DepartmentSeeder] does not exist.

I have tried with both the normal laravel seeder

<?php

use Illuminate\Database\Seeder;

class DepartmentSeeder extends Seeder

and what I use for some seeders (seeding Csv) https://github.com/jeroenzwart/laravel-csv-seeder

But as soon as I try to implement it in PEST it fails

Activity icon

Replied to Seeding For PEST Test

I get the same error, unfortunately the composer dump-autoload does not solv it


use Illuminate\Database\Seeder\DepartmentSeeder;

it('creates a new user', function () {
    $this->seed(DepartmentSeeder::class);

Error

• Tests\Feature\ExampleTest > it creates a new user
   Illuminate\Contracts\Container\BindingResolutionException 

  Target class [Illuminate\Database\Seeder\DepartmentSeeder] does not exist.

  at vendor/laravel/framework/src/Illuminate/Container/Container.php:811

Any idea what's wrong?

Jul
20
1 month ago
Activity icon

Replied to Where On A Nested With Eagerload

Thx, but I still get returned periods with event null

"laravel_through_key":1,"event":null}

Activity icon

Started a new Conversation Where On A Nested With Eagerload

Hi!

I would like to return the users and just the periods that has a specific event.

Query

 $users = User::where('department_id', 5)->with(['periods.event' => function($query) {
            $query->where('type', 'Service');
        }])->get();

But I get all the periods, how can I make a constraint that only the periods.event where type is "service" get returned?

Relationships

User Model
    public function periods()
    {
        return $this->hasManyThrough(Period::class, Event::class);
     
    }

Event Model
public function periods()
    {
        return $this->hasMany(Period::class)->orderBy('start', 'desc');
    }

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

Thx in advance!

Jul
06
2 months ago
Activity icon

Started a new Conversation N+1 Problem, HasManyThrough When Reaching For "parent"

Hi!

I get a n+1 problem in my blade template.

Controller, INCLUDING WITH

 
$users = User::where('department_id', $user->department_id)->with(['periods', 'events'])->get();

Blade template

@foreach ($users as $user)
    @foreach ($user->periods as $period)
    {
      
        id: {{ $period->id }},
        name: {{ $period->event->title }},
        sectionID: {{ $loop->parent->iteration }},
        start: moment('{{ $period->start }}'),
       
    },
    @endforeach
 @endforeach

The line name: {{ $period->event->title }}, triggers a new database Query. Isn't it already included in the with(['periods', 'events']) in the controller?

How can I get rid of this n+1 problem???

Relationships

User Model

 public function periods()
    {
        return $this->hasManyThrough(Period::class, Event::class);
       
    }

 public function events()
    {
        return $this->hasMany(Event::class);
    }

Event Model
 public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function periods()
    {
        return $this->hasMany(Period::class)->orderBy('start', 'desc');
    }

Period Model
  public function event()
    {
        return $this->belongsTo(Event::class);
    }
Activity icon

Replied to Multiple Routes In Web.php Or Query String?

Thx! Refactored to small controllers, sharing code using traits

Jul
01
2 months ago
Activity icon

Started a new Conversation Multiple Routes In Web.php Or Query String?

Hi!

I have 15-20 pdf:s that the user can choose to print.

What would be the best way to show the pdf the user chose?

At the moment I use a query string with the name of the function inside the controller and route to [email protected]

Is this the best way? (I have the drawback that the controller is really long and with lots of functions)

Or would it be better to have multiple Controllers whit just one function? And then the drawback of having multiple lines in web.php routing to all the controllers?

Thanks in advance!

Jun
29
2 months ago
Activity icon

Replied to Specify Columns To Return When Eager Load

Thx! Just needed to change to ->get([‘id’,’email’]).

Then I can specify the columns in users table.

In the events query I added ->select([‘user_id’,’type’])

But then the models that are always included when “calling” events just return empty arrays.

How can I still include these models (grand-children) to users?

Jun
27
2 months ago
Activity icon

Started a new Conversation Specify Columns To Return When Eager Load

Hi!

How do I specify what columns I want to return when using eager load? I just want to return 'email' from user and then all columns from the eager loaded model

 $users = User::where('department_id', 1)->with(['events' => function($query) use ($type){
                $query->where(['type' => $type]);
            }])->get('email', 'events.*');

I have tried to specify columns using ->Select('email', 'events.*) or using ->get() as above.

How can I specify the columns I want to return?

Thanks in advance!

Jun
03
3 months ago
Activity icon

Replied to Sanctum Roles & Permissions

Thx! I will check it out!

May
30
3 months ago
Activity icon

Replied to Sanctum Roles & Permissions

Hi!

I have the same question. Did you find any solution/ best practice?

May
29
3 months ago
Activity icon

Replied to Using Vuejs, Vuetify And Laravel Authentication Best Practise/advise

I have the same questions as you. Did you find any good recommendations/ answers?

Thanks in advance!

May
15
4 months ago
Activity icon

Replied to Use Axios / Ajax To Send File And Other Data Without FormData?

Is there an easier way to do this? How is it possible to validate the $test input?

Activity icon

Started a new Conversation Vue File Upload + Json And Laravel Validation

Hi!

I have a vue component with inputs (text, textarea, select-multiple and file upload). I use Axios to POST to an endpoint in Laravel.

First, is there a better/simpler way to do this than what I am trying?!!! So to say is there a simpler way to handle file upload in vue. Before introducing the file upload part of the component it was easy to handle the axios POST and I did not need to use formData.append

Otherwise, this is what I try to do.

VUE.

data: function() {
        return {
            form: new Form({
                title: "",
                description: "",
                periods: [
                    {
                        start: "",
                        end: "",
                        service_grade: "",
                        months_fulltime: ""
                    }
                ],
                goalsfield: [],
                subgoalsfield: [],
                servicediploma: ''
            }),
        };
    },

 methods: {
    
       handleFileUpload(){
             this.form.servicediploma = this.$refs.servicediploma.files[0];
      },
        submitFile(){
     
            let formData = new FormData();
            formData.append('servicediploma', this.form.servicediploma);
            formData.append('title', this.form.title);
            formData.append('description', this.form.description);
            formData.append('periods', JSON.stringify(this.form.periods));
            formData.append('goalsfield', JSON.stringify(this.form.goalsfield));
            formData.append('subgoalsfield', JSON.stringify(this.form.subgoalsfield));
         
       
            axios.post( '/services',
                formData,
                {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
              }
            ).then(function(){
          console.log('SUCCESS!!');
        })
        .catch(function(){
          console.log('FAILURE!!');
        });
      },
    }

In this way I manage to get all the "data" to the controller. dd($request->all()); in controller


array:6 [
  "title" => "Titleinput"
  "description" => "Description input"
  "periods" => "undefined"
  "goalsfield" => "[{"id":1,"goal":"a1","type":"goal","soc_guideline":"2015","created_at":"2020-05-01T13:01:45.000000Z","updated_at":"2020-05-01T13:01:45.000000Z"},{"id":2,"goal":"a2","type":"goal","soc_guideline":"2015","created_at":"2020-05-01T13:01:45.000000Z","updated_at":"2020-05-01T13:01:45.000000Z"}]"
  "subgoalsfield" => "[{"id":39,"goal":"c3","type":"subgoal","soc_guideline":"2015","created_at":"2020-05-01T13:01:45.000000Z","updated_at":"2020-05-01T13:01:45.000000Z"},{"id":29,"goal":"a4","type":"subgoal","soc_guideline":"2015","created_at":"2020-05-01T13:01:45.000000Z","updated_at":"2020-05-01T13:01:45.000000Z"}]"
  "servicediploma" => Illuminate\Http\UploadedFile {#473
    -test: false
    -originalName: "test.png"
    -mimeType: "image/png"
    -error: 0
    #hashName: null
    path: "/private/var/tmp"
    filename: "phpWVihP5"
    basename: "phpWVihP5"
    pathname: "/private/var/tmp/phpWVihP5"
    extension: ""
    realPath: "/private/var/tmp/phpWVihP5"
    aTime: 2020-05-15 13:39:50
    mTime: 2020-05-15 13:39:50
    cTime: 2020-05-15 13:39:50
    inode: 8612913150
    size: 520054
    perms: 0100600
    owner: 501
    group: 0
    type: "file"
    writable: true
    readable: true
    executable: false
    file: true
    dir: false
    link: false
  }
]

However, I get problem with validation for the objects/arrays I used JSON.stringify in vue. How can I use json_decode before using validation?

May
14
4 months ago
Activity icon

Started a new Conversation Sync, Reformat Object To Array

Hi!

I have implemented vue-multiselect (https://vue-multiselect.js.org/) for dropdown in a vue component instead og using bootsrap-select.

This changed the structure of the request in the laravel controller. So instead of getting

$goals = request('goalsfield');
dd($goals);
array:2 [▼
  0 => "9"
  1 => "11"
]

that I could use


$course->goals()->sync($goals);

I now get

array:2 [
  0 => array:2 [
    "goal" => "a1"
    "id" => "1"
  ]
  1 => array:2 [
    "goal" => "a2"
    "id" => "2"
  ]
]

Now I get an error

Column not found: 1054 Unknown column 'goal' in 'field list' (SQL: insert into `goal_service` (`goal`, `goal_id`, `id`, `service_id`) 

Is there any possible solution to use this array of objects together with sync? Or is there a way to reformat this new array of objects to a "simple" array that I could use with sync?

Best regards, Tobias

May
05
4 months ago
Activity icon

Started a new Conversation Design Strategies, Front End Dynamic Add Form Fields

Hi,

I would like to get som advice on design strategies for a form, where I need to be able to add more rows with input fields. Best practice? Easiest way? Standard blade, vue component, jquery, vuetify?

The first part (service) of the form contains "title" and "description".

The second part (periods), a row with inputs, "start", "end", "service_grade". In the second part it should be possible to add more rows to add more periods.

  • Would it be best with a "add button" that submits a post request and returns the view and blade that generates new row of inputs?
  • Jquery script that adds new row with inputs?
  • Build Vue-component or directly include Vue in the blade.php (if thats possible)?

The "backend" of Laravel is already working with correct relationships, validation, and store methods.

But what would be the best way to handle the dynamic part of the frontend?

May
04
4 months ago
Activity icon

Started a new Conversation CreateMany() Form Field Text Array, Instead Of For Loop

Hi!

Is there any way to use createMany() when handling multiple textfields (array)

View:

 <input name="service_grade[]" type="text"> 
 <input name="start[]" type="text"> 
 <input name="end[]" type="text"> 

Controller:

$inputs = $request->all();
$service->periods()->createMany($inputs);

Generates error:

Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::create() must be of the type array, string given, called in 

dd($inputs) gives

array:6 [▼
  "_token" => "z7RZmUW1XNovo83asdkolkncojp989as89"
  "title" => "a"
  "description" => "a"
  "start" => array:2 [▼
    0 => "2020-03-01"
    1 => "2020-03-01"
  ]
  "end" => array:2 [▼
    0 => "2020-03-01"
    1 => "2020-03-01"
  ]
  "service_grade" => array:2 [▼
    0 => "99"
    1 => "99"
  ]
]

I can save the array with

 for($i = 0; $i < count($inputs['start']); $i++){
        $service->periods()->create(['start' => $inputs['start'][$i], 'end' => $inputs['end'][$i], 'service_grade' => $inputs['service_grade'][$i] ] 
            );
        }

But it would read so much better with createMany() Is there a simple way to handle fields arrays (eg start[], end[]) and insert them in the database. This must be a common situation, but I do not find an elegant solution.

Best regards,