PHP laravel object not creating in 5.8 - php

I have a PHP Laravel CRUD application I made where I am using MVC style. I have controllers views and models. My database migration is made and my table in the database is made with php artisan migrate. I am using php 7.3 and laravel 5.8.
On my create view I go to create a single object in my database and my errors are thrown saying nothing in text box (no input) If I comment out the errors then just I click my submit button and nothing happens nothing is entered into my db. I have looked at many different crud examples and I am not sure why my object isn’t being created. Here is what I have
My env is setup correctly I just don’t get the not creating object.
//view create
#section('main')
<section id="section-content" class="text-center">
<div class="container contentdiv rounded">
<div class="row">
<div class="col-md-12">
<div class="pb-2 mt-4 mb-2 border-bottom clearfix">
<h2>Create Contact</h2>
</div>
<div >
<a class="btn btn-success" href="{{route('contacts.index')}}">Back</a>
</div>
</div>
<!-- <div class="col-md-10 mx-auto">
#if($errors->any())
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div><br />
#endif
</div> -->
<div class="row">
<div class="col-md-10 mx-auto mt-3">
<form method="POST" action="{{ route('contacts.store') }}">
#csrf
<div class="form-group row">
<label for="txtfn" class="col-sm-3"><b>First Name:</b></label>
<div class="col-sm-9">
<input type="text" class="form-control" name="txtfn" id="txtfn"/>
</div>
</div>
<div class="form-group row">
<label for="txtln" class="col-sm-3"><b>Last Name:</b></label>
<div class="col-sm-9">
<input type="text" class="form-control" name="txtln" id="txtln"/>
</div>
</div>
<div class="form-group row">
<label for="txtem" class="col-sm-3"><b>Email:</b></label>
<div class="col-sm-9">
<input type="text" class="form-control" name="txtem" id="txtem"/>
</div>
</div>
<button type="submit" class="btn btn-primary">Create Contact</button>
</form>
</div>
</div>
</div>
</section>
//controller
namespace App\Http\Controllers;
use App\Contact;
use Illuminate\Http\Request;
class ContactController extends Controller
{
public function store(Request $request)
{
$request->validate([
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required'
]);
$contact = new Contact([
'first_name' => $request->get('first_name'),
'last_name' => $request->get('last_name'),
'email' => $request->get('email'),
'job_title' => $request->get('job_title'),
'city' => $request->get('city'),
'country' => $request->get('country')
]);
$contact->save();
return redirect('/contacts')->with('success', 'Contact saved!');
}
public function index()
{
$contacts = Contact::all();
return view('contacts.index', compact('contacts'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('contacts.create');
}
// model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Contact extends Model
{
protected $fillable = [
'first_name',
'last_name',
'email',
'city',
'country',
'job_title'
];
}

Your problem is that your input names do not correspond to the keys you are referencing in your store() method:
for example:
<input type="text" class="form-control" name="txtfn" id="txtfn"/>
here, your input name is txtfn, but in your store method, you are looking for first_name.
'first_name' => $request->get('first_name')
so, $request->get('first_name') returns null as if you didn't pass any value.
You must make your input names match with the keys you are using in your store method, either by changing input names, or by changing key names.
example:
<input type="text" class="form-control" name="first_name" />
<input type="text" class="form-control" name="last_name" />
<input type="text" class="form-control" name="email" />

Related

data was not stored in laravel and not getting any errors

I tried to store data but data not store to database, the field in database and form input already match but still can't store data, and there is no actual message error. please help.
this is my controller:
public function store(Request $request)
{
$validatedData = $request->validate([
'kabupaten' => ['required'],
'provinsi' => ['required'],
'unit' => ['required'],
'satuan_kerja' => ['required'],
'nama_area' => ['required'],
'kode_area' => ['required']
]);
Area::create($validatedData);
return redirect('/dashboard/areas')->with('success','Area baru telah ditambahkan!');
}
this is the form input:
<form action="/dashboard/areas" method="POST">
#csrf
<div class="mb-3">
<label for="provinsi" class="form-label">Provinsi</label>
<input type="text" class="form-control" id="provinsi" name="provinsi" value="Jawa Tengah">
</div>
<div class="mb-3">
<label for="kabupaten" class="form-label">Kabupaten</label>
<input type="text" class="form-control" id="kabupaten" name="kabupaten" value="Brebes">
</div>
<div class="mb-3">
<label for="unit" class="form-label">Unit</label>
<input type="text" class="form-control" id="unit" name="unit" value="Pemerintah Kabupaten Brebes">
</div>
<div class="mb-3">
<label for="satuan_kerja" class="form-label">Satuan Kerja</label>
<input type="text" class="form-control" id="satuan_kerja" name="satuan_kerja" value="Pemerintah Desa Dumeling">
</div>
<div class="mb-3">
<label for="nama_area" class="form-label">Nama Area</label>
<input type="text" class="form-control" id="nama_area" name="nama_area">
</div>
<div class="mb-3">
<label for="kode_lokasi" class="form-label">Kode Lokasi</label>
<input type="text" class="form-control" id="kode_lokasi" name="kode_lokasi">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
And this is my area model:
class Area extends Model
{
use HasFactory;
protected $primaryKey = 'id_area';
protected $guarded = [
'id_area'
];
public function aset(){
return $this->hasMany(Aset::class, 'id_area');
}
}
Thank you if there anyone can help me with this problem, I really appreciate it.
So most likely your validation is failing, what you need to do is to display the results of the failed validation error messages, and you can do so in your blade file:
#if ($errors->any())
#foreach ($errors->all() as $error)
<div>{{$error}}</div>
#endforeach
#endif
You may read more on how to display the errors here: https://laravel.com/docs/9.x/validation#quick-displaying-the-validation-errors
You can as well display it per input field or change the class of the input method, etc.. check the #error directive from here: https://laravel.com/docs/9.x/validation#the-at-error-directive

submit form not storing data to database

So i was trying to make a posting form using ckeditor and post it to database, and then try to display it in the same view, but after i submit the form i don't see anything in my database table so clearly it's not even storing to database, is there any mistakes in my controller or view ?
this is my GuestbookController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Guestbook;
class GuestbookController extends Controller
{
public function index()
{
$guestbooks = Guestbook::get();
return view('post.post_textarea',[
'guestbooks' => $guestbooks,
]);
}
public function store(Request $request)
{
Guestbook::create([
'name' => $request->name,
'message' => $request->message
]);
return redirect()->back();
}
}
this is my routes
Route::get('/posting','GuestbookController#index')->name('guestbook');
Route::post('/posting','GuestbookController#store')->name('guestbook.store');
this is my model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Guestbook extends Model
{
protected $fillable = ['name', 'message'];
}
and this is my view
<section class="games-single-page">
<div class="container">
#foreach ($guestbooks as $guestbook)
<div class="card">
<div class="card-body">
<label>mike</label>
<h3>{{ $guestbok->name }}</h3>
{!! $guestbook->message !!}
</div>
</div>
#endforeach
<div class="card">
<div class="card-body">
<form action="/posting" method "POST">
<div class="form-group">
<label style="color: black;" >Title</label>
<input type="text" class="form-control" name="name">
</div>
<div class="form-group">
<label style="color: black;" >Your Input</label>
<br>
<textarea class="form-control" name="message" id="" rows="10"></textarea>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value"Send">
</div>
</form>
</div>
</div>
</div>
</section>
You forgot an equal sign '=' and a csrf field. try the answer.
<form action="/posting" method="POST">
{{csrf_field()}}

Laravel redirect withErrors not working

SO i've trying to make simple laravel validation, but kinda stuck because i cannot return validation error message.
Controller:
//for "GET" method
public function courseAdminCreate()
{
return view('course/adminCreate');
}
//for "POST" method
public function doCourseAdminCreate()
{
$rules = array(
'name' => 'required',
'contact_name' => 'required',
'contact_number' => 'required|numeric',
'account_number' => 'required|numeric',
'address' => 'required',
'latitude' => 'required',
'longitude' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
//get error message
$messages = $validator->messages();
//die($messages); //if i using DIE command, error message appear
return redirect("course/admin/create")->withErrors($validator);
} else {
//Save to DB
}
}
Routes.php:
//other code
Route::get('course/admin/create', ['as' => 'courseAdminCreate', 'uses' => 'CourseController#courseAdminCreate']);
Route::post('course/admin/create', ['as' => 'doCourseAdminCreate', 'uses' => 'CourseController#doCourseAdminCreate']);
//other code
Views:
#extends('layouts.app')
#section('title')
Course
#stop
#section('content')
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
#yield('title') Add
</div>
<div class="panel-body">
{!! Form::open(['url' => '/course/admin/create']) !!}
<div class="row">
<div class="col-lg-12">
<!--START PRINT ERROR MESSAGE -->
#if (count($errors) > 0)
<div class="alert alert-warning alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</div>
#endif
<!-- END PRINT ERROR MESSAGE -->
</div>
<div class="col-lg-6">
<div class="form-group">
<label>Course Name</label>
<input class="form-control" name="name" placeholder="name.." required>
</div>
<div class="form-group">
<label>Contact Name</label>
<input class="form-control" name="contact_name" placeholder="contact.." required>
</div>
<div class="form-group">
<label>Contact Number</label>
<input class="form-control" name="contact_number" placeholder="number.." required>
</div>
<div class="form-group">
<label>Account Number</label>
<input class="form-control" name="account_number" placeholder="account.." required>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label>Address</label>
<textarea class="form-control" name="address" rows="5" placeholder="address.." required></textarea>
</div>
<div class="form-group">
<label>latitude</label>
<input class="form-control" name="latitude" placeholder="latitude.." required>
</div>
<div class="form-group">
<label>longitude</label>
<input class="form-control" name="longitude" placeholder="longitude.." required>
</div>
</div>
<!-- /.col-lg-12 -->
<div class="col-lg-12">
<input type="submit" class="btn btn-default btn-success" value="Save"/>
Cancel
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row (nested) -->
{!! Form::close() !!}
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
#stop
The validation is actually working, so for instance if i input other character beside numeric in "contact_number" it will redirect me back to course/admin/create, the problem are i cannot print the message. $errors in the view always count as empty array if i try to var_dump it.
Hope my information is enough, thank you very much.
The problem is probably in your controller. You can use the $this->validate() method in your Controller method instead of the facade method Validator::make. As you are not using any manually created validators/rules there is no point in using the make method.
If there is any error while validation, Laravel will automatically redirect back to the page the user is coming from - so you do not need any custom redirect logic.
Try this in your controller. You can inject the complete request into your doCourseAdminCreate method and pass it to the $this->validate() method.
//for "GET" method
public function courseAdminCreate()
{
return view('course/adminCreate');
}
//for "POST" method
public function doCourseAdminCreate(Request $request)
{
$rules = array(
'name' => 'required',
'contact_name' => 'required',
'contact_number' => 'required|numeric',
'account_number' => 'required|numeric',
'address' => 'required',
'latitude' => 'required',
'longitude' => 'required'
);
$this->validate($request, $rules);
// Save to db
}
All error messages are autommatically stored into the $errorvariable, that you are already using in your template.

Creating New Forms in Laravel 5 and Submitting Them

I wish to clarify the steps to get a new form properly submitted to my database using Laravel 5.2 and Bootstrap 3.
I have the login/register pages set up properly using Laravel's defaults, and they work fine. I now want to create a user profile page accessible to authenticated users. I am using one row in the database for all of their user info. Some fields were filled in during registration, and now I want them to have access to additional fields (while restricting access to certain registration fields like user name).
In the example code below, there are fields to upload a personal photo, enter a first name, and enter a last name. (None of these were done during registration.)
What I have already done (all code is below):
Create the view profile.blade.php
Create a controller profileController.php
Update routes.php in the controller directory.
A note:
When I try to submit the form as it appears below, I get, Type error: Argument 1 passed to App\Http\Controllers\ProfileController::update() must be of the type array, none given.
What are the next steps required to get this page working properly?
profile.blade.php:
#extends('layouts.app')
#section('content')
<div class="container" style="padding-top: 30px;">
<h1 class="page-header">User Profile</h1>
<div class="row">
<!-- left column -->
<div class="col-md-4 col-sm-6 col-xs-12">
<div class="text-center">
<i class="fa fa-user fa-5x"></i>
<h6>Please upload a photo...</h6>
<input type="file" class="text-center center-block well well-sm">
</div>
</div>
<!-- edit form column -->
<div class="col-md-8 col-sm-6 col-xs-12 personal-info">
<form class="form-horizontal" role="form" method="POST" action="{{ url('/profile') }}">
{!! csrf_field() !!}
<div class="form-group">
<label class="col-lg-3 control-label">First name:</label>
<div class="col-lg-8">
<input class="form-control" value="<?php echo Auth::user()->firstname; ?>" id="firstname" name="firstname" placeholder="First..." type="text">
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Last name:</label>
<div class="col-lg-8">
<input class="form-control" value="<?php echo Auth::user()->lastname; ?>" id="lastname" name="lastname" placeholder="Last..." type="text">
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label"></label>
<div class="col-md-8">
<button type="submit" class="btn btn-primary">
<i class="fa fa-btn fa-user"></i>Submit
</button>
<span></span>
<input class="btn btn-default" value="Cancel" type="reset">
</div>
</div>
</form>
</div>
</div>
</div>
#endsection
profileController.php:
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Http\Request;
class ProfileController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('profile');
}
protected function update(array $data)
{
return User::update([
'firstname' => $data['firstname'],
'lastname' => $data['lastname'],
]);
}
}
And I added the following in the routes middleware:
Route::get('/profile', 'ProfileController#index');
Route::post('/profile', 'ProfileController#update');
It's a protocol mismatch, since you're POSTing your form. You need to change your route to
route::post('/profile', 'ProfileController#index');
Using a validator is a great idea, since it will make sure that your input is exactly what you need it to be, and all required fields are filled out.
Your update function should look something like this:
public function update(Request $request)
{
$first_name = $request->input('firstname');
$last_name = $request->input('lastname');
$id = Auth::user()->id;
$user = \App\User::find($id);
$user->firstname = $first_name;
$user->lastname = $last_name;
$user->save();
return view('profile');
// Sanitize, validate, before you do ANYTHING with update
// Instead of returning the update result, you can instead show another view or forward them to another page.
}

Validation error message not showing and datas not being saved to database

I am trying to first validate the inputs and then add the values to database but neither I am able to see the validation error message nor I am able to insert records to database. I have a table in database named 'news' where I have
this is my boxed.blade.php
<form class="form-horizontal" role="form" method="post" action="/addNews" novalidate>
<div class="form-group">
<label for="inputEmail1" class="col-lg-2 col-sm-2 control-label">Title</label>
<div class="col-lg-10">
<input type="text" name="title" class="form-control" id="inputEmail1" placeholder="News Title" value="{{ Input::old('title') }}">
</div>
</div>
<div class="form-group">
<label for="inputPassword1" class="col-lg-2 col-sm-2 control-label">Description</label>
<div class="col-lg-10">
<textarea name="description" class="form-control" rows="6">{{ Input::old('description') }}</textarea>
</div>
</div>
<div class="form-group">
<label for="inputEmail1" class="col-lg-2 col-sm-2 control-label">Reporter</label>
<div class="col-lg-10">
<input type="text" name="reported_by" class="form-control" id="inputEmail1" placeholder="Reporter Name" value="{{ Input::old('reported_by') }}">
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<div class="checkbox">
<label>
<input type="checkbox" name="status"> Status
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<button type="submit" class="btn btn-danger"><i class="fa fa-comments"></i> Add To List</button>
</div>
</div>
</form>
And routes.php
Route::get('addNews', function()
{
return View::make('pages.boxed');
}
);
Route::post('addNews', function()
{
//processing the form
$rules = array(
'title' => 'required',
'description' => 'required|min:50',
'reported_by' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()){
$message = $validator->message();
return Redirect::to('addNews')->withErrors($validator)->withInput(Input::all());
}
else{
$news = new News;
$news->title = Input::get('title');
$news->description = Input::get('description');
$news->reported_by = Input::get('reported_by');
$news->status = Input::get('status');
$news->save();
return Redirect::to('addNews');
}
}
This is my model News.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class News extends Model
{
protected $fillable = array('title', 'description', 'reported_by', 'status');
}
If you want to see the error, place the following code above your form:
#if (count($errors) > 0)
<div class="alert alert-danger">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
UPDATE 1: Instead of defining the methods in routes.php file, define it in a Controller called NewsController
So, to do this, update your routes.php file to this:
Route::get('/addNews', 'getNewsForm');
Route::post('/addNews', 'postNewsForm');
NewsController.php
/**
* Display the add news form to the user.
*
* #return view
*/
public function getNewsForm()
{
return View::make('pages.boxed');
}
/**
* Store the input in the database after validation
*
* #param $request Illuminate\Http\Facade\Request
*/
public function postNewsForm(Request $request)
{
$this->validate($request, [
'title' => 'required',
'description' => 'required|min:50',
'reported_by' => 'required'
]);
News::create($request->all());
return redirect('/addNews');
}

Categories