JohnBraun

JohnBraun

PhD candidate (Organic Chemistry) at VU University Amsterdam

Member Since 2 Years Ago

Netherlands

Experience Points
133,670
Total
Experience

1,330 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
917
Lessons
Completed
Best Reply Awards
66
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 27
133,670 XP
Dec
30
3 weeks ago
Activity icon

Replied to Socialite With Twitter And Instagram?

Ah, right. Thanks for the update.

Activity icon

Replied to Socialite With Twitter And Instagram?

Instagram states that it allows (https://developers.facebook.com/docs/instagram-basic-display-api/):

  • Getting an Instagram User Access Token and permissions from an Instagram user
  • Getting an Instagram user’s profile
  • Getting an Instagram user’s images, videos, and albums

However, it might be that they changed their API and you'll need to update the Instagram driver for Socialite.

Dec
29
3 weeks ago
Activity icon

Awarded Best Reply on Socialite With Twitter And Instagram?

Twitter

Twitter requires you to add a link to your app's privacy policy and terms of service (in the App/Details section at https://developer.twitter.com/en/apps/).

Then, you switch to the Permissions tab and choose edit. From here, you should now be able to check the field "Request email address from users".

After that change, it should all work fine.

Instagram

I don't see any problems if you want to use Instagram. You can register to use their API here (https://www.instagram.com/developer/register/) and there is a driver for Socialite over here: https://socialiteproviders.netlify.com/providers/instagram.html.
Activity icon

Replied to Socialite With Twitter And Instagram?

Twitter

Twitter requires you to add a link to your app's privacy policy and terms of service (in the App/Details section at https://developer.twitter.com/en/apps/).

Then, you switch to the Permissions tab and choose edit. From here, you should now be able to check the field "Request email address from users".

After that change, it should all work fine.

Instagram

I don't see any problems if you want to use Instagram. You can register to use their API here (https://www.instagram.com/developer/register/) and there is a driver for Socialite over here: https://socialiteproviders.netlify.com/providers/instagram.html.
Activity icon

Replied to Too Few Arguments Error In Service Controller

How does the VideoPlayer class look like? Does it accept more than 1 argument in the constructor?

Dec
24
4 weeks ago
Activity icon

Replied to Json_encode

I mean in your Product(?) model

Activity icon

Replied to Json_encode

Did you override the toArray() method on the model? Do you have a custom getter (getNameAttribute()) ?

Activity icon

Replied to Json_encode

That's weird. I don't see what we're missing here now...

Activity icon

Replied to Json_encode

In that case, you could use $data['product']->toJson() instead of encoding the object yourself. I think it goes wrong when you try to json_encode the paginator object, which first needs to transform itself to an array.

Activity icon

Replied to Json_encode

Allright, so far so good. What if you dump the return value in the toJson() method?

dd(json_encode($this->jsonSerialize(), $options));
Activity icon

Replied to Json_encode

How I would debug this, is by checking what the value of $this->items->toArray() is in the toArray() method of the paginator class (by using the dd() function before the return statement. What does this give you?

Activity icon

Replied to Json_encode

The LengthAwarePaginator class implements the Jsonable interface, as you can see here.

This means that it has a method toJson as you can see below. This in turn makes use of the toArray() method which returns the result as you posted after the json_encode() transformation.

class  LengthAwarePaginator
{
    // other methods...

    /**
     * Get the instance as an array.
     *
     * @return array
     */
    public function toArray()
    {
        return [
            'current_page' => $this->currentPage(),
            'data' => $this->items->toArray(),
            'first_page_url' => $this->url(1),
            'from' => $this->firstItem(),
            'last_page' => $this->lastPage(),
            'last_page_url' => $this->url($this->lastPage()),
            'next_page_url' => $this->nextPageUrl(),
            'path' => $this->path(),
            'per_page' => $this->perPage(),
            'prev_page_url' => $this->previousPageUrl(),
            'to' => $this->lastItem(),
            'total' => $this->total(),
        ];
    }

    /**
     * Convert the object into something JSON serializable.
     *
     * @return array
     */
    public function jsonSerialize()
    {
        return $this->toArray();
    }

    /**
     * Convert the object to its JSON representation.
     *
     * @param  int  $options
     * @return string
     */
    public function toJson($options = 0)
    {
        return json_encode($this->jsonSerialize(), $options);
    }
}
Dec
22
1 month ago
Activity icon

Replied to How To Change Date Format In Dd/mm/yyyy For Database

To solve the error you mention in the code block, you should first create a Carbon object from the 'estimate_shipping' request parameter. You can even define how the 'estimate_shipping' parameter is formatted when it comes in, using the createFromFromat() method.

Carbon::parse(request('estimate_shipping'))->format('d/m/Y');
// or
Carbon::createFromFormat('m-d-Y', request('estimate_shipping'))->format('d/m/Y');
Dec
19
1 month ago
Activity icon

Awarded Best Reply on Laravel 6 Custom Package Development: How To Auto Publish The Package Config File?

@emilmoe I don't think it is diserable to have packages automatically publish their config files either.

@amitshahc You can't automatically publish them, but you can make it easier for users of your package by providing an Installation command which does the trick for you. Then your users may run php artisan your-package:install and it will publish the config files / migrations / etc.

In the handle() method of the command you can use:

/**
 * Execute the console command.
 *
 * @return void
 */
public function handle()
{
  $this->callSilent('vendor:publish', ['--tag' => 'advertisement-config']);
  $this->info('[Your-package-name] was installed successfully.');
}
Activity icon

Awarded Best Reply on Auto Serial Number

Laravel offers a $loop variable which holds information about the foreach loop you're using. It looks like you want to get the current iteration.

@foreach($item as $item)
<tr>
  <td> {{ $loop->iteration }}</td>
  <td> {{ $item->id }}</td>
  <td> {{ $item-> td_item_desc }}</td>
  <td> {{ $item-> td_qty }}</td>
  <td>{{number_format($item->td_unit_price,3)}}</td>
  <td> {{ number_format($item->td_unit_price * $item->td_qty,3) }}</td>
</tr>
@endforeach  

See the documentation to see what else you can do with $loop.

Activity icon

Awarded Best Reply on Disable Auto Exception Handling In A Situation

This is the case because you let Laravel automatically resolve/instantiate the Advertise class via route model binding (due to the Advertise typehint in the function's parameters).

To circumvent the 404, you should resolve the object yourself:

public function show(int $advertiseId)
{
  $advertise = Advertise::find($advertiseId);

  return response($advertise, Response::HTTP_OK);
}
Activity icon

Replied to Route Parameter Validation

The simple and straight forward approach:

public function Afunc($param)
{
  $validParameters = ["A", "B"];

  if (! in_array($param, $validParameters)) {
    // throw an exception / redirect back with a message
  }
  
  // the parameter is in the defined array, so continue...
}

A cleaner approach would be to create a Custom Validation Rule.

Update: I see @tisuchi posted a solution regarding the use of regex to validate the parameter. This could also be a really good solution, but it depends on your situation. If you always expect a certain format of the parameter (for example in the case of a phone number / email address, etc.), go with @tisuchi's solution. If the parameter doesn't have a strict format but needs to be in a predefined set, go with the solution I posted above.

Activity icon

Replied to Get All Data

Sure, don't forget to send them to the view:

public function index()
{
  $emps = Emps::all();
  $users = User::all();
  $salaries = Salary::all();
  $corps = Corp::all();

  return view('admin.dashboard', compact('emps', 'users', 'salaries', 'corps'));
}
Activity icon

Replied to Disable Auto Exception Handling In A Situation

To return a json response, use response()->json($data, $http_status) where $data is the data you want to return and $http_status is a status code.

However, maybe this article will help you: https://medium.com/@DarkGhostHunter/laravel-convert-to-json-all-responses-automatically-c4a72b2fd3ac

Activity icon

Replied to Auto Serial Number

Laravel offers a $loop variable which holds information about the foreach loop you're using. It looks like you want to get the current iteration.

@foreach($item as $item)
<tr>
  <td> {{ $loop->iteration }}</td>
  <td> {{ $item->id }}</td>
  <td> {{ $item-> td_item_desc }}</td>
  <td> {{ $item-> td_qty }}</td>
  <td>{{number_format($item->td_unit_price,3)}}</td>
  <td> {{ number_format($item->td_unit_price * $item->td_qty,3) }}</td>
</tr>
@endforeach  

See the documentation to see what else you can do with $loop.

Activity icon

Replied to Disable Auto Exception Handling In A Situation

I don't completely understand what you're asking here. Could you clarify?

Did you read the documentation regarding json responses? https://laravel.com/docs/6.x/responses#json-responses

Activity icon

Replied to Laravel 6 Custom Package Development: How To Auto Publish The Package Config File?

@emilmoe I don't think it is diserable to have packages automatically publish their config files either.

@amitshahc You can't automatically publish them, but you can make it easier for users of your package by providing an Installation command which does the trick for you. Then your users may run php artisan your-package:install and it will publish the config files / migrations / etc.

In the handle() method of the command you can use:

/**
 * Execute the console command.
 *
 * @return void
 */
public function handle()
{
  $this->callSilent('vendor:publish', ['--tag' => 'advertisement-config']);
  $this->info('[Your-package-name] was installed successfully.');
}
Activity icon

Replied to Disable Auto Exception Handling In A Situation

This is the case because you let Laravel automatically resolve/instantiate the Advertise class via route model binding (due to the Advertise typehint in the function's parameters).

To circumvent the 404, you should resolve the object yourself:

public function show(int $advertiseId)
{
  $advertise = Advertise::find($advertiseId);

  return response($advertise, Response::HTTP_OK);
}
Dec
18
1 month ago
Activity icon

Replied to What Is Queue Connection Name And What Is The Use Of That

Yes, you can use onConnection() to specify which driver should handle the queued job, see https://laravel.com/docs/6.x/queues#customizing-the-queue-and-connection

Activity icon

Awarded Best Reply on What Is Queue Connection Name And What Is The Use Of That

My explanation wasn't quite right, so I updated it. The high and low are queue names indeed which you define using the onQueue() method. You can specify the order in which the queues should be processed by providing a list of queues to the --queue flag of the worker command (in order of high importance first, lowest importance last).

From the documentation:

Sometimes you may wish to prioritize how your queues are processed. For example, in your config/queue.php you may set the default queue for your redis connection to low. However, occasionally you may wish to push a job to a high priority queue like so:

dispatch((new Job)->onQueue('high'));

To start a worker that verifies that all of the high queue jobs are processed before continuing to any jobs on the low queue, pass a comma-delimited list of queue names to the work command:

artisan queue:work --queue=high,low
Activity icon

Replied to What Is Queue Connection Name And What Is The Use Of That

My explanation wasn't quite right, so I updated it. The high and low are queue names indeed which you define using the onQueue() method. You can specify the order in which the queues should be processed by providing a list of queues to the --queue flag of the worker command (in order of high importance first, lowest importance last).

From the documentation:

Sometimes you may wish to prioritize how your queues are processed. For example, in your config/queue.php you may set the default queue for your redis connection to low. However, occasionally you may wish to push a job to a high priority queue like so:

dispatch((new Job)->onQueue('high'));

To start a worker that verifies that all of the high queue jobs are processed before continuing to any jobs on the low queue, pass a comma-delimited list of queue names to the work command:

artisan queue:work --queue=high,low
Activity icon

Replied to Filter GET Requests From Telescope

In Telescope's Service Provider you can enable what should be logged. As you can see, by default every incoming entry is logged when the environment is local. However, you could change that to return $entry->isReportableException() ||$entry->isFailedJob(); instead of return true; for example.

/**
 * Register any application services.
 *
 * @return void
 */
public function register()
{
    $this->hideSensitiveRequestDetails();

    Telescope::filter(function (IncomingEntry $entry) {
        if ($this->app->isLocal()) { // update this statement or remove it entirely
            return true;
        }

        return $entry->isReportableException() ||
            $entry->isFailedJob() ||
            $entry->isScheduledTask() ||
            $entry->hasMonitoredTag();
    });
}
Activity icon

Replied to Difference Between Queue:listen & Queue:work

The difference is that queue:listen will continue to work after altering your code (you don't have to manually restart the worker), while queue:work needs to be restarted before reflecting the changes you made. However, the queue:work command is more efficient than the queue:listen version.

Also, see https://laravel.com/docs/5.8/queues

Activity icon

Replied to What Is Queue Connection Name And What Is The Use Of That

Queue priorities

It only matters when you have a lot of different tasks and a large volume of tasks that can be queued. In those cases, it might be that you want to prioritize a core business task over - let's say - sending a welcome e-mail.

Setting priorities make it easy to allow processing of queued high priority tasks over low priority tasks. For example by running --queue=high,low you will give more priority to queued jobs coming in defined as 'high priority'. Additionally, you might put more workers on the high priority queue.

Dec
17
1 month ago
Activity icon

Awarded Best Reply on Primary Route

Why don't you move the logic to that controller, which checks if the user is authenticated and based upon that, it returns the corresponding view (with additional data).

// Dashboard Controller

public function index()
{
  if (! auth()->check()) {
    return view('login');
  }

  // the rest of the controller logic
  return view('homepage');
}
Activity icon

Replied to Primary Route

Why don't you move the logic to that controller, which checks if the user is authenticated and based upon that, it returns the corresponding view (with additional data).

// Dashboard Controller

public function index()
{
  if (! auth()->check()) {
    return view('login');
  }

  // the rest of the controller logic
  return view('homepage');
}
Activity icon

Replied to Primary Route

Would this do it for you?

Route::get('/', function () {
  return auth()->check() ? view('homepage') : view('login');
});

You can of course also move this logic to a dedicated controller.

Dec
16
1 month ago
Activity icon

Replied to Primary Route

Then just use the Auth middleware, which will redirect to the login page when a user visits the route without being authenticated.

What's the problem in that?

Activity icon

Replied to Primary Route

If you don't want to redirect the user, you can use the @auth blade directive to determine what is shown to each type of visitor.

@guest
  @include('login_form') 
@endguest

@auth
  Content that will be shown to authenticated users. 
@endauth

Alternatively, you could create a a Vue component which determines what to show based on an "authenticated" prop or so.

Dec
12
1 month ago
Activity icon

Awarded Best Reply on Package Commands Registration!

I don't see the advantages of one method over the other. Personally, I always use the first approach you mentioned.

Activity icon

Awarded Best Reply on Remove Github From Source Code

I don't know exactly what you're asking, but if you want to reset the git repository just delete the .git directory

rm -rf .git

Next, re-initialize git with git init and define the upstream Github repository. In case you're using the same repo as before, push with the force flag git push -f.

Dec
10
1 month ago
Activity icon

Replied to Remove Github From Source Code

I don't know exactly what you're asking, but if you want to reset the git repository just delete the .git directory

rm -rf .git

Next, re-initialize git with git init and define the upstream Github repository. In case you're using the same repo as before, push with the force flag git push -f.

Dec
06
1 month ago
Activity icon

Replied to General Class Or Model Or Repository Or Service - What / Where???

My advice: start by creating custom classes in the app/ directory. After you have a working application, you can always refactor to a cleaner approach at a later stage.

Getting started is the most important part and will provide new insights regarding how you would like to structure your application.

Furthermore, Jeffrey has a very comprehensive video series where you build a forum together using TDD. I learned a lot from this series. https://laracasts.com/series/lets-build-a-forum-with-laravel

Activity icon

Replied to Package Commands Registration!

I don't see the advantages of one method over the other. Personally, I always use the first approach you mentioned.

Dec
02
1 month ago
Activity icon

Replied to Restored() Event Is Not Triggering

From the Laravel documentation: https://laravel.com/docs/6.x/eloquent#soft-deleting

You may also use the restore method in a query to quickly restore multiple models. Again, like other "mass" operations, this will not fire any model events for the models that are restored:

App\Flight::withTrashed()
        ->where('airline_id', 1)
        ->restore();

So, to circumvent the issue, you could loop over all model instances and call restore() on each of them.

Nov
18
2 months ago
Activity icon

Replied to Need To Do 22K Curl Calls

I would recommend this series here on Laracasts: https://laracasts.com/series/queue-it-up

Activity icon

Replied to Laravel-FakeId Help

I just checked out this package and I must admit the readme is a somewhat incomplete. I've submitted a PR adding a section on the usage in the views.

After you've followed the setup instructions, you can use the package as follows:

Given you have a route to show a specific items in your web.php:

Route::get('items/{item}', '[email protected]')->name('items.show');

To generate a URL to a certain item, you can use the following code in your view:

{{ route('items.show', Item::first()) }}

This generates a link to 'items/{hash}' where the "hash" is translated to the corresponding ID. This way, an item with an ID of 1 can have a link /items/579747662. In that way, users of your application do not get information on how many items there are and cannot guess the next / previous entries.

Activity icon

Replied to Need To Do 22K Curl Calls

That are quite a lot of calls... If you do want to check them, youll have to do that one by one. The best way would be to create a Job that handles this one by one (via a Queue).

Activity icon

Replied to Redirection Problem With Laravel And Vue

The problem is that the administrator's view is also redirected and I don't want that to happen.

Could you include the related (admin. view) code?

Nov
12
2 months ago
Activity icon

Awarded Best Reply on Async Await And Axios

Use this in await this.getNextThing( item.id ) and return the axios response from the getNextThing() method perhaps?

Activity icon

Replied to Vue Lodash Sort By Nested Array

Not the most elegant approach, but it appears to be working as you intend.

First sort the lineStatusses by severity and then sort the railways by their first lineStatus (which is now the highest statusSeverity number).

lines.forEach(function (line) {

  let sorted = _.sortBy(line.lineStatus, function(status) {
    return status.statusSeverity;
  }).reverse();
  
  line.lineStatus = sorted;
});

let sorted = _.sortBy(lines, function(line) {
  return line.lineStatus[0].statusSeverity;
}).reverse();

console.log(sorted); // now shows the railways having the highest "severityStatus" first

You can play around with it on CodeSandbox: https://codesandbox.io/s/patient-smoke-gko6n

Activity icon

Replied to Async Await And Axios

Use this in await this.getNextThing( item.id ) and return the axios response from the getNextThing() method perhaps?