< GDB >

Member Since 4 Months Ago

Experience Points
22,300
Total
Experience

2,700 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
148
Lessons
Completed
Best Reply Awards
4
Best Reply
Awards
  • start your 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-in-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 Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist 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.

  • Community Pillar

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

Level 5
22,300 XP
Dec
17
1 month ago
Activity icon

Replied to Display Image Thumbnails Instead Of Full Size Load

Hi,

Don't know if there is a Laravel built in function and maybe I do not completely understand what you mean.

I would just give a css styling and classname how I like/want it and apply that to the view

Dec
09
1 month ago
Activity icon

Awarded Best Reply on Which Path Should I Take To Learn Laravel?

@kevinpigar,

Here's my path so far (started beginning of October - no previous experience except for earlier courses in php)

The Php Practitioner -> Good to go over fundamentals :

https://laracasts.com/series/php-for-beginners

What's new in php 7.1 :

As I'm using this version : https://laracasts.com/series/whats-new-in-php-7-1

U might want to go for new in php 7.4 or the php 8 crash course : https://laracasts.com/series/php8-crash-course

Next OOP principles in PHP, (recommended!) : https://laracasts.com/series/object-oriented-principles-in-php

could also do, php bits (i only did a few here) : https://laracasts.com/series/php-bits

So after these PHP courses, I decided to do the Laravel from Scratch course :

https://laracasts.com/series/laravel-6-from-scratch

Prepare yourself, I found this very hard to follow.

Also maybe before starting the laravel course, check these 2 first, just so you can see differences from lar6/7/8

https://laracasts.com/series/whats-new-in-laravel-8

https://laracasts.com/series/whats-new-in-laravel-7

Lastly, the docs... Personally I think it's a pain to read that and also hard to follow sometimes, but quite sure it's fundamental and I'm guilty of not reading it completely...

Have fun and don't hesitate to recommend me what you found interesting ;-)

Dec
03
1 month ago
Activity icon

Replied to Building A Laravel App With TDD - Course

@plambkin

Yeah, think the course is in Lar. 6... So assume you could create the project in that version (instead of 8)

Imo I would go at it in Lar. 8 and check these two courses first (very short anyways):

https://laracasts.com/series/whats-new-in-laravel-7

https://laracasts.com/series/whats-new-in-laravel-8

This way you are better prepared for the changes in the tutorial and you adapt to lar 8

Activity icon

Replied to Making An Article Model Live

@rffred @automica you guys can still read my comment ๐Ÿ˜ณ

Am sorry I didn't understand what 'making it live' meant, so that's why I deleted it since I was completely off.

What automica said, looks to be the answer you are looking for.

