Search code examples
phpdatabaselaravelphpmyadminlaravel-5.3

Adding data to DB fails without an error - Laravel


I am having problems adding information to the database. I am not getting any errors, but every time I either try to validate or add information to the table Kids I get redirected to the main page "/" and nothing gets add. I really hope you can help me:

PagesController:

    <?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Kids;
use App\Guardians;
use App\Donations;
use App\Expenses;
use App\Food;
use App\Medicines;
use App\Inventory;
use App\User;
use App\Http\Requests;
use App\Http\Controllers\Controller;


class PagesController extends Controller
{

     public function viewAddPage(){

        return view('add');
    }

    public function storeKids(Request $request)
    {
    $validation= array(
                      'KidID'=>'required',
                      'fname'=>'required',
                      'lName'=>'required',
                      'DateOfBirth'=>'required',
                      'Sex'=>'required',
                      'Age'=>'required',
                      'SchoolName'=>'required',
                      'SchoolGrade'=>'required',
                      'SchoolGroup'=>'required',
                      'BloodType'=>'required',
                      'Allergies'=>'required',
                      'enroll_date'=>'required',
                      'exit_date'=>'required',
                      'created_by'=>'required',
                      'updated_by'=>'required'

                          );
        $v1= Validator::make(Input::all(),$validation);

        if( $v1->fails())
        {
        return Redirect::to('add/list/')->withErrors($v1);
        }
        else
        { $poststudent=$request->all();
          $data = array('KidID'=>$poststudent['KidID'],
                         'fname'=>$poststudent['fname'],
                         'mName'=>    $poststudent['mName'],
                    'lName'=>    $poststudent['lName'], 
                         'DateOfBirth'=>   $poststudent['DateOfBirth'],
                         'Sex'=>   $poststudent['Sex'],
                         'Age'=>   $poststudent['Age'],
                         'SchoolName'=>   $poststudent['SchoolName'],
                         'SchoolGrade'=>   $poststudent['SchoolGrade'],
                         'SchoolGroup'=>   $poststudent['SchoolGroup'],
                         'BloodType'=>   $poststudent['BloodType'],
                         'Allergies'=>   $poststudent['Allergies'],
                         'enroll_date'=>   $poststudent['enroll_date'],
                         'exit_date'=>   $poststudent['exit_date'],
                         'created_by'=>   $poststudent['created_by'],
                         'updated_by'=>   $poststudent['updated_by']

                         );

        $check=0;
        $check=DB::table('kids')->insert($data);

        if($check > 0)
        {
        return Redirect::to('kids/list/');
        }
        else
        {
        return Redirect::to('add/list/');
        }

        }
    }
}

web.php (Routes):

<?php
Route::get('/', function(){
return view('welcome');
});

Route::post('/signin',[
'uses'=>'UserController@postSignIn',
'as'=>'signin'
]);

Route::get('user/logout',function(){
Auth::logout();
return redirect('/');
});

Route::get('/home', [
'uses'=> 'UserController@getDashboard',
'as'=> 'home'
]);

Route::get('kids/list', 'PagesController@viewKidsList');
Route::get('guardians/list', 'PagesController@viewGuardiansList');
Route::get('donations/list', 'PagesController@viewDonationsList');
Route::get('expenses/list', 'PagesController@viewExpensesList');
Route::get('food/list', 'PagesController@viewFoodList');
Route::get('medicines/list', 'PagesController@viewMedicinesList');
Route::get('inventory/list', 'PagesController@viewInventoryList');
Route::get('users/list', 'PagesController@viewUsersList');
Route::get('add/list','PagesController@viewAddPage');
Route::post('/save', array('uses'=>'PagesController@storeKids'));

View (add.blade.php):

@extends('menu')

@section ('add')

<style>

.imagen{
width:400px;
height:auto;
margin-top: 10px;
margin-left: 40px;
margin-bottom: 10px;
}

.user{
position:absolute;
margin-top: -70px;
right:20px;
font-size:14px;
font-family:"courier";
}

