JohnBraun

JohnBraun

PhD candidate: Organic Chemistry at VU University Amsterdam

Member Since 1 Year Ago

Netherlands

Experience Points
117,720
Total
Experience

2,280 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
868
Lessons
Completed
Best Reply Awards
49
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 24
117,720 XP
08 Sep
2 weeks ago

JohnBraun left a reply on Route Model Binding Not Working

@chron That is something we never could have guessed from your question and the code you posted. Please try to formulate your questions better in the future. Please respect peoples time.

If you want to get help, you have to post (the relevant!) code.

JohnBraun left a reply on Route Model Binding Not Working

So, I understand that you have the following setup, right?


@foreach ($formdata as $data)
  <form action="{{ route('test.store', $data->id) }}" method="POST">
    @csrf
    <button type="submit">Submit with ID {{ $data->id }}</submit>
  </form>
@endforeach

What happens when you alternatively use a hidden input field?

@foreach ($formdata as $data)

  <form action="{{ route('test.store') }}" method="POST">
    @csrf

    <input type="hidden" name="id" value="{{ $data->id }}">

    <button type="submit">Submit</button>
  </form>
@endforeach

Then the route becomes:

Route::post('test','[email protected]')->name('test.store');

And your controller:

public function store()
{
    dd(request('id'));
}
04 Sep
2 weeks ago

JohnBraun left a reply on Laravel 5.8 Email Verification Not Working With Different Browsers

@hafizur If youre using Laravel 5.8 and properly copied the VerificationController code everything should work. Could you double check your code?

03 Sep
2 weeks ago

JohnBraun left a reply on Is There Such Method In Collection?

Right, that is the result of the map function you have provided. So ... what is your question?

JohnBraun left a reply on Is There Such Method In Collection?

Could you elaborate on the problem you have a bit more?

For now, I don't see what you are looking for.

JohnBraun left a reply on Common Functions In Laravel

Yes, you can add as many helper functions as you like in the app/helpers.php file.

You could also split them amongst multiple files, as long as you include them in the composer.json 'files' array within the autoloader section.

JohnBraun left a reply on Common Functions In Laravel

I believe you want to create your own global helper functions which will be accessible throughout your entire application.

To do so, create a helpers.php file in your 'app' directory, and let's add a function you want globally available:

// helpers.php

function myFunction($message)
{
    return 'this is my ' . $message;
}

Now, let's include your helpers file under a files key in the composer.json file, within the autoload section:

// composer.json

    "autoload": {
        "psr-4": {
            "App\": "app/"
        },
        "classmap": [
            "database/seeds",
            "database/factories"
        ],
        "files": [
            "app/helpers.php"
        ]
    },

Finally, run composer dump-autoload and try it out in!

You can now run myFunction('message') anywhere in your app.

JohnBraun left a reply on Laravel 5.8 Email Verification Not Working With Different Browsers

Hey @hafizur,

You are correct. The VerificationController makes use of the auth middleware, which requires users to first be authenticated before verifying their e-mail address.

To circumvent this, an approach you could take is as follows:

Step 1. Comment out the `auth` middleware from the VerificationController

    public function __construct()
    {
        // $this->middleware('auth');
        $this->middleware('signed')->only('verify');
        $this->middleware('throttle:6,1')->only('verify', 'resend');
    }

Step 2. Override the verify() method from the VerifiesEmails trait

In the VerifiesEmails trait, the verify() method checks if the currently logged in user's ID is equal to the ID of the user that is requested to be verified. We don't want to do this, so we'll override the method in the VerificationController:

public function verify(Request $request)
    {
        // if ($request->route('id') != $request->user()->getKey()) {
        //     throw new AuthorizationException;
        // }

        $user = User::find($request->route('id'));

        auth()->login($user);

        if ($request->user()->hasVerifiedEmail()) {
            return redirect($this->redirectPath());
        }

        if ($request->user()->markEmailAsVerified()) {
            event(new Verified($request->user()));
        }

        return redirect($this->redirectPath())->with('verified', true);
    }

Don't forget to import the necessary classes in the VerificationController:

use Illuminate\Http\Request;
use Illuminate\Auth\Events\Verified;
use Illuminate\Auth\Access\AuthorizationException;

