JohnBraun

JohnBraun

Member Since 1 Year Ago

Netherlands

PhD candidate: Organic Chemistry at VU University Amsterdam

Experience Points 95,400
Experience Level 20

4,600 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 765
Lessons
Completed
Best Reply Awards 30
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.

17 Jun
1 day ago

JohnBraun left a reply on How Can I Structure My Database?

I think your best bet is a many-to-many table.

Potions table: id (int), name (string), dose (int), price (int)

Mixtures table: id (int), name (string)

mixture_potion table: mixture_id (int), potion_id (int)

From the many to many relationship, you can then collect the potions that were combined for this mixture, and calculate the total "dose".

$mixture = Mixture::first();

$totalDose = $mixture->potions->sum('dose');

To calculate the cheapest option to obtain a mixture with a given "dose", you'll first need to break it down to possible combinations of the potions. Let's say we have a total dose of 4, we can achieve that in multiple ways:

// If the total dose of the mixture is 4
$totalDose = $mixture->potions->sum('dose'); // = 4;

// Buy 4 potions of dose "1"
$costsA = $potionA->price * 4;

// Buy 2 potions of dose "2"
$costsB = $potionB->price *2;

// Buy 1 potion of dose "2" and 2 potions of dose "1"
$costsC = $potionB->price + (2 * $potionA->price);

Does that answer your question?

JohnBraun left a reply on Manual Login

Looking at the authentication middleware that ships with Laravel, does your code work when you use the following middleware?

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Factory as Auth;

class isAuth
{
    protected $auth;

    public function __construct(Auth $auth)
    {
        $this->auth = $auth;
    }

    public function handle($request, Closure $next)
    {
        if (! $this->auth->check()) {
            return route('showLogin');
        }

        return $next($request);
    }
}

Remember that you can return early and skip the if/else construction.

16 Jun
2 days ago

JohnBraun left a reply on Payment Plan Laravel

@DEVFREY - Tried posting the same question a couple of times on the Laracasts forum

15 Jun
3 days ago

JohnBraun left a reply on How To Get Id In Session?

@SNAPEY - I see I've messed that up in my comments as well, I meant $article->id where I said $article_id (was typing on mobile when I replied). I've updated my comments above.

JohnBraun left a reply on Get Dynamic Csrf Token

@KUNDEFINE - The idea is not to move your function into a blade file...

JohnBraun left a reply on Get Dynamic Csrf Token

@KUNDEFINE - Please read our comments again

14 Jun
4 days ago

JohnBraun left a reply on How To Get Id In Session?

@IRANKHOSRAVI - @jlrdw I see

@irankhosravi For your specific example it would be

session(['id' => $article_id]);

JohnBraun left a reply on How To Get Id In Session?

@IRANKHOSRAVI - That line of code stores the id of the saved article to the article_id key in the session. Then you can grab the id from the session using session()->get(‘article_id’)

JohnBraun left a reply on How To Get Id In Session?

If you want to store the ID of the newly saved article in the session, you should do that as follows in your controller:

public function store()
{
    // ...
    $article->save();
    
    session(['article_id' => $article_id]);

    return redirect()->route('notes.index')->with('id', $request->id);
}

JohnBraun left a reply on How To Create Composer Package ?

This course by Marcel Pociot is really good and helped me develop my first package. If I can do it, so can you!

https://phppackagedevelopment.com/

JohnBraun left a reply on Update Record Without Updating Timestamp

You could define a scope your on your model:

class Member extends Model
{
    public function scopeWithoutTimestamps()
    {
        $this->timestamps = false;
        return $this;
    }
}

Then, use it as follows:

Member::withoutTimestamps()->where('member_id', $user->id)->update(['active' => false]);

JohnBraun left a reply on Ideal SVG Size

I guess 512 px by 512 px is a standard logo

JohnBraun left a reply on Ideal SVG Size

An SVG file doesn't have dimensions, it is a vector

JohnBraun left a reply on Ideal SVG Size

Well, the idea with SVG is that you can scale it indefinitely without losing resolution. Therefore I don't get your question.

JohnBraun left a reply on Is It Possible To Cache External Images?

I think I don't understand your (actual) question.

The image will be cached by the clients browser when you provide the image and they have to download it.

JohnBraun left a reply on What Should I Use In Laravel For Onpage Add, Edit ,delete,view ,like,update In My Discussion Forum Platform?

Jeffrey has a really in-depth series here in which you build a forum together: https://laracasts.com/series/lets-build-a-forum-with-laravel

It is mainly focused on TDD.

JohnBraun left a reply on Communicate To Webserver Using Websocket (pusher/laravel-echo). Not An Endpoint.

Are you looking for something like this?

https://laravel.com/docs/5.8/broadcasting#client-events

From the documentation page:

Sometimes you may wish to broadcast an event to other connected clients without hitting your Laravel application at all. This can be particularly useful for things like "typing" notifications, where you want to alert users of your application that another user is typing a message on a given screen.

Echo.private('chat')
    .whisper('typing', {
        name: this.user.name
    });

To listen for client events, you may use the listenForWhisper method:

