alchermd

Member Since 2 Years Ago

Malolos

Experience Points
21,210
Total
Experience

3,790 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
183
Lessons
Completed
Best Reply Awards
2
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 5
21,210 XP
Apr
24
5 months ago
Activity icon

Replied to How Do I Create A File From Path For Testing?

@FTIERSCH - Sadly, that page (which is essentially the same as the official docs) tackles how to create a fake file. The CSV file that I need follows a specific format, thus the reason I need to submit the file itself instead of a fake one.

Apr
21
5 months ago
Activity icon

Started a new conversation How Do I Create A File From Path For Testing?

Hello everyone.

Given that I have a CSV file that I'd like to use with the following path storage/test/files/records.csv, how do I implement the following test code?

// Given a CSV file with records in it.
$csv = /** how? */

// When it is submitted to the POST handler.
$this->actingAs($admin)
    ->post(route('records.store'), [
        'csv' => $csv
    ]);

// Records are persisted to the database.
$this->assertDatabaseHas('records', [
    'foo' => 'bar'
]);

Closest that I came up with is

use Symfony\Component\HttpFoundation\File\File;

// Exception: Serialization of 'Symfony\Component\HttpFoundation\File\File' is not allowed.
$csv = new File(storage_path('test/files/records.csv'));

... but validating the file ($request->validate(['csv' => 'file|mimes:csv'])) throws the exception in the snippet above. Any help will be greatly appreciated!

Apr
13
6 months ago
Activity icon

Replied to Field 'faculty_id' Doesn't Have A Default Value

The error implies that faculty_id is not supplied. Is the $id variable the id of the related faculty? If it is, you can do something like:

public function update(Request $request, $id)
{
  // ...

  $departement = new Departement([
    'name' => $request->get('name'),
    'speciality'=> $request->get('speciality'),
    'faculty_id' => $id
  ]);

  $departement->save();

  // ...
}

Or better yet, utilize route model binding and simplify your code a lot more:

public function update(Request $request, Faculty $faculty)
{
  // ...
  
  $faculty->department()->create([
    'name' => $request->get('name'),
    'speciality'=> $request->get('speciality'),
  ]);
  
  // ...
}
Mar
20
6 months ago
Activity icon

Replied to Checkdatetime Between Two Times

@STEREOH - Ooops. Thanks for checking it out, I may have misunderstood the premise. I thought "if time is ..." meant "if time today ...". Which I guess makes sense given how he structured his question, but yeah, it can be interpreted as "if time from the input ...".

Activity icon

Replied to Checkdatetime Between Two Times

@WISSAL - Follow the link that I gave and put the logic within the passes method of your custom Rule class.

Activity icon

Replied to Checkdatetime Between Two Times

if (
    $date->gte(Carbon::parse('today 8am')) && $date->lte(Carbon::parse('today 12pm')) ||
    $date->gte(Carbon::parse('today 14pm')) && $date->lte(Carbon::parse('today 16pm'))
) {
   // Do your stuff.
}

You might want to create a custom Rule for this one so you can use it within your validation string.

Disclaimer: I'm not on my dev laptop so the code above is untested, but the logic should be the same.

Jan
06
9 months ago
Activity icon

Replied to Email Verification Isn't Rendering Properly

For documentation purposes, I solved it by publishing the laravel-notifications without any customization and it worked for some reason

php artisan vendor:publish --tag=laravel-notifications

https://i.imgur.com/gLwdReu.png

My hunch is there's a conflict between 5.6 and 5.7 that inflates the markdown mails, resulting with the email verification mail not rendering properly (don't quote me on this haha).

Jan
05
9 months ago
Activity icon

Started a new conversation Email Verification Isn't Rendering Properly

I'm lost what went wrong here.. The mailable isn't even renderable, AFAIK. Can someone help me out? Thanks!

Dec
31
9 months ago
Activity icon

Replied to How Do I Generate A Route For An Array Of Query Strings?