The complete `VerificationController` then looks as follows:

<?php

namespace App\Http\Controllers\Auth;

use Illuminate\Http\Request;
use Illuminate\Auth\Events\Verified;
use Illuminate\Auth\Access\AuthorizationException;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\VerifiesEmails;

class VerificationController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Email Verification Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling email verification for any
    | user that recently registered with the application. Emails may also
    | be re-sent if the user didn't receive the original email message.
    |
    */

    use VerifiesEmails;

    /**
     * Where to redirect users after verification.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        // $this->middleware('auth');
        $this->middleware('signed')->only('verify');
        $this->middleware('throttle:6,1')->only('verify', 'resend');
    }

    public function verify(Request $request)
    {
        // if ($request->route('id') != $request->user()->getKey()) {
        //     throw new AuthorizationException;
        // }

        $user = \App\User::find($request->route('id'));

        auth()->login($user);

        if ($request->user()->hasVerifiedEmail()) {
            return redirect($this->redirectPath());
        }

        if ($request->user()->markEmailAsVerified()) {
            event(new Verified($request->user()));
        }

        return redirect($this->redirectPath())->with('verified', true);
    }
}
04 Aug
1 month ago

JohnBraun left a reply on Session Timeout Redirect To A Lockscreen

If you combine the example as explained in the thread you've posted and this GitHub gist found in this thread, I think you could get your idea working.

03 Aug
1 month ago

JohnBraun left a reply on How Do I Set An End Point With An Array Of Values

intial thought

I first thought you wanted to load a bunch of orders using their id, which you would send along to an endpoint like `/api/order/1,2,3,4,5` which would then fetch those orders.

current understanding of your question

However, now I understand from your post that you want to be able to submit those id's as an array.

Instead of using axios.get, I would advise to use axios.post and register the route as Route::post.

In your axios.post call, you specify the endpoint as the first argument and the payload as the second argument. This payload can be your desired array.

axios.post('/api/list/order', ['ids' => [1,2,3,4,5]])
    .then()
    .catch();

Then, in your controller you'll have access to that array of id's:

public function listOrders()
{
    $ids = request('ids'); // [1,2,3,4,5]
    $orders = DB::table('products')->whereIn('id', $ids)->get();
    // etc.
}

JohnBraun left a reply on How Do I Set An End Point With An Array Of Values

In the backend you're returning a collection of 'products' from that table where the id's are in the array you 've passed to the endpoint.

What is that you want to achieve on the front end part?

JohnBraun left a reply on Laravel Echo Events Render Issue

Did you recompile your assets with npm run dev (or npm run prod / npm run watch)?

JohnBraun left a reply on How Do I Set An End Point With An Array Of Values

Well, if you decide to get all orders from a comma separated string in the URL, you can first explode that string into an array:

public function list_order($order = null){

    if ($order == null) {
        abort(404, 'No order was passed');
    }

    $order = explode(',', $order);
    
    $orders = DB::table('products')->whereIn('id', $order)->get();

    return $orders;
}
30 Jul
1 month ago

JohnBraun left a reply on Call To A Member Function ToSql() On Array

Cant you produce that query yourself from the combination of values in the query and bindings array?

JohnBraun left a reply on AssertSee Videos?

To answer your question we need a little more information regarding your view (blade/vue/...) template

JohnBraun left a reply on Call To A Member Function ToSql() On Array

dd(DB::getQueryLog());

Gives you an array, containing the keys 'query', 'bindings' and 'time'.

JohnBraun left a reply on Call To A Member Function ToSql() On Array

you also get a 'bindings' key in that array. Doesn't that give you these values?

JohnBraun left a reply on Getting Data From Another Website Using Axios

@hjortur17 Ask the owner of the site to add the CORS headers. Alternatively, you might be able to scrape the website.

@martinzeltin that will yield the same error

JohnBraun left a reply on Call To A Member Function ToSql() On Array

DB::connection('second_connection')->enableQueryLog();

DB::connection('second_connection')->select("
                 SELECT id, reply_text, sending_time
                 FROM inbox_replies
            ");

dd(DB::getQueryLog());

JohnBraun left a reply on Laravel Store Function

You'll have to properly import your User/CommentController

// Admin/CommentsController

use App\Http\Controllers\User\CommentController as UserCommentController;

public function abc()
{
    // ....
    UserCommentController::store();
}

JohnBraun left a reply on Start A Project Offline

Have you tried using Homestead yet? That's a great solution for working on Windows

https://laravel.com/docs/5.8/homestead

JohnBraun left a reply on Getting Data From Another Website Using Axios

The website does not allow foreign ajax calls.

JohnBraun left a reply on Call To A Member Function ToSql() On Array

You already specify the sql query, so what would you try to achieve?

SELECT id, reply_text, sending_time
                 FROM inbox_replies

JohnBraun left a reply on Redirect After Login

To bypass the intended path problem, you can define an authenticated method on the LoginController where to redirect to, that takes precedence over the standard intended path.

Wouldn't something like this do the trick?

// LoginController

public function authenticated()
{
    if (auth()->user()->role == 'admin') {
        return redirect('/admin');
    }

    return redirect('/');
}
29 Jul
1 month ago

JohnBraun left a reply on Modifying A HasMany() To Return A Row For Each Date In A Relation

@miguelstevens That's completely possible!

Laravel ships with the DateTime library called Carbon. This library has a CarbonPeriod class, which does exactly what you want.

You can use it in the following way:


use Carbon\Carbon;
use Carbon\CarbonPeriod;

$start = Carbon::parse('20 july 2019');
$end = Carbon:parse('25 july 2019');

$period = CarbonPeriod::between($start, $end);

$dates = collect($period)->map(function ($date) {
    return $date->format('d-m-Y');
});

/** $dates is now equal to: 
 [
       "20-07-2019",
       "21-07-2019",
       "22-07-2019",
       "23-07-2019",
       "24-07-2019",
       "25-07-2019",
     ]
**/