Echo.private('chat')
    .listenForWhisper('typing', (e) => {
        console.log(e.name);
    });

JohnBraun left a reply on How To Config Nginx To Server Static Html Website

Did you add ("install") your repository to the site you created within Forge?

JohnBraun left a reply on Can I Use Vuejs With Ajax In My Laravel Project For My Only Dashboard Page?

Is you dashboard made with Laravel? If so, it comes out of the box with the axios library, which can make AJAX calls within Vue for you. You'll end up with something like this:

export default {

    data() {
        return {
            payload: {},
        }
    },

    mounted() {
        axios.get('/endpoint').then(response => {
            this.payload = response.data;
        });
    }
}

Check out Jeffrey's video's on VueJS: https://laracasts.com/series/learn-vue-2-step-by-step

13 Jun
5 days ago

JohnBraun left a reply on Vue.js Some Items In Checkout Card Are Not Reactivity

@lars-janssen you also have a typo in “bestaalstatus” which should be “bestelstatus” ;-)

JohnBraun left a reply on Guzzle API Response

@MARCELLOPATO - And $receita[‘data’][‘natureza_juridica’]; then? Sorry, I am not at home otherwise I would’ve validated my replies.

JohnBraun left a reply on Guzzle API Response

$receita->toArray()[‘data’][‘natureza_juridica’]; ?

JohnBraun left a reply on Guzzle API Response

@MARCELLOPATO - $receita->data->natureza_juridica;

JohnBraun left a reply on Get Dynamic Csrf Token

@KUNDEFINE - A blade component is noting more than e.g. a form.blade.php file living in resources/views/components.

Then, you can include the form on your page:

<div> 
  @include(‘components.form’)
</div>

JohnBraun left a reply on Guzzle API Response

@MARCELLOPATO - What does a var_dump($receita) give you?

JohnBraun left a reply on Get Dynamic Csrf Token

@ Why don’t you extract your form to a blade component and use that component in your views?

JohnBraun left a reply on How Can I Save Comment_id In LIKE Table Without Displaying It On Code?

@ZHXSCRIPT - I agree on your point using uuid's, if this is what @raviawasti wants to achieve from a security perspective.

@raviawasti You could also still consider using a 'slug', see: https://laravel.com/docs/5.8/routing#implicit-binding

JohnBraun left a reply on How To Queue:work Only Notifications With ShouldQueue

@AUCT - Sounds like you want to be able to push to different queues.

From the Laravel documentation:

// This job is sent to the default queue...
Job::dispatch();

// This job is sent to the "emails" queue...
Job::dispatch()->onQueue('emails');

php artisan queue:work --queue=emails can be run separately from php artisan queue:work --queue=default

JohnBraun left a reply on Data Is Not Coming From Db Into Chart

Where is the Results coming from?

datasets: [{
                      label: 'Records',
                      data: Results,
                      borderWidth: 1
                  }]

JohnBraun left a reply on Issue Adding Days In A For Loop

To make the code more readable, you could try to refactor from the inside-out thus first creating a separate method for the inner for() loop:

for($a = 0; $a < $validated['attendance_sessions'];$a++) {

    Attendancesession::create([
        'attendances_id'    => $attendance->id,
        'session_starttime' => $validated['start_time'],
        'session_endtime' => $validated['end_time'],
        'session_date' => $sessionDate,
    ]);

    $sessionDate->add($validated['session_interval'], 'day');

}

// first refactor step:

public function createAttendanceSession($validated, $attendance, $sessionDate)
{
    for ($a = 0; $a < $validated['attendance_sessions']; $a++) {
        Attendancesession::create([
            'attendances_id'    => $attendance->id,
            'session_starttime' => $validated['start_time'],
            'session_endtime' => $validated['end_time'],
            'session_date' => $sessionDate,
        ]);

        $sessionDate->add($validated['session_interval'], 'day');
    }

    return true;
}
$courseDate = new Carbon($validated['start_date']);
for($i = 0; $i < $validated['no_classes'];$i++) {
                $course = Course::create([
                    'course_cat_id' => $coursecat->id,
                    'name' => $coursecat->name . ' : ' . $courseDate->format('Y-m-d'),
                    'start_date' => $courseDate->format('Y-m-d'),
                    'start_time' => $validated['start_time'],
                    'end_time' => $validated['end_time'],
                    'summary' => $validated['description'],
                ]);
                $sessionDate = new Carbon($courseDate); // Make a new carbon object and copy it into session date before adding days. This is then used in second iteration. and can be modified independantly of $courseDate
                $courseDate->add($validated['interval'], 'day');
                $no_courses++;
                $attendance = Attendance::create([
                    'course_id' => $course->id,
                ]);

// after initial for loop

$this->createAttendanceSessions($validated, $attendance, $sessionDate);

Now, after the first refactor step, a lot of things could be cleaned up: doubly used variables, lower the amount of variables we have to pass to the function(s), unclear variable names ($a), what should we return from the function (true, or a collection of created attendance sessions?), maybe we could use a collection instead of a for loop, maybe the whole API should be reworked. These are decisions you'd need to overthink.

Have you checked out Jeffrey's course on refactoring yet? https://laracasts.com/series/whip-monstrous-code-into-shape

JohnBraun left a reply on Guzzle API Response

Did you try to get it using:

$receita->natureza_juridica;

Or if you'd like to accept it in Vue:

export default {

data() {
    return {
        receita = {};
    }
},

created() {
    axios.get('https://www.receitaws.com.br/v1/cnpj/').then((response) => {
        this.receita = response.data;   
    });
},
}

Then you could use this.receita.natureza_juridica to access the value

JohnBraun left a reply on Issue Adding Days In A For Loop

@CTYLER - Great! you're welcome

JohnBraun left a reply on Get Dynamic Csrf Token

Do you get the value when you dd(csrf_token()); in your controller? If so, I would do something like this:

public static function generateForm() {
    $output = '';

    $output .= '<form action="/category" method="post">
                    <input type="hidden" name="_token" value="'. csrf_token() .'">
                    <input type="text">
                    <input type="submit" value="Submit" id="">                      
                </form>';
    return $output;
}

JohnBraun left a reply on How To Queue:work Only Notifications With ShouldQueue

What are you trying to achieve? Could you please formulate your question a bit better?

The ShouldQueue interface puts the Notification on the queue, which is handled by the worker when running php artisan queue:work (except when the queue driver is set to sync, then everything bypasses the queue and is handled right away).

JohnBraun left a reply on Single Page App On Homestead

Aha, OK.

Since Homestead uses nginx, you should update your server configuration.

I've never used Homestead before, but I assume you have a site available in the /etc/nginx/sites-available folder. I guess you have some server block as listed below. Then, you just update the location / block to use index.html instead of $uri $uri/ /index.php?$query_string.

server {
    listen 80;
    listen [::]:80;

    . . .

    root /var/www/html/quickstart/public;
    index index.php index.html index.htm index.nginx-debian.html;

    server_name example.com www.example.com;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    . . .
}

JohnBraun left a reply on Mkdir(): No Such File Or Directory

  1. What does $location return?
  2. Could you show the save() method from the Image class?

JohnBraun left a reply on Single Page App On Homestead

The public/index.php file is the bootstrapping of Laravel itself, so you lead all incoming web requests to that file.

JohnBraun left a reply on How Can I Save Comment_id In LIKE Table Without Displaying It On Code?

@RAVIAWASTI - If you have a hidden text input like this:

<input type="hidden" name="comment_id" value="1">

You can get the value of that field by using the following javascript code:

let comment_id = document.querySelector("input[name='comment_id']").value;
12 Jun
6 days ago

JohnBraun left a reply on Issue Adding Days In A For Loop

@SNAPEY - You'd beat me to it! :-D

JohnBraun left a reply on Filter Data

$childrenWithEvents = auth()->user()->children()->whereHas('events')->get();

JohnBraun left a reply on Filter Data

You mean something like this?

User::whereHas(' children.events')->get();

JohnBraun left a reply on Issue Adding Days In A For Loop

Hey, I took a look at your code and I noticed that you're incrementing a $no_courses variable after every parent for loop. I think that is redundant, since it will always equal $validated['no_classes], right?

To address your problem, in your inner for loop you first set $sessionDate = $courseDate, and at the end you increase the days on this date. Then, in your next loop, you'll reset the updated $sessionDate back to $courseDate.

    for ($a = 0; $a < $validated['attendance_sessions']; $a++) {
        $sesssionDate = $courseDate;
    // here we've reset the updated $sessionDate back to $courseDate.
        
        Attendancesession::create([
            'attendances_id'    => $attendance->id,
            'session_starttime' => $validated['start_time'],
            'session_endtime'   => $validated['end_time'],
            'session_date'      => $sesssionDate,
        ]);
        
        $sesssionDate = $sesssionDate->addDays($validated['session_interval']); 
    // here we've updated $sessionDate
    }

JohnBraun left a reply on How Can I Save Comment_id In LIKE Table Without Displaying It On Code?

I have two options of reading your question.

  • Option 1: You don't want ID's but you want slugs, like here on Laracasts (../discussions/../how-can-i-....)

  • Option 2: You just don't want to show an 'id' in your code

Why don't you want to show the comment id to the user? Your database will need to know in the end.

Normally, you would probably pass this value via the route, like:

https://myapp.com/comments/1

Here, '1' is the id. It's not a shame to capture the 'id' and put it in a hidden .

JohnBraun left a reply on Create Table Point Using One To Many

I don't understand your question, could you please specify what it is you're trying to achieve?

JohnBraun left a reply on Adding A Step Before Registration

The authentication that ships with Laravel has controllers in the App\Http\Controllers\Auth namespace.

From there on, you'll find a RegisterController from which you can poke deeper.

Take a look at the documentation: https://laravel.com/docs/5.8/authentication#authentication-quickstart

JohnBraun left a reply on Suggestion - Plan Package

Is it something Laravel Spark may solve for you? https://spark.laravel.com/

There is a series on Laracasts as well: https://laracasts.com/series/laravel-spark