Rubber duck debugging works lmao. Just as I posted the question I realized that:

route('search.courses', [
   'languages' => [
       $lang1,
       $lang2  
    ]
 ])

does exactly what I want.

Activity icon

Started a new conversation How Do I Generate A Route For An Array Of Query Strings?

Say I have a test case like:

public function a_user_can_search_for_courses_by_language()
{
    // ...

    $this->get(route('search.courses', [
        // Won't work since 'skills[]' is a duplicate key
            'languages[]' => $lang1->name,
            'languages[]' => $lang2->name,
        ]))
        ->assertSee($course->title);
}

What I want, in the end, is to send a get request to

/search?languages[]=lang1&languages[]=lang2

How do I generate a route for that?

Thanks!

Dec
02
10 months ago
Nov
27
10 months ago
Activity icon

Replied to Do You Prefer Helper Functions Over Facades/DI?

@MARTINBEAN - Oh yeah, that's exactly what I'm thinking of! With the trajectory of PHP becoming more Java-like, using global functions just feels out of place. I wouldn't have any issue with it if these functions need to be explicitly imported, though.

Activity icon

Replied to Do You Prefer Helper Functions Over Facades/DI?

@georgehanson

IIRC helper functions just resolve the classes from the container anyway, so there isn't really much difference between using a helper function or a facade.

My only gripe is that it messes up with autocompletion for PHPStorm. I hope there's an alternative way, like methods on the base Controller class so that we can do something like:

public function store()
{
   // This is already an option
   $this->validate();

    // Maps to auth()->check(), for example.
    if ($this->user()->isAuthenticated()) {
        // ...
    }

    // Akin to how Symfony does it.
    return $this->render('foo.bar');
}
Activity icon

Started a new conversation Do You Prefer Helper Functions Over Facades/DI?

To be precise, I'm talking about something like:

public function store(Request $request)
{
    $request->validate([/** ... */]);

    if (Auth::check()) {
        // ...
    }

    return view('foo.bar');
}

over something like:

public function store()
{
    request()->validate([/** ... */]);

    if (auth()->check()) {
        // ...
    }

    return view('foo.bar');
}

I used to think that the first one is more clear since Facades and/or injected dependencies are explicitly defined as parameters/imports. But lately I've been seeing that using helper functions results to more terse code, which kinda leads to lesser cognitive overhead when scanning a certain codebase.

What do you prefer?

Nov
21
10 months ago
Activity icon

Started a new conversation What's Your Most Favorite Series Here In Laracasts?

As the Black Friday sales commences, I think it's a good time to reflect and see what content we liked best here in Laracasts.

I personally think that The PHP Practitioner is a very solid introduction for the language. It covers a good chunk, from variable declarations to building a makeshift framework -- all within a reasonable time frame.

How about yours? :)

Nov
16
11 months ago
Activity icon

Replied to Black Friday 2018 Not Working

@XTREMER360 - Used to be https://laracasts.com/sales/holiday-2018 but I guess it wans't meant to go live yet.

Activity icon

Replied to QUESTION: Complete Profile First After Login Session

Add a boolean field profile_completed on the users table and check for that.

Nov
15
11 months ago
Activity icon

Replied to Black Friday 2018 Not Working

Same thing for me.

Activity icon

Replied to What Am I Missing Out If I'm Not Using A VM/Container For My Development Setup?

@SAPPOROGUY - > You are missing out on all the hipster grooves man!

Ayyyy I do like my hipster points!

From my simple understanding, docker has the benefit that everything you need is already packaged up and you don't have to deal with Infrastructure giving you headaches about your requirements.

Yeah, that makes sense and I can see how that could be useful. But I'm still not sold how that is better than $ bash setup_and_install_everything_i_need.sh. Which I'm sure someone will come later and educate me how that's terrible and I'm definitely all ears.

Still, if your setup works then Docker might just be a great learning experience rather than something you really need. Remember, the net has made it this far and we used to use FTP and folders on our local machines for version control.