However, if you're retrieving the start and end dates from an eloquent model, you can define the column names to be cast to dates already in your base model class:

// Model.php

protected $dates = ['start', 'end'];

Then, you don't have to parse the date first, but directly use them:

use Carbon\CarbonPeriod;

$period = CarbonPeriod::between($model->start, $model->end);

$dates = collect($period)->map(function ($date) {
    return $date->format('d-m-Y');
});

JohnBraun left a reply on Modifying A HasMany() To Return A Row For Each Date In A Relation

Could you elaborate a bit more on the actual behaviour of the piece of code you're trying to write?

JohnBraun left a reply on App.js Not Updating When Using Vue

Did you register your component in resources/js/app.js?

Vue.component('product-sorting', require('./components/ProductSorting.vue').default);

And did you recompile your assets with Laravel mix (webpack)?

JohnBraun left a reply on Displaying An Info-collection Page At Every Login...

Add the following method to your app/Http/Controllers/Auth/LoginController.php:

public function authenticated()
{
    return redirect('/fill-in-this-form');
}
25 Jul
1 month ago

JohnBraun left a reply on Database Password Receive From API Request

Actually I don't think it is a good idea to store your password somewhere else than in your .env file.

Is there any particular reason why you want to do this?

JohnBraun left a reply on Git Pull Request From Local Branch

Ah, I see.

This is the info from BitBucket themselves:

Pull requests can be used in conjunction with the Feature Branch Workflow, the Gitflow Workflow, or the Forking Workflow. But a pull request requires either two distinct branches or two distinct repositories, so they will not work with the Centralized Workflow. Using pull requests with each of these workflows is slightly different, but the general process is as follows:

  • A developer creates the feature in a dedicated branch in their local repo.
  • The developer pushes the branch to a public Bitbucket repository.
  • The developer files a pull request via Bitbucket.
  • The rest of the team reviews the code, discusses it, and alters it.
  • The project maintainer merges the feature into the official repository and closes the pull request.

https://www.atlassian.com/git/tutorials/making-a-pull-request

JohnBraun left a reply on Database Password Receive From API Request

You could override the config() value where DB_PASSWORD is stored at runtime, using:

config(['database.connections.mysql.password' => $passwordFromApi]);

However, I don't know which database driver you're using.

Do note that you can't override .env variables at runtime.

