toby

toby

Member Since 5 Years Ago

Duisburg, Germany

IT-Consultant at ACS

Experience Points 109,030
Experience Level 22

970 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 1494
Lessons
Completed
Best Reply Awards 17
Best Reply
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

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

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

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

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    Laracasts Evangelist

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

  • Chatty Cathy Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

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

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

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

26 Apr
2 months ago

toby left a reply on Laravel Query

Try to use sum() instead of count()

DB::table('table')
    ->select('item', DB::raw('sum(count) as Total'))
    ->groupBy('item')
    ->get();
16 Apr
2 months ago

toby left a reply on SQLSTATE[42000]: Syntax Error Or Access Violation: 1059 Identifier Name ' ' Is Too Long

Take a look at the API docs: foreign(string|array $columns, string $name = null), which means that you can define your own name.

Schema::table('mother_haematological_disorder_type', function ($table){
    $table->uuid('mother_medical_history_id')->unique()->after('id');
    $table->foreign('mother_medical_history_id', 'NAME_GOES_HERE')->references('id')->on('mother_medical_history')->onDelete('cascade');
        });

toby left a reply on Override Login Authentication

You can overwrite the e.g. login() credentials() in your LoginController (check the trait Illuminate\Foundation\Auth\AuthenticatesUsers to get an overview of the methods)

01 Apr
2 months ago

toby left a reply on BelongsToMany With Different DB Connections

I'm trying now... If there are interesting results (instead of work arounds...) I'll post an update.

Meanwhile, I also opened an issue on the https://github.com/laravel/ideas repo

toby left a reply on BelongsToMany With Different DB Connections

Hmm... no, this also doesn't help... I just wanted to create an GitHub issue and found this one $connection of custom pivot model ignored #25140.

So I guess, I need to to some "manual" work around :/

Thanks for your help!

toby left a reply on BelongsToMany With Different DB Connections

Hi and thanks for your reply,