100% agree.

Activity icon

Started a new conversation What Am I Missing Out If I'm Not Using A VM/Container For My Development Setup?

What up peeps.

For the past few weeks, I've dabbled and played around with Docker and Homestead just to see what's in store. But still, I can't see how much I'm gaining for the effort when my current setup (locally installed PHP7.2+Postgres+Redis etc. on a Linux box which is pretty much identical to my production setup) already works. Can someone fill me in? Maybe I'm looking at it the wrong way.

Thanks for your input!

Nov
14
11 months ago
Activity icon

Replied to Dusk Not Using Correct Environment

@skoobi maybe try this solution that I found a couple months back: https://github.com/laravel/dusk/issues/531#issuecomment-412123677

Nov
10
11 months ago
Activity icon

Replied to Dusk Is Not Connecting To The Expected Database

Glad I could help. Dusk is a pretty awesome project, but I almost gave up when I experienced this issue and there was no documentation around. Good luck on your tests!

Nov
09
11 months ago
Activity icon

Replied to How Do I Test Login Throttling?

Anyway, I found a workaround and just assert to expect a ValidationException to be thrown for the sixth login attempt. I think I'm good with that for now. Thanks everyone!

Activity icon

Replied to How Do I Test Login Throttling?

@D9705996 - Hi! I don't think the ThrottlesLogins trait applies the middleware explicitly (or at all) so I can't test it that way.

Activity icon

Started a new conversation How Do I Test Login Throttling?

Hello!

I've built a customized authentication system that isn't that much different from what the make:auth scaffolds for us, and have recently added throttling via the ThrottlesLogins trait. I have confirmed with manual usage that it does indeed throttle the login attempts, but have yet to find a way to write a concise test for it. What I currently have:

/** @test */
public function multiple_invalid_login_attempts_are_throttled()
{
    $admin = $this->createAdminUser();

    $response = null;
    for ($i = 0; $i < 100; ++$i) {
        $response = $this->post(route('admin.authenticate'), [
            'email' => $admin->email,
            'password' => 'secret',
        ]);
    }

    $response->assertStatus(429); // Also tried asserting for headers and session errors, but no luck
}

What really trips me up is that I have this code block for throttling in my controller that isn't being triggered even after that many login attempts:

public function store(Request $request)
{
    if ($this->hasTooManyLoginAttempts($request)) {
        dd('hola!'); // This dd() should be triggered when running the test, but it does not ...
        $this->fireLockoutEvent($request);
        $this->sendLockoutResponse($request);
    }

    // ...
}

Any idea where should I look at?

Oct
04
1 year ago
Activity icon

Started a new conversation If You Write A Test For An Eloquent Model That Contains Business Logic, Is It Still A Feature Or A Unit Test?

Hola!

As an example, this Laracasts episode features a Team class that can add/remove members. The gist of the class is as follows:

class Team extends Model
{
    public function add(User $user) : void;
    public function remove(User $user) : void;
    public function count() : int;
    // etc...
}

The tests are as follows:

class TeamTest extends TestCase
{
    public function it_can_add_members() { }
    public function it_enforces_a_maximum_size() { } 
    public function it_can_remove_members() { } 
}

I have some questions:

  1. Is this test considered a feature test since it involves multiple classes (Team and User)

  2. If it isn't, does the fact that it hits the database (it being an Eloquent model) makes it not a unit test?

  3. Is the Team class the correct place to add the business logic in this case?

Thanks a bunch!

Aug
07
1 year ago
Activity icon

Started a new conversation Dusk: "These Credentials Do Not Match Our Records"

Hello!

I'm not 100% sure what's wrong with my setup. I've confirmed manually that my authentication works. It's just that Dusk keeps spouting "these credentials do not match our records" when I'm trying to login a user.

