Splashsky
Splashsky

Reputation: 139

Laravel Custom Validation Method

I'm trying to develop a PHP game with Laravel, and so far a user - with enough gold and not part of a guild - can create a guild using a simple form with one text field. The issue is that currently I'm using Laravel's dd() function in order to show that they failed to have the gold or were already in a guild.

As such, I went looking for a way to give it a more baked-in feel by seeing if I could put this behavior into a custom rule/validator, but I'm unsure as to how to go about this. Examples would be preferred... here's my current function.

public function store(Request $request)
{
    $request->validate([
        'name' => 'required|min:4|alpha_dash|unique:guilds'
    ]);

    $char  = Auth::user()->character;
    $cost  = config('game.create-guild-cost');
    $guild = new Guild;

    if($char->gold < $cost) {
        dd('Not enough money');
    }

    if($char->guild != null) {
        dd('You cannot already be in a guild.');
    }

    $guild->name = request('name');
    $guild->leader_id = $char->id;
    $guild->save();

    $char->gold = $char->gold - $cost;
    $char->guild_id = $guild->id;
    $char->save();

    return redirect()->route('guilds.show', ['guild' => $guild]);
}

Upvotes: 0

Views: 669

Answers (1)

Raheel
Raheel

Reputation: 9024

  public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|min:4|alpha_dash|unique:guilds'
        ]);

        if ($validator->fails()) {
            return redirect()
                        ->back() //please double check this but you got the idea
                        ->withErrors($validator)
                        ->withInput();
        }

        // Do your stuff here....
    }

So basically Laravel provides you to put your error messages in session behind the scene and then go to your desired page get the errors from the session and show them nicely in your view files.

Upvotes: 1

Related Questions