stefan de boer
stefan de boer

Reputation: 405

Inserting data in database with Laravel

I'm making a web app with a form that inserts data into a database. I'm making this web app with Laravel. Now I made the form and the code for the insertion but it is not working, it is giving a not found error. Hopefully, someone can give me some advice on how to fix this problem.

This is my View:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Spelers Toevoegen</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="main.css" />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="main.js"></script>
</head>
<body>
 <form id="form" action="/add" method="post">

 @csrf

   <div class="form-group">
     <h1>Speler toevoegen</h1>
     <label>Naam:<input name="naam" type="text" value="" class="form-control"></label><br>
     <label>Aantal:<input name="aantal" type="text" value="" class="form-control"></label><br>
            <label>Positie:<input name="positie" type="text" value="" class="form-control"></label><br>
            <label>club:<input name="club" type="text" value="{{$naam}}" class="form-control"></label><br>
            <button type="submit" class="btn btn-primary"><a id="btn_link">Voeg spelers toe</a></button>
        </div>
 </form>

This is my controller function:

public function Add(Request $request)
{
    $speler_naam = $request->input('naam');
    $aantal = $request->input('aantal');
    $positie = $request->input('positie');
    $club = $request->input('club');

    $data = array('speler_naam'=>$speler_naam, "doelpunten"=>$aantal, "positie"=>$positie, "club_naam"=>$club);

    SpelerSelectie::insert($data);
}

This is my route:

Route::post('/add', 'VoetbalController@Add');

Upvotes: 0

Views: 53

Answers (1)

utdev
utdev

Reputation: 4112

First you should name your method in lower case not Uppercase

So your route should look like this:

Route::post('/add', 'VoetbalController@add');

And you save it like this to your database:

public function add(Request $request) {
    $data = SpelerSelectie::create($request->all());

    if($data) {
        return redirect()->route('add.index')->with('message', 'Success.');
    }

    return redirect()->route('add.index')->with('message', 'error.');
}

Further you should import the model in your Controller at the Top of the file:

use App\SpelerSelectie;

Further you need to add the field which you are inserting / updating to your model in your model's fillable array:

protected $fillable = ['field1']; // you need to add your field name (tablenames)

I assume that you created a proper migration, if not you have to create a proper migration first.

Upvotes: 1

Related Questions