{
    $this->browse(function (Browser $browser) {
        $user = factory(User::class)->create([
            'password' => bcrypt('my-password-123'),
        ]);

        $browser->visit('/login')
                ->type('email', $user->email)
                ->type('password', 'my-password-123')
                ->click('input[type="submit"]')
                ->waitForLocation('/home'); // Fails here since it's being redirected back to the login page due to incorrect credentials.
    });
}

I tried using a .env.dusk, .env.dusk.local, and .env.dusk.testing with the same values as the .env file (except for the DB_DATABASE which I set to a separate mysql database). Any idea on how to fix this?

Aug
05
1 year ago
Activity icon

Replied to How Do I Query For A Field Of An Eloquent Model's Relationship?

Oh wow. That's painfully simple lol. I'm probably looking at the wrong side of the docs. Thanks!

Activity icon

Started a new conversation How Do I Query For A Field Of An Eloquent Model's Relationship?

So when a Member buys a Product, a Sales object is saved into the database. It contains the member_id and the product_id among other fields. Now, I'd like to implement a search field in which the user can search through the Sales product name.

public function index(Request $request)
{
        $term = $request->query('term');

        $sales = /** Find all Sales objects in which its Product contains the $term variable. */;

        return $sales;
}

How do I create that query? My searching led me to this snippet:

$sales = Sales::with(['product' => function ($query) use ($term) {
            $query->where('name', 'like', "%$term%");
}])->get();

But it still loads all of the Sales -- it just sets the relationship to product as null for those that don't contain the $term.

Any help is appreciated!

Jul
03
1 year ago
Activity icon

Replied to My Tests Return A 422 - Where Did I Go Wrong?

@Cronix Ahh I haven't thought of that. Will try logging it!

Activity icon

Replied to My Tests Return A 422 - Where Did I Go Wrong?

@click errr, there must have been a mix up in our replies. I'm referring to the Laracast's markdown parser behaving funnily with the /home text. Tested it with other parsers and it rendered just fine.

Anyway, I was aware of 422 and validation failures, I'm just not sure how to debug it inside a testcase since I can't dump any data that I want to the console as the test runs. Which I asked in the last reply if you perhaps know how :D

Activity icon

Replied to My Tests Return A 422 - Where Did I Go Wrong?

@rin4ik It's inside a testcase, dd doesn't dump anything to the console output.

Activity icon

Replied to My Tests Return A 422 - Where Did I Go Wrong?

Here's the raw markdown, surely I got it right. Must have been a bug.

Anyway, how do you check the response object inside a test?

Activity icon

Replied to My Tests Return A 422 - Where Did I Go Wrong?

Weird, '/home' is rendered as '/ho`.

Activity icon

Started a new conversation My Tests Return A 422 - Where Did I Go Wrong?

Hello!

I have this following feature test:

/** @test */
public function user_can_create_new_resource()
{
    $user = factory(\App\User::class)->create();

    $resourceData = [
        'title' => 'New resource',
        'body' => 'This is a new resource.',
    ];

    $response = $this->actingAs($user)
                     ->post('/resource', $resourceData);

    $response->assertStatus(302);
    
    // rest of the test...
}

The test test fails with the assertStatus stating that it received a 422 instead of a 302. Here are my validation rules:

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{
    $validatedData = $request->validate([
        'title' => 'required|unique:resources|min:3',
        'body' => 'required|min:10',
    ]);

    $resource = new Resource($validatedData);
    $resource->user_id = $request->user()->id;
    $resource->save();

    return redirect('/home');
}