JohnBraun left a reply on One Component For Edit/Create Pages

The basic idea is to reuse the same form template for creating and editing a resource (a "page" in your case).

Let's say we have a "title" and a "body" of a page, the form to create a page and edit the page would feature the very same form, except that it is populated in the latter case and the "create" button instead now says "save changes".

Is there something in general you're struggling with?

JohnBraun left a reply on Git Pull Request From Local Branch

Could you provide more details on your specific scenario? For now, I can give a you a general gist of what it would look like to submit a PR to a repository.

First you "fork" the repository, so you have your own copy of the repository. Then you would clone that repo, create a new branch, do all the work. Push the branch back up (to bitbucket in this case) and then create PR from your "forked" repository branch to the original repository's master / dev / ... branch.

JohnBraun left a reply on Testing Real Emails And Production Deployment Considerations

You can easily test Mailing in Laravel and verify the contents of a certain e-mail. Check out: https://laravel.com/docs/5.8/mocking#mail-fake

JohnBraun left a reply on N Laravel 5.8 How To Save File To Public Folder Instead Of Saving To Storage

You have full control over the configuration of your filesystems in the corresponding config file.

Check out "config/filesystems.php":

return [
// ...

  'disks' => [
    'public' => [
      // ...
      'root' => storage_path('app/public'),
      'url' => env('APP_URL').'/storage',
      // ...
    ]
  ]

JohnBraun left a reply on Api

Do you have a more specific question? Is there any in particular that you're struggling with?

Otherwise, just do a Google search and try how far it'll get you.

JohnBraun left a reply on Dynamic Prefix Routing

@aznyouth "This doesn't work for me."

Sorry, my reply was meant to explain where the problem originates from, not a solution.

To make this system work the way you want, you should return a route based on the user's current location, instead of just returning the route called "login" in the Authenticate middleware.

// app/Http/Middleware/Authenticate.php

    protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
            // return route('login');
            return $request->url() . '/login';
        }
    }

JohnBraun left a reply on How To Show Only User Id And Name In Post , Comment And User Relationship Laravel?

Then you would need to collect all comments (both where the status is 0 and those with status 1), and handle the hiding logic on the front end.

For example, you could make a Vue component and then use it in your view:

Controller

public function index()
{
    $posts = Post::with('comments.user')->get();

    return view('posts.index', compact('posts'));
}

Blade View

<blog-post :posts="{{ $posts }}" />

The Vue component:

<template>
  <div>
      <article v-for="post in posts">

          <!-- post title, body, etc. -->       

          <div v-for="comment in post.comments" v-show="comment.status === 1">
                  <!-- here the actual comment -->
          </div>

      </article>    
  </div>
</template>

<script>
export default {
    props: ['posts'],     
}
</script>
24 Jul
1 month ago

JohnBraun left a reply on How To Show Only User Id And Name In Post , Comment And User Relationship Laravel?

@raviawasti Sure, add a whereHas method:

public function index()
{
    $posts = Post::whereHas('comments', function ($query) {
      $query->where('status', 1);
    })->with('comments.user')->get();

    return view('posts.index', compact('posts'));
}

JohnBraun left a reply on Dynamic Prefix Routing

edit: This is not a solution, only an explanation of the observed behaviour.

The problem is caused by the fact that you have multiple routes defined called "login". If I may simplify your example, it comes down to this routes file:

Route::group(['prefix' => 'front'], function() {
    authRoutes(); 
    // will evaluate to: 
    // Route::get('login', 'Auth\[email protected]wLoginForm')->name('login');
    
    Route::get('/', '[email protected]');
});

Route::group(['prefix' => 'admin'], function() {
    authRoutes(); 
    // will evaluate to: 
    // Route::get('login', 'Auth\[email protected]')->name('login');
    
    Route::get('/', '[email protected]');
});

function authRoutes()
{
    Route::get('login', 'Auth\[email protected]')->name('login');
}

Since you have the route called "login" multiple times defined, Laravel will always pick the last defined one.

In the app/Http/Middleware/Authenticate class, this route is returned when not authenticated.

// app/Http/Middleware/Authenticate.php

    protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
            return route('login');
        }
    }