Honestly (I'm a noob) I would not take the road of duplicating the article and messing with an articles_live table and what not. Just simple add a column 'status' to your Articles-table.

In the view where your user creates an article, set a dropdown field where the user can select the status of the article.

Next in your controller where you define what is shown, set a conditional to only show the articles where the status is set as "public"

Activity icon

Replied to Which Path Should I Take To Learn Laravel?

@kevinpigar,

Here's my path so far (started beginning of October - no previous experience except for earlier courses in php)

The Php Practitioner -> Good to go over fundamentals :

https://laracasts.com/series/php-for-beginners

What's new in php 7.1 :

As I'm using this version : https://laracasts.com/series/whats-new-in-php-7-1

U might want to go for new in php 7.4 or the php 8 crash course : https://laracasts.com/series/php8-crash-course

Next OOP principles in PHP, (recommended!) : https://laracasts.com/series/object-oriented-principles-in-php

could also do, php bits (i only did a few here) : https://laracasts.com/series/php-bits

So after these PHP courses, I decided to do the Laravel from Scratch course :

https://laracasts.com/series/laravel-6-from-scratch

Prepare yourself, I found this very hard to follow.

Also maybe before starting the laravel course, check these 2 first, just so you can see differences from lar6/7/8

https://laracasts.com/series/whats-new-in-laravel-8

https://laracasts.com/series/whats-new-in-laravel-7

Lastly, the docs... Personally I think it's a pain to read that and also hard to follow sometimes, but quite sure it's fundamental and I'm guilty of not reading it completely...

Have fun and don't hesitate to recommend me what you found interesting ;-)

Activity icon

Replied to Team Join/invites | Review My Approach

Hi @automica !

Thank you for recommending the series on multitenancy. This might sound a bit uninformed, but in a way am I not already (sort of) applying this?

As in each tenant => team And in my controllers I set conditionals like :

            //Check if user is already part of a team
        if(isset(Auth::user()->team_id)){

and

            //Find team associated with user
        $team = Team::where('id', Auth::User()->team_id)->firstOrFail();

If I understand correctly, by applying multitenancy you base all data around the tenant (id). Therefore users that are part of the tenant(id) can only see data belonging to that tenant.

So by applying conditionals as above I'm doing something similar, with the only exception that I'll need to be able to share data between Teams. F.ex.

User A of Team A can go to /results
User A of Team A can consult results of Team B

or

User A of Team A (f.ex. tenant id 1) can go to /discuss

User A can comment / talk  with User B of Team B (f.ex. tenant id 2) 

-> basically other Users of other Teams (= other tenants)

As I'm using conditionals and specify that when data displayed can only be related to the team the user is part of. I conclude It's better to put these calls in a global scope. (resulting in cleaner code and less chances of me forgetting, making mistake, etc.)

Or did I fail in understanding the purpose / goal of multitenancy?

Dec
02
1 month ago
Activity icon

Replied to Team Join/invites | Review My Approach

@automica

Depending on complexity

Mate, it's already complex enough as it is ๐Ÿ˜‚

BTW this is a prime opportunity to approach this with Test Driven Development

I had to look up what 'Test driven Development' meant? I saw a few courses (fex Build a Laravel App with TDD) but I thought that was some sort of package or something ๐Ÿ˜‡

Maybe you could add a 'team_founder' role. the main thing is who gets permission to dispand the team, it might be that a team is dispanded when everyone leaves.

Yeah, think you are right... Ok, I'll have to think a bit more about it and decide what/how, until I have a solid plan/approach.

At same time I'll mark your last answer as best, it basically says all that needs to be said.

Thanks you btw!

Activity icon

Replied to OnDelete Cascade... Not Working, Some Help?

Hi @santino,

I'm not sure on this but shouldn't this :

$table->integer('user_id');

be :

$table->unsignedBigInteger('user_id);

?

It should refer to the foreign key right? So when you do '$table->integer('user_id')' does that still have the same functionality?

Again, I'm not sure -> just got it that way from the laravel from scratch course...

Another thing :

 Schema::create('tickets', function (Blueprint $table) {
    
        $table->foreign('id')->references('ticket_id')->on('ticket_comments')
           ->onDelete('cascade');
    });

In this case your foreign key, shouldn't that be

Schema::create('tickets', function (Blueprint $table) {
    
        $table->foreign('user_id')->references('id')->on('users')
           ->onDelete('cascade');
    });

This because your foreign key is user_id?

And lastly :

Shouldn't it be something like :

 Schema::create('tickets', function (Blueprint $table) {
        $table->id();
        $table->unsignedBigInteger('user_id');
        $table->text('question');
        $table->boolean('closed')->default( false );
        $table->timestamps();
        $table->foreign('user_id')->references('id')->on('users')
           ->onDelete('cascade');
    });

    Schema::create('ticket_comments', function (Blueprint $table) {
        $table->id();
        $table->unsignedBigInteger('ticket_id');
        $table->text('comment');
        $table->integer('like')->default( 0 );
        $table->boolean('best_answer')->default( false ); // small typo I think
        $table->timestamps();
        $table->foreign('ticket_id')->references('id')->on('tickets')
    ->onDelete('cascade');
    });

Far from sure about this, but this is how I "understood" or at least think I understood ;-)

Activity icon

Replied to Team Join/invites | Review My Approach

Hey @automica !

Thank you for your feedback and kinda confirming that my steps/approach makes sense.

you might want to add a step to invalidate the token to prevent one person approving and then another person disapproving.

Correct, as soon as a member approves/disapproves the token must be deleted to avoid users messing around with it.

I assume your approval link will take the user to login and then see the user they are approving before they approve them?

Euh no, userA (=wants to join) is already registered and logged in. He can edit his account, chat with friends and create a team (or join a team if already created). In the case he needs to join, he'll click 'join-button'.

This click on button, will create a unique token (stored in database table for this) and a notification should be sent to UserB(already member). I'm planning to create a small user-profile-card that can be part of this notification/message, so UserB can immediately see who it is and decide to accept or refuse.

you might also want to add a 'team_leader' role 

That is actually a very good idea, only problem with trying to implement this is the following situation.

Imagine you and me are in a team. You are actually the one who 'founded' the team (or the one that invests time/money/etc) and I'm just a member.

If I'm first to register the team, I would be team_leader. While in reality you would/should be TL.... Hmmm maybe flaw in my approach... Good point though...

Dec
01
1 month ago
Activity icon

Started a new Conversation Team Join/invites | Review My Approach

Hi guys/girls,

Today I'm trying to get my team-invite-join logic finished so I can try to implement this. Excited ๐Ÿ˜

Alright, so after giving it consideration this would be my approach :

    roles 	-> user :
                			- assigned 
                			- not_assigned -> (default)
      		-> team :
                			- red 
                			- blue

method(s) :

            - Get assigned role:

                	User gets role 'assigned', when creating team

                or

                	User gets role 'assigned', when joining team

            - Join team :

                - view with "join-button"
                - click => create token 
                        -> send notification (containing User profile based on user id) to assigned-team member(s)
                        -> approve => assign role 'assigned'
                        -> disapprove => return view (f.ex. not approved) to user

Am I missing something or do you agree that this is a good / correct approach?

Thank you for your feedback / review!

Nov
30
1 month ago
Activity icon

Replied to Close Topic

@pasamsin

You can not delete your own forum questions (as far as I know), keep in mind that when you ask a question a lot of other people might have the same issue or could benefit from reading your question/answer to help solve theirs. So by asking a clear and well formatted question, you'll have higher chances of getting support and thus having more change to actually help others at the same time ;-)

Also when posting a question, best to put a bit more description of what the actual issue is, and when possible, always mark the best answer. So everyone who consults the q&a knows what / how to resolve the issue.

Nov
27
1 month ago
Activity icon

Replied to Store Route Is Shown Instead Of Show, Until Refresh Page

because you should never return a view for a POST method. POST / PUT deals with storing data. Save your data and then redirect to a GET method to display it.

Very clear feedback!! I did not catch / realise that!

After giving it a quick thought, yes I think this :

return redirect('user.profile.show')

Can be :

return redirect()->route('user.profile.show'); //specify route name > in steps

return redirect(route('user.profile.show')); // specify route name > joined

return redirect('/myprofile'); // specify route


I'll have to test my 2 additions though, so for anyone else reading this, look at best answer to be sure! 

Thank you very much @automica !! Not only is my problem solved but I learned (I hope ๐Ÿ˜‡) what the culprit was, how to solve it and a bit of homework to get more acquainted with http redirects ๐Ÿ’ช

The beginning of that idempotency video was spot on ๐Ÿคฃ

Activity icon

Replied to Store Route Is Shown Instead Of Show, Until Refresh Page

@automica

Answering your question :

/myprofile
  • If User is not yet part of a team (default basically), the /myprofile will load with an include 'add_team' that will give possibility to user to add team (if team is already created he'll get a redirect to join the team)

    if you don't have a team, you add one, then save it to:

  • Correct, the User fills in the form (just 2 fields) from the include 'add_team' which hits the TeamController-store-method.

    and when you are finished, you've added a team and then you redirect to

  • Correct, basically same as step one, only show controller detects that a team is linked and will show a form with the 2 fields filled in (+ several other fields that can be edited and updated) -> works fine

    perhaps your redirect isn't working?

Hรจhรจ, I tried with

 return redirect()->route('user.profile.show');

and

 return redirect()->route('user.profile.show', ['team'=>$team]);

Both are working... so..... inevitable question....

How come my redirect wasn't working?

And 1 thing I'm unsure off is

why was a redirect is necessary instead of just return view('...

EDIT : OK so my first question to you 'why it failed'. It's because I'm redirected to a named route right? https://laravel.com/docs/8.x/redirects#redirecting-named-routes

If I wanted to use like so :

return redirect('user.profile.show')

I would have to specify that in my web.php routes, right?

Please tell me I'm right ๐Ÿ˜ƒ

Activity icon

Replied to Store Route Is Shown Instead Of Show, Until Refresh Page

@automica

This is my UserController::show

public function show(){
//Check if User has Team
        if(!empty(Auth::User()->team_id)){
            $team = Team::where('id', Auth::User()->team_id)->firstOrFail();
            return view('user.profile.show', ['team'=>$team]);
        } //Else
        return view ('user.profile.setup');
    }

Regarding :

surely you are passing $team into the blade from the controller?

Yeah, only if the user does have a team though

Activity icon

Replied to Store Route Is Shown Instead Of Show, Until Refresh Page

@automica

hmm, I tried what you suggested as in :

return redirect('user.profile.show')

This results in the error :

Undefined variable: team

It points to f.ex. the following line

<img    src="{{ asset($team->avatar) }}"

This is from an include (teamProfile) in the show-view. (btw it does do the store logic and row is added to database)

This is also why I added the 'team' arguments to my route. So.... if I try to add that logic to your suggestion, I get the error :

Argument 2 passed to Symfony\Component\HttpFoundation\RedirectResponse::__construct() must be of the type int, array given, called in 

In this case the store-method also function but the error pops up, if i refresh

very similar as original issue 

"The page that you're looking for used information that you entered. Returning to that page might cause any action that you took to be repeated. Do you want to continue?"

I continue -> correct view is shown (so almost identical as original issue, just now an error is thrown)

Activity icon

Replied to Store Route Is Shown Instead Of Show, Until Refresh Page

hey @automica ,

Yes, this is the complete store method :

// Store
    public function store(Request $request){
        
        //Check if user is already part of a team
        if(isset(Auth::user()->team_id)){
            //Return back with error
            return Redirect::back()->with('error', 'user already belongs to a team'); 
        }

        //Fetch web URL
        $teamurl = $request->input('teamurl'); 
            //Tidy up
            if(!preg_match("~^(?:f|ht)tps?://~i", $teamurl)) {
                $teamurl = "https://" . $teamurl;
            }
                //Merge for validation
                $request->merge(['teamurl' => $teamurl]);
        
        //Check if input is unique - else redirect
        if(Team::where('teamurl', '=', $request->input('teamurl))->exists()){
            // Exists -> Redirect to ask to join
            return view('team.join');
        }

        //Validate input
        request()->validate([
            'teamurl' => ['required', 'string', 'active_url', 'unique:teams'],
            'name' => ['required', 'string', 'unique:teams'],
        ]);
    
        //Process
        $team = new Team();
        $team->teamurl = $request->input('teamurl');
        $team->name = $request->input('name');
        
        //Save 
        $team->save();
        
        //Link Team to User
        Auth::user()->update(['team_id' => $team->id]);

        //Return view
        return view('user.profile.show', ['team'=>$team]);    
    }

Regarding the route, yes my route :

 Route::get('/myprofile', [UserController::class, 'show'])->name('user.profile.show');

Does not contain any team argument, as it was not necessary. But as I got further in my 'project' I needed to give the argument with the route in order for it to function correctly (otherwise $team is undefined error)

Activity icon

Started a new Conversation Store Route Is Shown Instead Of Show, Until Refresh Page

Hi,

I'm a bit confused trying to solve a small issue.

So I have my store-method in controller that at the end of the necessary actions redirects to the show view like so :

// Return view
        return redirect()->route('user.profile.show', ['team'=>$team]);

The view I ended up with looked not as expected, until I refreshed the page. So I renamed my routes to find out what was being shown and it appears to be my store-route

So this route :

// Team store
            Route::post('/teamstore', [TeamController::class, 'store'])->name('team.store');

instead of :

// Profile show
            Route::get('/myprofile', [UserController::class, 'show'])->name('user.profile.show');

So what happens is it shows kinda the right page, but some data is missing. (url = /teamstore) When I refresh the page, I get this :

The page that you're looking for used information that you entered. Returning to that page might cause any action that you took to be repeated. Do you want to continue?

Doing this results in the right view with correct data.

Can anyone guide me in the right direction to what I've to look for? How this type of 'error' can occur?

As always help is appreciated and thank you in advance!

Nov
26
1 month ago
Activity icon

Replied to SQLSTATE[22001] : String Data Too Long

Thank you for clarifying! Nice to know!

Activity icon

Replied to SQLSTATE[22001] : String Data Too Long

@snapey Thank you for your input!

I've updated the best answer to yours, as it :

  • shows I was wrong with assumption string length is max. 255 (that was just default) (so no need to change type)
  • You gave a guidance in max length.

nb: you are very convincing when saying 'never more than 2048 chars'

Specific reason for this? Or just exp?

Thanks!!

Activity icon

Replied to SQLSTATE[22001] : String Data Too Long

@nakov Thanks for that link, so indeed just a matter of changing the type instead of string to text or medium/longtext...

Taking this into account, I saw they said :

TEXT: 65,535 characters - 64 KB 
MEDIUMTEXT: 16,777,215 - 16 MB 
LONGTEXT: 4,294,967,295 characters - 4 GB

They also say not to put a limit as a condition.

But for you as an experienced dev. do you agree with that statement? Surely text should be sufficient right, a url with 65k characters, does that even exist? Is there a disadvantage of not setting a max input length?

Activity icon

Started a new Conversation SQLSTATE[22001] : String Data Too Long

Good afternoon all,

I get the following error :

SQLSTATE[22001]: String data, right truncated: 1406 Data too long for column 'googmaps' 

I added a column to my database table where the user can insert a 'Google maps'-link. As you probably can imagine, these links tend to be long :-/

This is my migration scheme for this field:

 $table->string('googmaps')->nullable();

This is my validation in controller :

'googmaps' => ['nullable', 'active_url'],

I did not put a max of characters as a condition, but assume this error is thrown as a string has a max. length of 255 characters. (not sure if this is 100%, just how I concluded)

Is this just a matter of changing the type in my migration scheme to f.ex. text or longtext?
Or is this not really correct?

Thank you for your advice!

Nov
25
1 month ago
Activity icon

Replied to Laracasts 50% Off

@tray2 hey! I hope you were not joking ๐Ÿฅบ, as I bought the lifer on the spot.

How will I be refunded though?

Sep 20, 2020 $99.00 Paid View Nov 25, 2020 $175.00 Paid View

Nov
24
2 months ago
Activity icon

Replied to Store Function Failing

@automica Woaw, not sure if I should laugh or cry (prob this)... in my process of cutting and pasting I did indeed not provide a form end tag. Everything seems to work now ๐Ÿ˜ต๐Ÿ”ซ

Geez, now I have to update "best answer"

Terribly sorry, but very grateful for your help!

Activity icon

Replied to Store Function Failing

@automica my UserController calls a blade file depending if the User has or hasn't gotten a team yet.

UserController :

    public function show(){
        if(!empty(Auth::User()->team_id)){
            $team = Team::where('id', Auth::User()->team_id)->firstOrFail();
            return view('user.profile.show', ['team'=>$team]);
        }
        return view ('user.profile.setup');
    }

f.ex. user has no team yet so -> user.profile.setup is loaded

this is my setup.blade:

            <div class="card">
                <div class="card-body">
                    <ul class="nav nav-pills bg-nav-pills nav-justified mb-3">
                        <li class="nav-item">
                            <a href="#profile" data-toggle="tab" aria-expanded="false" class="nav-link rounded-0 active">
                                My Profile
                            </a>
                        </li>
                        <li class="nav-item">
                            <a href="#team" data-toggle="tab" aria-expanded="true" class="nav-link rounded-0">
                                My Team
                            </a>
                        </li>
                        <li class="nav-item">
                            <a href="#settings" data-toggle="tab" aria-expanded="false" class="nav-link rounded-0">
                                Social
                            </a>
                        </li>
                    </ul>
                    <!-- User Profile tab -->
                    <div class="tab-content">
                        @include('user.includes/userProfileTab')
                        @include('team.includes/addteam')
                        @include('user.includes/settings')
                    </div> <!-- end tab-content -->
                </div> <!-- end card body -->
            </div> <!-- end card -->

So f.ex. userProfileTab

<div class="tab-pane show active" id="profile">                    
<form>
    <h5 class="mb-3 text-uppercase bg-light p-2"><i class="mdi mdi-account-circle mr-1"></i> Personal 				Info</h5>
    <div class="row">
        <div class="col-md-6">
            <div class="form-group">
                <label  for="firstname">First Name</label>
                <input  readonly 
                        type="text" 

And f.ex. Addteam is like :

<div class="tab-pane" id="team">
    <h5 class="mb-3 text-uppercase bg-light p-2">team Info</h5>
        <div class="text-center w-75 m-auto">
            <h4 class="text-dark-50 text-center mt-0 font-weight-bold">Add your team!</h4>
            <p class="text-muted mb-4">First we'll verify if the team has been registered already. Enter the team name below:</p>
        </div>    
    
    <form   method="POST"
            action="{{route ('team.store') }}">
            @csrf
            
            <div class="row">

                <div class="col-md-6">
                    <div class="form-group">

If in this case, I submit a "teamname" in the page reloads (/myprofile) showing the first tab (myprofile) and the a token + filledinfield is set behind the url (so /myprofile?_token etc)

But even on the other situation where a team is set yet,

It shows the team nicely, but when I will want to update records of this, I'll get the same issue (reload the page nothing happens though). But in this last case, I can update the profile records fine. In the first case -> no team connected yet -> I can't edit my profile either.

Activity icon

Replied to Store Function Failing

@automica well this is awkward , I fixed my 'layout-issue' turns out it did not fix the failed store method. ๐Ÿ˜‡

My moment of enlightment was short lived...

your remark is 100% valid, I do not have a create route for team ! 

But not really sure how to implement as the /myprofile is loaded by the UserController and if I change from one tab (userprofile) to the other (teamprofile), my route does not change.

So could it be that I just need to hit the create team route (yet to be made) if the tab (teamprofile) is hit?

If so where do it do that though?

I do have this :

<div class="card">
                <div class="card-body">
                    <ul class="nav nav-pills bg-nav-pills nav-justified mb-3">
                        <li class="nav-item">
                            <a href="#profile" data-toggle="tab" aria-expanded="false" class="nav-link rounded-0 active">
                                My Profile
                            </a>
                        </li>
                        <li class="nav-item">
                            <a href="#team" data-toggle="tab" aria-expanded="true" class="nav-link rounded-0">
                                My Team
                            </a>
                        </li>

Should I link to the teamController where it is now #team and to the UserController where is #profile?

Otherwise, I do not really see where I can do that...

Activity icon

Replied to Store Function Failing

@munazzil yeah, I have it like that see above.

But thanks for the suggestion!

Activity icon

Replied to Store Function Failing

@ma unfortunately I have it correct, see

        <form   method="POST"
            action="{{route ('team.store') }}">
            @csrf
            
            <div class="row">

                <div class="col-md-6">
Activity icon

Replied to Store Function Failing

@automica

sorry for that here's my routes :

// User
    use App\Http\Controllers\UserController;
    // Group
        Route::group(['middleware' => 'auth'], function(){
            // Profile show
                Route::get('/myprofile', [UserController::class, 'show'])->name('user.profile.show');
            // Profile edit
                Route::get('/myprofile.edit', [UserController::class, 'edit'])->name('user.profile.edit');
            // Profile Update
                Route::put('/myprofile', [UserController::class, 'update'])->name('user.profile.update');
        });
    
    // Team
        use App\Http\Controllers\TeamController;
        // Group
            Route::group(['middleware' => 'auth'], function(){
                // Team index
                    Route::get('/team', [TeamController::class, 'index'])->name('team.index');
                // Team join
                    Route::get('/jointheteam', [TeamController::class, 'join'])->name('team.join');
                // Team store
                    Route::post('/myprofile', [TeamController::class, 'store'])->name('team.store');
                // Team add/create
                    Route::get('/team/add', [TeamController::class, 'create'])->name('team.create');
                // Team edit
                    Route::get('/team/edit', [TeamController::class, 'edit'])->name('team.edit');
                // Team update
                    Route::put('/team', [TeamController::class, 'update']);
        });

(geez, I still can't get the format perfect)

also check you have set form method='POST' if all its doing on submit is reloading the page.

Yes my form is set as post see here :

    <form   method="POST"
        action="{{route ('team.store') }}">
        @csrf
        
        <div class="row">

            <div class="col-md-6">
Activity icon

Replied to Store Function Failing

@munazzil Thanks for your advice! But I'm quite sure that changing the name is not necessary here...

Activity icon

Replied to Store Function Failing

@automica

how is the method failing

It is failing to :

  • store the data in the database
  • instead it reloads the /profile page and adds the token and fields from the form in the url

I cleared the routes after setting it up, and this is my route:list

(see post below as this failed to format well)

I'd like to confirm where my controller fails, but honestly i'm under the impression that it doesn't even hit the controller and just reloads the page ๐Ÿคจ

Activity icon

Replied to Laracasts 50% Off

@neilstee Just my luck again, took a yearly sub at 99$ approx a month ago. Now the forever plan is 175$ ๐Ÿ˜… ! F !

Seeing you are a 2 year member, I would assume it's a no brainer? So instead of

What makes you decide?

I would ask you

What makes you doubt?
Activity icon

Started a new Conversation Store Function Failing

This is probably something basic that I'm forgetting to take into account.

I have a UserController that works fine to show/edit/store/update the userprofile

I have a TeamController that works fine to show/edit/store/update the teamprofile

When keeping this separate it works fine. But f.ex. this is my route to show the user profile

Route::get('/myprofile', [UserController::class, 'show'])->name('user.profile.show');

This view, has a userprofile tab and also a tab for the team profile.

if the user has not yet added (or joined) a team, this tab will display a form to do this.

Here's where it's going wrong :-(

The form route is

action="{{route ('team.store') }}">

This is my route

     Route::post('/team', [TeamController::class, 'store'])->name('team.store');

Now when I click submit, this route gets hit:

Route::get('/myprofile', [UserController::class, 'show'])->name('user.profile.show');

And in the URL the filled in data from the store form is displayed..

I thought I had to change the route like this:

Instead of :

Route::post('/team', [TeamController::class, 'store'])->name('team.store');

This:

Route::post('/myprofile', [TeamController::class, 'store'])->name('team.store');

But same result, just reload of /myprofile followed by the token and data from form

What am i forgetting to take into account?

Nov
23
2 months ago
Activity icon

Replied to Retrieve File From Storage

@ruslanjohnbell

I'm sorry mate, but you make it too fancy for me using additional parameters and not sure what the attribute function does. ๐Ÿ˜•

Surely a more experienced member here will be able to give you a solid feedback.	

I would also recommend you to post :

  • How you call / fetch the stored attachment

  • what error message you receive

Activity icon

Awarded Best Reply on FirstOrFail Method. Bad Approach Or Just Need Other Conditional?

Hi @mirlan bekturov,

In addition to the comment of Sergiu, your remark solves this. However, in my situation the condition needs to be met on the controller.

I've updated my UserController like this :

public function show(){
if(!empty(Auth::User()->team_id)){
    $team = Team::where('id', Auth::User()->team_id)->firstOrFail();
           return view ('user.profile.show', ['team'=>$team]);
	}
	return view('user.profile.setup');
}

So first in my show-method I need to check if the team_id field is empty or not (could have used isset also) When this field is not empty (a team has been linked) the first route will be hit.

If the field is empty the second route will be hit, which is similar, except instead of returning a view that contains $team fields, it will return a view only consisting of $user-fields and under the Team tab an option to add a team.

Your suggestion did help me realise a simple solution, still not 100% this is the best approach though.

Activity icon

Replied to Retrieve File From Storage

hey @ruslanjohnbell,

I'm no expert, but recently learned a few basics regarding this subject.

Can you upload your store function from the controller?

the default storage disk, will be set to the local one. By using the storage:link command you'll get symlinked to the public disk.

please show us how you stored the file/image

Activity icon

Replied to FirstOrFail Method. Bad Approach Or Just Need Other Conditional?

Hi @mirlan bekturov,

In addition to the comment of Sergiu, your remark solves this. However, in my situation the condition needs to be met on the controller.

I've updated my UserController like this :

public function show(){
if(!empty(Auth::User()->team_id)){
    $team = Team::where('id', Auth::User()->team_id)->firstOrFail();
           return view ('user.profile.show', ['team'=>$team]);
	}
	return view('user.profile.setup');
}

So first in my show-method I need to check if the team_id field is empty or not (could have used isset also) When this field is not empty (a team has been linked) the first route will be hit.

If the field is empty the second route will be hit, which is similar, except instead of returning a view that contains $team fields, it will return a view only consisting of $user-fields and under the Team tab an option to add a team.

Your suggestion did help me realise a simple solution, still not 100% this is the best approach though.

Activity icon

Replied to FirstOrFail Method. Bad Approach Or Just Need Other Conditional?

Hi @sergiu17,

Thanks for your advice, however, null is not returned but a QueryException :

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'teams.team_id' in 'where clause' (SQL: select * from `teams` where `teams`.`team_id` = 4 and `teams`.`team_id` is not null limit 1)	

In users table, user with id 4 has a team_id of null

in teams teble there is no record of a team with id4

I assume that is because team_id can be null but team table can't have a record with no id

Ok, so that error is avoided by updating your suggestion to :

public function show()
{
	return view ('user.profile.show', ['team' => Auth::user()->team_id]);
}

However, in this case it views the "team"-data as a property of a non-object.

I had this earlier, hence why I defined the $team as :

$team = Team::where('id', Auth::User()->team_id)->firstOrFail();
Activity icon

Started a new Conversation FirstOrFail Method. Bad Approach Or Just Need Other Conditional?

Good afternoon all,

Quick info about situation :

User registers -> User logs in

The next step that I want to do is get the user to finish his profile so 

User hits /profile

This page contains a tab : User profile and a tab Team profile

All worked until the point I added the Team profile.

Controller looks like this :

 public function show(){
        $team = Team::where('id', Auth::User()->team_id)->firstOrFail();
       
        return view ('user.profile.show', ['team'=>$team]);
    }

As you (probably) can imagine (but I ofc didn't think of that) the User did not create or joined a team yet. So the 'firstOrFail' method does it's thing and returns a 404.

So my question is :

Is my approach wrong by using the firstOrFail() method ?  

Or, I tried the following conditional (but failed):

public function show(){
	try{
        $team = Team::where('id', Auth::User()->team_id)->firstOrFail();
       	// Team exists
        	return view ('user.profile.show', ['team'=>$team]);
    } catch (ErrorException $e) {
	// Team does not exist 
	return view('user.profile.show');
}

It still gets stuck on the fail...

Than I tried this conditional :

public function show(){
        $team = Team::where('id', Auth::User()->team_id)->get();
            //Found
            return view ('user.profile.show', ['team'=>$team]);    
        if($team->isEmpty()){
                return view ('user.profile.show');
            }
    }

This conditionals throws up = does not exist on this collection instance

So before I try to dig into that issue, is this last approach the best I can do in this case?

Nov
20
2 months ago
Activity icon

Replied to Class 'App\Http\Controllers\...' Not Found, When Trying To Access From Different Controller

@sinnbeck ๐Ÿ˜ณ I should have known that! Sorry and thank you for the swift feedback!

Activity icon

Started a new Conversation Class 'App\Http\Controllers\...' Not Found, When Trying To Access From Different Controller

I'm getting the following error :

Class 'App\Http\Controllers\Team' not found

Everything works fine if I :

Have route :

// Team index
            Route::get('/myteam', [TeamController::class, 'index'])->name('team.index');

Have TeamController - index function :

 public function index(){
        
        //Find team associated with user
        	$team = Team::where('id', Auth::User()->team_id)->firstOrFail();
        
        //Return view
        	return view('team.index', ['team'=>$team]);
    }

Index blade :

{{ $team->teamname }}

But, here's what I'm trying to do :

Have this route :

// Profile show
            Route::get('/myprofile', [UserController::class, 'show'])->name('profile.show'); 

Have UserController - show function :

(This is where I'm stuck)

public function show(){
        $team = Team::where('id', Auth::User()->team_id)->firstOrFail();
        dd($team);



Well I can't find TeamController if I'm using UserController ๐Ÿ˜…, but how do I otherwise get this done?

The profile is loaded by the UserController, but there is a tab-pane that shows in 1 tab the User profile data (that can be edited) and in another tab the Team data.

Or is the only solution to reload the route using TeamController when the team-tab is clicked?
Nov
19
2 months ago
Activity icon

Replied to HasMany < - > HasOne Relationship Fail ->What Did I Miss

it doesn't prevent them switching or leaving a team.

Ah, didn't realise this ๐Ÿ˜

Thnx!!!

Activity icon

Replied to HasMany < - > HasOne Relationship Fail ->What Did I Miss

@automica Sorry to bother you again, but my user can still make multiple teams.

In the teamtable the new team is inserted in another row. In the usertable the team_id gets updated.

In a way this makes sense as team_id gets updated in controller:

Auth::user()->update(['team_id' => $team->id]);

But I thought this would not be the case as :

// User.php

public function team(){
	return $this->hasOne(Team::class);
}

and

// Team.php

public function users(){
	return $this->hasMany(User::class);
}

Does that mean I have to check first (in teamcontroller) if a user already has a team_id before doing anything else (validation, process data, save)?

Nov
18
2 months ago
Activity icon

Replied to HasMany < - > HasOne Relationship Fail ->What Did I Miss

@automica aah I did like this

Auth::user()->update(['team_id', $team->id]);

Hence, why nothing happened ๐Ÿ˜‚

I marked your previous answer as 'Best' because it points out the mistake.

How do you know where to search in the docs? I mean I searched through the docs to help me, but never did I thought of reading through / searching for the #mass Updates part. Mostly because I skipped "Getting Started" and went straight to relationships.

Is there a trick? Or I just have to read through all of it ๐Ÿ˜ฌ

Activity icon

Replied to HasMany < - > HasOne Relationship Fail ->What Did I Miss

"you've got this logic the wrong way round."

I see... Because the team hasMany and a user hasOne? Hence the link should be on User-table, right?

// Attach team to user
Auth::user()->update('team_id', $team->id);

How does this work though? My team field gets created, but my User table does not get updated with team_id. I assume this is because nothing really happens with this command?

This flow does assume that the person creating the team will always want to assign themselves to that new team.

Exactly, or create (if doesnt exists) or join (if exists).

Again, @automica thank you very much for all the insights and help!

Activity icon

Replied to HasMany < - > HasOne Relationship Fail ->What Did I Miss

@automica

Hmm, interesting that the ideal flow would be from a user standpoint instead of team.

I did like this :

  1. User accesses /team/add

  2. User submits data to /team/store

  3. store method :

    // Store public function store(Request $request){

         //Check if input is unique - else redirect
         if(Team::where('cred1', '=', $request->input('cred1'))->exists()){
             // Exists -> Redirect to ask to join
             return view('team.join');
         }
    
         //Validate input
         request()->validate([
             'cred1' => ['required', 'string', 'unique:teams'],
             'cred2' => ['required', 'string', 'unique:teams'],
         ]);
    
         //Process
         $team = new Team();
         $team->cred1 = $request->input('cred1');
         $team->cred2 = $request->input('cred2');
    
         //Link user
         $team->user_id = Auth::User()->id
    
         //Save 
         $team->save();
    

Result :

  1. The 'check if input is unique, else redirect' is doing what expected.
  2. Teams Table is being inserted with data and user_id field
  3. However User Table does not show any relation to Teams Table (not entirely sure that is necessary)
  4. User can just create another team != what I want

So am I failing because my flow is incorrect? Checked several vids, articles, etc... Looks like my initial understanding of the relationship setup is okay. Now seeing how you would 'hit every step' I'm starting to doubt my method.

Activity icon

Replied to HasMany < - > HasOne Relationship Fail ->What Did I Miss

@automica I'm not following entirely...

set the team_id field as nullable so you can save your user without it.

I've set the team_id field in the user migration table to nullable. (Well mostly because my user is created before a team...)

Then when you edit your user, you can assign a team_id as normal. 

This is where I lose you, so clearly I'm missing something here. What is wrong with:

- user has possibility to add team
- user has to give 2 unique credentials (which will verify if team exist or needs to be created -> decided during validation)
- If team needs to be created, the team controller processes the input, creates a new team (I add the 2 credentials + link the user and save).

This results in a team-table-row that contains all info.

However my user, also has a team_id field, which I need to populate (otherwise user can create several teams).

So I assume that this also needs to be done during the 'store'-method in team-controller (upon creating the team)?

edit: just found this (https://laracasts.com/series/eloquent-relationships) might need to watch that first :)

Nov
17
2 months ago
Activity icon

Replied to HasMany < - > HasOne Relationship Fail ->What Did I Miss

@automica

So I was correct? ๐Ÿ˜ฎ (well almost correct, 'details')

In the meantime I kept tinkering and already added the team_id to my users table. (being stubborn and wanting to avoid the third table, which turns out I don't need anyways)

However if I want to link the team i get an error.

This is how i link user :

$team->user_id = Auth::User()->id;

This is how i link team (and fail at it) :

$user->team_id = $team->id;

error:

Creating default object from empty value

Makes sense, as the $team is not saved yet...

But when or where do i link them? if I do it after saving the newly created $team, the error stays the same..

Activity icon

Replied to HasMany < - > HasOne Relationship Fail ->What Did I Miss

Hi @orest Thnx for helping!

Hmm, I think I messed up by trying to avoid having a Team_User table. I did not set a "user_id" parameter, but inserted the user_id in the controller process. So my table "Team" had a user_id, but the table "User" did not have a team_id.

But upon reflection, this didn't make sense, as many users could join the same team, my team table would have several rows with same data, different user_id, etc...

So having a third table for the relationship, makes sense... now...