I've confirmed that creating a new resource using my browser (through forms) work just fine — the data is persisted and I'm getting redirected to `/ho . Any ideas where I went wrong?

Jun
15
1 year ago
Activity icon

Replied to JSON Data Not Being Asserted

@tykus indeed, your solution is correct! It's kinda shameful that I'm only now being aware of the intricacies of HTTP status codes. I'm glad that I asked! :D

Activity icon

Replied to JSON Data Not Being Asserted

@tykus oh yeah that makes sense. Will try once I'm on my laptop.

Activity icon

Replied to JSON Data Not Being Asserted

@bobbybouwmann Invalid JSON was returned from the route., which triggers on the ->assertJson(['deleted' => 'true']) call.

@tykus I see, I'll keep that in mind!

Jun
14
1 year ago
Activity icon

Started a new conversation JSON Data Not Being Asserted

Hello!

I have this test:

/** @test */
public function can_delete_a_specific_task()
{
    $task = factory(Task::class)->create();

    $response = $this->delete('/api/tasks/' . $task->id);

    // dd($response);

    $response->assertStatus(204)
        ->assertJson(['deleted' => 'true']); // Invalid JSON was returned from the route.

    $this->assertDatabaseMissing('tasks', ['id', $task->id]);
}

that hits this method:

/**
 * Remove the specified resource from storage.
 *
 * @param  \App\Task  $task
 * @return \Illuminate\Http\Response
 */
public function destroy(Task $task)
{
    $task->delete();

    return response()->json(['deleted' => true], 204);
}

Uncommenting the dd() call will show the $response object as:

Illuminate\Foundation\Testing\TestResponse {#236
  +baseResponse: Illuminate\Http\JsonResponse {#2613
    #data: "{"deleted":true}"
    #callback: null
    #encodingOptions: 0
    ...
  }
}

which looks like the json {'deleted':true} is successfully being sent back. I have a similar test for POSTrequests and I was able to assert a {'created' : true} response. Any hints in where I went wrong?

May
28
1 year ago
Activity icon

Replied to How Do I Set Relationships With Conditions?

@rin4ik I don't have a Student or Teacher class; all I have is the default User class that uses a role_id field to determine its roles.

Activity icon

Started a new conversation How Do I Set Relationships With Conditions?

Say I have a User class that can have different role_ids.

>>> $johnTheStudent = User::create([
        'name' => 'John Doe',
        'major' => 'Information Technology',
        'role_id' => Role::where('name', 'Student')->first()->id, 
    ]);
>>> $janeTheTeacher = User::create([
        'name' => 'Jane Smith',
        'faculty' => 'Social Sciences',
        'role_id' => Role::where('name', 'Teacher')->first()->id, 
    ]);

Now, I'd like to create a Exam model that belongs to both a student and a teacher.

>>> $socialScienceExam = Exam::create([
        'passing_grade' => 80,
        'due_date' => Carbon::tomorrow(),
        'student_id' => $johnTheStudent->id,
        'teacher_id' => $janeTheTeacher->id,
    ]);

How do I define these relationships in the Exam model so I can use it like this:

>>> $socialScienceExam->teacher->name
'Jane Doe'
>>> $socialScienceExam->student->major
'Information Technology'
# etc etc

They are both User instances so I'm kinda stuck.

class Exam extends Model
{
    public function student()
    {
        $this->belongsTo(/** A User that has a role_id of a student */);
    }

    public function teacher()
    {
        $this->belongsTo(/** A User that has a role_id of a teacher */);
    }
}

Thanks in advance for the help, guys!

May
20
1 year ago
Activity icon

Replied to After Registration, Users Are Redirected To The Login Page. Help Me Debug?

Isn't that backwards? The app can have many students and companies. A one to one relationship means that there is only one student and one company, no? The way I set it up is that a User belongs to a Role, and a Role has many Users.

Activity icon

Replied to After Registration, Users Are Redirected To The Login Page. Help Me Debug?

@Cronix a user could either be a Student or a Company, at least from the start. I can see having an Admin role or different payment tiers in the future. Anyway, my current setup is having a role_id for a User which is connected to a Role model (seems cleaner than hard coding strings as a value for a role field).

Activity icon

Replied to After Registration, Users Are Redirected To The Login Page. Help Me Debug?

Hey guys one last thing: if I'd just use the App\User class with a account_type field, how would I setup belongTo and hasMany relationships between the account_types?

May
19
1 year ago
Activity icon

Replied to After Registration, Users Are Redirected To The Login Page. Help Me Debug?

@Snapey I assume it does because it extends the App\User class.

Activity icon

Replied to After Registration, Users Are Redirected To The Login Page. Help Me Debug?

@Vilfago @Cronix so when is it a good idea to extend the User class to do multi-model authentication?

Activity icon

Replied to After Registration, Users Are Redirected To The Login Page. Help Me Debug?

@Snapey The dd() is not present on the code, sorry for the confusion. I mean if it is it wouldn't even redirect to the login page anyway since the execution died at that point :D

Activity icon

Replied to After Registration, Users Are Redirected To The Login Page. Help Me Debug?

I would really want a native Laravel solution. I'm really conflicted right now, so I guess I'd try the roles approach too just to see how it works. But really, what I'm trying to do in my original post is possible, right?

Activity icon

Replied to After Registration, Users Are Redirected To The Login Page. Help Me Debug?

@Cronix wouldn't that make a massive User class if I ever need to add another account type in the future? I've heard that approach before, but I've also seen different models used (which makes more sense to me) for authentication. I'm not really sure which way to go.

Activity icon

Started a new conversation After Registration, Users Are Redirected To The Login Page. Help Me Debug?

I'm not really sure what's tripping my code up. I've bootstrapped my authentication with php artisan make:auth, and then customized the RegisterController to fit my multi-model setup.

Let's say my app has two models: Student and Company that both extend the User model. I'd like my app to login both of these models. For now, as the title states, I'm able to register new Students, but wasn't able to log them in. My RegisterController (stripped of comments):

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Validation\Rule;
use Illuminate\Http\Request;
use App\Student;
use App\Company;

class RegisterController extends Controller
{
    use RegistersUsers;

    protected $redirectTo = '/home';

    public function __construct()
    {
        $this->middleware('guest');
    }


    public function register(Request $request)
    {
        $this->validator($request->all())->validate();

        $guard = $request->_account_type;
        $user = $this->create($request->all());

        auth()->guard($guard)->login($user);
        
        dd(auth()->user()); // returns null.

        return redirect($this->redirectPath());
    }


    protected function validator(array $data)
    {
        if ($data['_account_type'] == 'student') {
            return Validator::make($data, [
                'name' => 'required|string|max:255',
                'email' => 'required|string|email|max:255|unique:students',
                'password' => 'required|string|min:6|confirmed',
                'school' => 'required|string',
                'course' => [
                    'required',
                    Rule::in(app()->get('courses')),
                ],
                'address' => 'required|string|min:10',
                'contact_number' => 'required|min:7',
            ]);
        }

        if ($data['_account_type'] == 'company') {
            return Validator::make($data, [
                'name' => 'required|string|max:255',
                'email' => 'required|string|email|max:255|unique:companies',
                'password' => 'required|string|min:6|confirmed',
                'school' => 'required|string',
                'field' => [
                    'required',
                    Rule::in(app()->get('courses')),
                ],
                'address' => 'required|string|min:10',
                'contact_number' => 'required|min:7',
            ]);
        }

        return back()->withErrors('Invalid account type.');
    }


    protected function create(array $data)
    {
        if ($data['_account_type'] == 'student') {
            return Student::create([
                'name' => $data['name'],
                'email' => $data['email'],
                'password' => Hash::make($data['password']),
                'school' => $data['school'],
                'course' => $data['course'],
                'address' => $data['address'],
                'contact_number' => $data['contact_number'],
            ]);
        }

        if ($data['_account_type'] == 'company') {
            return Company::create([
                'name' => $data['name'],
                'email' => $data['email'],
                'password' => Hash::make($data['password']),
            ]);
        }
    }
}

Note that in the register method, a call to dd(auth()->user()); returns null even after the attempt to log the student in with auth()->guard($guard)->login($user);.

Any hints? Or maybe I should provide more info?