In the meantime I tried exactly this; with no luck :(

I tried the following approaches:

// App/Action.php

public function repairs()
{
    return $this->belongsToMany(Repair::class')->using(ActionRepair::class);
}

with this Pivot class:

// App/ActionRepair.php

use Illuminate\Database\Eloquent\Relations\Pivot;

class ActionRepair extends Pivot
{
    protected $connection = 'mysql'; // tested 'default' as well...

    // and setting it in the constructor also doesn't work
    public function __construct(array $attributes = [])
    {
        $this->setConnection('mysql'); // tested 'default' as well...
        parent::__construct($attributes);
    }
}

The connection attributes seems to be ignored, even if I write gibberish in there like asdf, it doesn't do anything :(

toby started a new conversation BelongsToMany With Different DB Connections

Hi everyone,

I've got two Models:

  • Action is a model on my local database (mysql connection)
  • Repair is a model on a different database (sqlsrv connection; read-only)

Now I need to link those models via belongsToMany; therefore I created a action_repair-table as a pivot table with the columns action_id and repair_id; this pivot table is created on the mysql connection.

But as soon as I try to save new relations, Laravel assumes, that the pivot table lives on the sqlsrv connection (like the Repair model, which is wrong.

How can I set a $connection for this pivot table?!

Thanks in advance!

05 Feb
4 months ago

toby left a reply on How Could I Join 2 Collections From 2 Different Databases?

You can't join, but you can use the regular relationship methods

toby left a reply on How Could I Join 2 Collections From 2 Different Databases?

In your config/database.php file, you can define new connections. Then, in you model, you can use this connection via the protected $connection = 'another-mysql-connection-name'; property.

Example:

// config/database.php

return [

    'default' => env('DB_CONNECTION', 'mysql'),
    'connections' => [
        'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
        ],
        'another-mysql-connection-name' => [
            'driver' => 'mysql',
            'host' => '192.168.0.200',
            'port' => '3306',
            'database' => 'forge2',
            'username' => 'forge2',
            'password' => 'secret2',
            'unix_socket' => '',
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
        ],
    ],

    //...

];

See: https://laravel.com/docs/5.7/eloquent#defining-models under Database Connection

29 Oct
7 months ago

toby started a new conversation Intermediate/pivot Table W/ Three Foreign Keys

Hi everyone,

In a current project, I try to relate models via an intermediate/pivot table with three foreign keys. The models which are connected through this pivot tables are:

UseCase
=======
id
name

Hazard
======
id
name

Action
======
id
name

the pivot table looks like this:

knots
-----
use_case_id
hazard_id
action_id

The scenario is the following: A UseCase can have many Hazards and (the combination of) a UseCase and a Hazard can have many Actions.

But I need to display each relation from every model, therefore I used the following methods:

class UseCase extends Model
{
    public function hazards()
    {
        return $this->belongsToMany(Hazard::class, 'knots')
            ->groupBy(['use_case_id', 'hazard_id'])
            ->orderBy('hazards.name')
            ->withPivot('use_case_id', 'hazard_id', 'action_id');
    }

    public function actions()
    {
        return $this->belongsToMany(Action::class, 'knots')
            ->groupBy(['use_case_id', 'action_id'])
            ->orderBy('actions.name')
            ->withPivot('use_case_id', 'hazard_id', 'action_id');
    }
}
class Hazard extends Model
{
    public function useCases()
    {
        return $this->belongsToMany(UseCase::class, 'knots')
            ->groupBy(['hazard_id', 'use_case_id'])
            ->orderBy('use_case.name')
            ->withPivot('use_case_id', 'hazard_id', 'action_id');
    }

    public function actions()
    {
        return $this->belongsToMany(Action::class, 'knots')
            ->groupBy(['hazard_id', 'action_id'])
            ->orderBy('actions.name')
            ->withPivot('use_case_id', 'hazard_id', 'action_id');
    }
}
class Action extends Model
{
    public function hazards()
    {
        return $this->belongsToMany(Hazard::class, 'knots')
            ->groupBy(['action_id', 'hazard_id'])
            ->orderBy('hazards.name')
            ->withPivot('use_case_id', 'hazard_id', 'action_id');
    }

    public function useCases()
    {
        return $this->belongsToMany(UseCase::class, 'knots')
            ->groupBy(['action_id', 'use_case_id'])
            ->orderBy('use_cases.name')
            ->withPivot('use_case_id', 'hazard_id', 'action_id');
    }
}

I used the grouping to remove any duplicates (because it is possible, that the same Action can be assigned to a UseCase but with a different Hazard...)

But now I want to display every UseCase with its Hazards and the according Actions and I really got stuck here :(

Do you have any idea on how to display this relation correctly (w/o duplicated and/or missing Actions [due to the groupBy]?

Thanks in advance and have a nice day!!!

07 Sep
9 months ago

toby left a reply on Laravel 5.7 - Policy Issue

Thanks!!

12 Jul
11 months ago

toby left a reply on Anyone Facing Barcode Generator Using Milon/barcode Package Got Issue When Displaying?

Maybe there is a CSS/JS problem..? What happens if you use a blank blade file (no CSS, no JS) and just display the barcode?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Barcode test</title>
</head>
<body>
{!! DNS1D::getBarcodeSVG('123', "C39", 1, 25, '#2A3239') !!}
<hr>
<img src="data:image/png;base64,{{ DNS1D::getBarcodePNG("4", "C128B")}}" alt="barcode" />
</body>
</html>

toby left a reply on Anyone Facing Barcode Generator Using Milon/barcode Package Got Issue When Displaying?

I just tested it and inserted {!! DNS1D::getBarcodeSVG('123', "C39", 1, 25, '#2A3239') !!} in a blade file and it showed up correctly the first time. Even printing the page via ctrl+p works.

Which method do you use to generate the barcode (I tested several and they all work fine...)? Does it make a difference if you change the browser?

toby left a reply on Default Cache Time In Laravel?

If you take a look at the core vendor/laravel/framework/src/Illuminate/Cache/RedisStore, it looks like this:


/**
 * Store an item in the cache for a given number of minutes.
 *
 * @param  string  $key
 * @param  mixed   $value
 * @param  float|int  $minutes
 * @return void
 */
public function put($key, $value, $minutes)
{
    $this->connection()->setex(
        $this->prefix.$key, (int) max(1, $minutes * 60), $this->serialize($value)
    );
}

toby left a reply on Anyone Facing Barcode Generator Using Milon/barcode Package Got Issue When Displaying?

No issues here; I'm using this package to generate SVG barcodes which will show up in a PDF document (via barryvdh/laravel-snappy):

{!! DNS1D::getBarcodeSVG($foo->bar, "C39", 1, 25, '#2A3239') !!}

toby left a reply on Handle Time And Memory Limits For Executing A Script

Basically, you just dispatch a new job within your controller which can be queued. Take a look at the docs, there is everything you need to know :) If you have any further questions, don't hesitate to ask.

11 Jul
11 months ago

toby left a reply on Implementing Jquery And Ajax In Laravel

$("start") is not the correct selector:

  • If start is a class name, use $('.start')
  • if start is an id, use $('#start')
  • if you want to select an element, use e.g. $('a')

Basically, you need a correct selector (like in CSS). Click here for more info

toby left a reply on Repository Vs Model?

I personally tend to use repositories only, if I've got some larger "queries" which I will use more than a few times. In most of my projects, models mostly contain only their fillable attributes, their casts, their relationships and maybe some mutators.

Here is an example, where I did use a repository: Say, we have got the following models: User, Employee and Department. A User belongs to an Employee and the Employee belongs to a Department (as mentioned above, the basics are coded inside these models).

Now, I have several places where I need to display a <select> dropdown field where the value is the user.id, the displayed text is the employee.full_name and each is grouped within the department.name (via <optgroup>). The query (based on Eloquent) and the necessary Collection methods are inside a repository :)

I would try to stick to models only as long as they stay clear and are maintainable. If there is too many other logic or if you keep repeating to code the same queries again, I would reach for a repo.

toby left a reply on Handle Time And Memory Limits For Executing A Script

If it is possible, use queues for those long running tasks; this way, this task can run in the background and your application responses immediately

toby left a reply on Package.json Devdependencies

Removing packages can be accomplished via npm remove lodash

toby left a reply on Package.json Devdependencies

Typically, it's not required to delete the node_modules folder. Running npm update updates each package according to the semver syntax in your package.json file.

Updating does not change your package.json file, instead, apackage.lock` will be created (since NPM v5, I think...) which contains the actual installed version of each dependency.

Therefore, it is also recommended to include the lock-file to your git repository, because npm install uses these information to download the same versions.

toby left a reply on Distinct In Eloquent, Laravel.

I read it like this:

partner_group_id | user_id
-----------------+--------
 1               | 1
 1               | 2
 2               | 1
 2               | 2
 2               | 3

which means

  • user with the ID of 1 belongs to the partner groups 1 and 2
  • Same for user #2.
  • User #3 only has the partner group #2.

I see no problems there...

Please post the SQL query which are performed.

toby left a reply on Distinct In Eloquent, Laravel.

User belongsToMany PartnerGroup?

toby left a reply on Distinct In Eloquent, Laravel.

Hm.... typically it should work like you posted it in the first place (groupBy shouldn't even be necessary)...

What I think of is the ->where('id', $id) part... Because Laravel performs a subselect and the ID column should be ambiguous and an error should be shown...

Try to insert the table name there like ->where('partner_groups.id', $id)

Also, do you have Debugbar installed? Can you show the performed query?

10 Jul
11 months ago

toby left a reply on Distinct In Eloquent, Laravel.

Did you try to ->groupBy('users.id')?

toby left a reply on Custom Messages In Reset Password Form Don´t Show

If you take a look at the SendsPasswordResetEmails-trait, you'll see, that a method called validateEmail() is responsible for validating request data. Therefore you need to overwrite this method in you controller like this:

// FILE: App\Http\Controllers\Auth\ForgotPasswordController.php

// ...

class ForgotPasswordController extends Controller
{
    use SendsPasswordResetEmails;

    protected function validateEmail(Request $request)
    {
        $this->validate($request, ['email' => 'required|email'], [
            'email.required' => 'The email field is mandatory.',
            'email.email' => 'Please insert a valid email.',
        ]);
    }

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }
}

toby left a reply on Custom Messages In Reset Password Form Don´t Show

token is not the csrf_token ;) It's the token from the url:

public function showResetForm(Request $request, $token = null)
{
    return view('auth.passwords.reset')->with(
        ['token' => $token, 'email' => $request->email]
    );
}

Just include a hidden input with this value and you're done:

<input type="hidden" name="token" value="{{ $token }}">

toby left a reply on Custom Messages In Reset Password Form Don´t Show

There are both routes:

  • password/email: Here the user enters their email address and the email will be send to them
  • password/reset: Here the user updates their password

toby left a reply on Custom Messages In Reset Password Form Don´t Show

Make sure to post to the Rese[email protected]-controller method via <form method="POST" action="/password/reset" accept-charset="UTF-8">

toby left a reply on Custom Messages In Reset Password Form Don´t Show

As long as your form POSTs to [email protected] it should work

toby left a reply on Custom Messages In Reset Password Form Don´t Show

Actually it should be Route::auth().

what does php artisan routes:list show? Is there the following line?

|        | POST      | password/email                                                                                 | password.email                        | App\Http\Controllers\Auth\[email protected]      | web,guest                                    |

toby left a reply on Custom Messages In Reset Password Form Don´t Show

copy/pasting your controller works fine, though... maybe it's your routes/web.php-file?

toby left a reply on Custom Messages In Reset Password Form Don´t Show

Did you use the ResetsPasswords trait before defining those methods? The following code should work:

// FILE: Http\Controllers\Auth\ResetPasswordController.php


class ResetPasswordController extends Controller
{
    use ResetsPasswords;

    /**
     * Get the password reset validation error messages.
     *
     * @return array
     */
    protected function validationErrorMessages()
    {
        return [
            'email.required' => 'The email field is mandatory.',
            'email.email' => 'Please insert a valid email.',
        ];
    }

    // ...
}

toby left a reply on [L5.*] Pagination: Change URL Query Name "page" Globally

Thanks for the suggestion, but I'm looking for something like a global setting; this is why I created the pagination()-helper (see first post) in the first place.

Something like a single place where I can define the query name. (Image to rename from seite to something different... Each controller needs to be updated...)

toby started a new conversation [L5.*] Pagination: Change Query Name "page" Globally

Hi,

almost a year ago, I asked, if it's possible to globally change the name for the page query attribute if you enable pagination: Instead of having a url like tickets?page=23 I wanted to translate this to tickets?seite=23. Therefore, I created a lil' helper function to do so.

I also use the following snippet inside my routes/web.php file to rename the routes from tickets/new to tickets/neu and tickets/23/edit to tickets/23/bearbeiten:

// routes/web.php

Route::resourceVerbs([
    'create' => 'neu',
    'edit' => 'bearbeiten',
]);

Route::resource('tickets', 'TicketController');

I wonder if there is an alternative solution to the ?page=-to-?seite=-problem?

Thanks in advance

toby left a reply on Undefined Variable

Your controller needs to pass the data to the view like:

    public function index()
        $subjectMarks = [1,2,3];
        return view('exam.submitPaper', compact('subjectMarks'));
    }

And in your blade file, you can access it like a variable, not like a constant. If you use

// use "$subjectMarks" not just "subjectMarks"
@foreach($subjectMarks as $subjectMark)
    {{ $subjectMark }}
@foreach

it should work

toby left a reply on Route Model Binding In Laravel 5.6

You can load even nested relations inside your controller:

public function show(Post $post)
{
    $post->load('comments.image');

    return $post;
}

toby left a reply on Route Model Binding In Laravel 5.6

Try to use return $post->load('comments')

09 Jul
11 months ago

toby left a reply on Can't Connect To MySQL Server On '127.0.0.1' (4)

As @Tray2 mentioned, homestead is a VM which means it has it's own IP address.

127.0.0.1 is always the localhost aka the current machine. If you want to connect to homestead's MySQL database, you need to connect to homestead's IP; typically it is 192.168.10.10.

You need the same IP if you update your /etc/hosts file (e.g. 192.168.10.10 laravel.test).

21 Jun
1 year ago

toby left a reply on Thoughts? Opinions? Roadmap To Proper Use?

It's definitely worth it! @JeffreyWay covers nearly everything from bottom to top!

Sure, there are other learning resources which cover PHP/Laravel, but IMHO Laracasts covers really everything in a great way: PHP basics, TDD, Design Patterns, Laravel (beginners to advanced) and it keeps getting better and better! I clearly recommend Laracasts! Insanely great work!!!

You can always subscribe for a month ($ 15) to get a brief overview.

04 May
1 year ago

toby left a reply on How To Create A Link In Javascript With Laravel

You could also create a mutator inside your model like this:

// in your eloquent model

public function getLinkAttribute() {
    return route('posts.show', $this);
}

Then you can create the link like: {{ $post->link }}(In your blade file).

Maybe you'll also need this custom accessor to your model's $appends-attribute: protected $appends = ['link']; if you want to use this data from a JSON response or something like this.

03 May
1 year ago

toby left a reply on Updating Homestead (not Sure Where To Run Git Pull... From)

It's the place where your Homestead.yaml is located; typically in located inside your home directory: ~/Homestead.

If you can't find it, type which homestead in your terminal: There the code will be displayed like

homestead () {
    (
        cd ~/Homestead && vagrant $*
    )
}

et voilà, there is your path :)

17 Apr
1 year ago

toby left a reply on ORM

Table names are always assumed to be the pluralized version of the Model name. You can change this via protected $table = 'poll'; in your model. See (https://laravel.com/docs/5.6/eloquent#eloquent-model-conventions)[The documentation for further information]

13 Apr
1 year ago

toby left a reply on Phpunit Not Always Right

Nice question for any future co-workers / employees xD

28 Mar
1 year ago

toby left a reply on German Locale On Windows Server 2008 Causes Problems W/ Umlauts

Perfect, thanks! Carbon::setUtf8(true);` did the trick!

PS: Beste Grüße aus Duisburg ;)

toby started a new conversation German Locale On Windows Server 2008 Causes Problems W/ Umlauts

Hi!

I have a strange problem with locales (esp. umlauts) on a Windows Server; first, this is my setup:

  • Windows Server 2008 R2 Standard (OS is in German)
  • IIS 7.5
  • PHP Version 7.1.14 (x64)

So far, everything works just fine (mostly Laravel applications).

But as soon as I want to display a formatLocalized() w/ Carbon, nothing shows if the desired output contains an umlaut, e.g.:

// Given there is a $post with created_at = '2018-03-15 08:17:00';

$post->created_at->formatLocalized('%A, %e. %B %Y');
// expected output: Donnerstag, 15. März 2018

template code (show.blade.php)

<!-- USING {{  }}: -->

<p>{{ $post->created_at->formatLocalized('%A, %e. %B %Y') }}</p>
<!-- renders: -->
<p></p><!-- yup, null, nothing... -->
<!-- USING {!!  !!}: -->

<p>{!! $post->created_at->formatLocalized('%A, %e. %B %Y') !!}</p>
<!-- renders: -->
<p>Donnerstag, 15. M�rz 2018</p>
<!-- USING {{ utf8_encode() }} -->

<p>{{ utf8_encode($post->created_at->formatLocalized('%A, %e. %B %Y')) }}</p>
<!-- renders: -->
<p>Donnerstag, 15. März 2018</p>

With Homestead, I am able to to display everything as expected using the following snippet in my AppServiceProvider (I had to install the german locales first):

public function boot()
{
    setlocale(LC_ALL, 'de_DE.utf8');
}

Unfortunately, this does not work on a Windows server environment :(

I tried several values for the setlocale function, such as deu, german, de_DE, [email protected], but nothing worked...

Do you have any idea how I can display this properly w/o always using a utf8_encode()?!

Thanks in advance!