</style>

        <form class ="form" action="<?=URL::to('/save')?>" method="POST">
        <h3><center>New kid Information</center></h3>

             <input type="hidden" name="_token" value="{{ csrf_token() }}">
             <div class="form-group">
                <input type="text" name="KidID" id="KidID" placeholder="Kid ID" class = "form-control">

                <br>

                <input class="form-control" type="text" name="fname" id="fname" placeholder="First Name">
                <br>

                <input class="form-control" type="text" name="mName" id="mName" placeholder="Middle Name">
                <br>

                <input class="form-control" type="text" name="lName" id="lName" placeholder="Last Name">
                <br>

                <input class="form-control" type="text" name="DateOfBirth" id="DateOfBirth" placeholder="Date Of Birth">
                <br>

                <input class="form-control" type="text" name="Sex" id="Sex" placeholder="Sex">
                <br>

                <input class="form-control" type="text" name="Age" id="Age" placeholder="Age">
                <br>

                <input class="form-control" type="text" name="SchoolName" id="SchoolName" placeholder="School Name">
                <br>

                <input class="form-control" type="text" name="SchoolGrade" id="SchoolGrade" placeholder="School Grade">
                <br>

                <input class="form-control" type="text" name="SchoolGroup" id="SchoolGroup" placeholder="School Group">
                <br>

                <input class="form-control" type="text" name="BloodType" id="BloodType" placeholder="Blood Type">
                <br>

                <input class="form-control" type="text" name="Allergies" id="Allergies" placeholder="Allergies">
                <br>

                <input class="form-control" type="text" name="enroll_date" id="enroll_date" placeholder="Enroll Date">
                <br>
                 <input class="form-control" type="text" name="exit_date" id="exit_date" placeholder="Enroll Date">
                <br>

                <input class="form-control" type="text" name="created_by" id="created_by" placeholder="Created By">
                <br>
                 <input class="form-control" type="text" name="updated_at" id="updated_at" placeholder="Enroll Date">
                <br>
           <input type="submit" value="Submit" name="save" class="text" />

        </form>
@endsection

Kids Table:

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateKidsTable extends Migration
{

public function up()
{
    Schema::create('kids', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('KidID')->unique();
        $table->string('fname');
        $table->string('mName');
        $table->string('lName');
        $table->date('DateOfBirth');
        $table->string('Sex');
        $table->tinyInteger('Age');
        $table->string('SchoolName');
        $table->tinyInteger('SchoolGrade');
        $table->char('SchoolGroup');
        $table->string('BloodType');
        $table->longText('Allergies');
        $table->date('enroll_date');
        $table->date('exit_date');
        $table->string('created_by');
        $table->timestamps();
    });
}

 public function down()
{
    Schema::drop('kids');
}

}

Kids

namespace App;

use Illuminate\Database\Eloquent\Model;

class Kids extends Model
{

protected $table = 'kids';

}

I have been looking to this problem for days, and I really don't know why it isn't storing nothing, and it keeps sending me to the "/" webpage.


Solution

  • If you add the fillable array to you Kids model

    protected $fillable = ['fName', 'mName','lName'...];
    

    You can then insert the record with eloquent, which is much simpler than the query builder:

    $kids = Kids::create($request->all());
    

    Your validator is quite involved, so move that to a FormRequest:

    php artisan make:request KidsRequest

    The add your validation array to the rules() method in Requests\KidsRequest and make sure you set the authorize() method to return true.

    You can now type hint that in your store method:

    public function storeKids(KidsRequest $request)

    You validation will then be automatically applied.

    So now we have the following method:

    public function storeKids(KidsRequest $request)
    {
            $kids = Kids::create($request->all());
    
            return Redirect::to('add/list/');      
    }
    

    Which I think you'll agree is a lot neater!

    Your code is a little unorthodox, if you stick to naming conventions: index(), show(), store(), edit() etc' you can use resource routes instead which prevents you having to list each route individually, and try to keep your field names on you db format consistent, snake case (e.g. last_name) is preferred in laravel for db fields.

    If you are struggling to understand some of this then there are some excellent tutorials on laracasts