You can see this in action if you change the order of the Route::group functions. If you put "admin" before "front", now all logins will be redirected to "/front/login".

JohnBraun left a reply on Watermark Pdf Pages

You could search for existing packages on Packagist, where I found this library which might do what you want https://github.com/binarystash/pdf-watermarker

<?php

//Specify path to image. The image must have a 96 DPI resolution.
$watermark = new PDFWatermark(base_path('path/to/watermark/image.png'); 

//Set the position
$watermark->setPosition('bottomleft');

//Place watermark behind original PDF content. Default behavior places it over the content.
$watermark->setAsBackground();

//Specify the path to the existing pdf, the path to the new pdf file, and the watermark object
$watermarker = new PDFWatermarker(base_path('/path/to/input.pdf'), base_path('/path/to/output.pdf'), $watermark); 

//Set page range. Use 1-based index.
$watermarker->setPageRange(1,5);
 
//Save the new PDF to its specified location
$watermarker->savePdf(); 
?>

JohnBraun left a reply on How To Show Only User Id And Name In Post , Comment And User Relationship Laravel?

Post model

// Post model (Post.php)

public function user()
{
    return $this->belongsTo(User::class)->select(['id', 'name']);
}

public function comments()
{
   return $this->hasMany(Comment::class);
}

Comment model

public function user()
{
    return $this->belongsTo(User::class)->select(['id', 'name']);
}

Controller

public function index()
{
    $posts = Post::with('comments.user')->get();

    return view('posts.index', compact('posts'));
}

JohnBraun left a reply on Is There A Way For Web Push Notification Like One Signal For Every Action In Laravel Such As Like, Comment, Asnwer

Maybe you could take a look at Laravel's model events and hook in to them, creating a listener that broadcast / notify user(s) upon execution

https://laravel.com/docs/5.8/eloquent#events

JohnBraun left a reply on Best Practice For Laravel Test Case Helper Functions?

@uccdev

In method 2 we're not modifying any behaviour (of "CreatesApplication"), just adding a function to the TestCase class.

Next, in your unit/feature tests you extend (and thereby inherit from) that TestCase class. Therefore, the method will be available in all classes (tests) that extend the TestCase class.

23 Jul
1 month ago

JohnBraun left a reply on Best Practice For Laravel Test Case Helper Functions?

There are multiple options

Keeping them in the same test file

One way to get around this is using annotation to separate your test methods from your other methods. Aditionally, you can make the helper protected or private.
     class MyTest extends TestCase {
     
        protected function myHelperFunction($arg) {
            return $arg + some actions;
        }
     
        /** @test */
        public function put_a_descriptive_method_name_here() {
            $arg = "my_arg_here";
            $this->assertNotNull($this->myHelperFunction($arg));
        }
            ... //other tests that involve my helper function
     }

Put the helpers in the TestCase class

You can put the methods on the base TestCase class if you'd like
abstract class TestCase extends BaseTestCase
{
    use CreatesApplication;

    protected function setUp()
    {
        parent::setUp();
        //....
    }

    protected function myHelperFunction($arg)
    {
        return $arg + some actions;
    }
}

Extract them to (e.g.) a helpers.php file

A different option is to put them in a helpers.php file in your tests directory, which you autoload using composer.

In composer.json:

    "autoload-dev": {
        "psr-4": {
            "Tests\": "tests/"
        },
        "files": [
            "tests/helpers.php"
        ]
    },

Don't forget to dump the autoload using

composer dump-autoload
22 Jul
2 months ago

JohnBraun left a reply on Add Array Form Field

$product = request('product');

JohnBraun left a reply on Show "logged In" Sessions / Logout Single Session

I don't know if there is a way to show all current sessions, but I know that a user can request to log out all of his other devices, is that what you are trying to achieve?

If so, check out this video

And in the Laravel documentation: Logging Out

20 Jul
2 months ago

JohnBraun left a reply on Tailwind @apply In My Vue Components Styles Block

border-primary is not a Tailwind CSS class...

JohnBraun left a reply on Laravel Echo Did Not Receive Event (event Not Broadcasted?)

I wrote an article on that topic, maybe thatll set you on the right track https://johnbraun.blog/posts/websockets-in-laravel