Laravel Form Input not required - php

I'm trying to make a simple contact form for my users and IF they have an order id to put it in a field. Or else i put it by default as "0" (lets say that they have a question)
So this is my code
Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\ContactUS;
class ContactUSController extends Controller
{
public function contactUS()
{
return view('contactUS');
}
public function contactUSPost(Request $request)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required|email',
'message' => 'required'
]);
ContactUS::create($request->all());
return back()->with('success', 'Thanks for contacting us! We will get back shortly.');
}
}
View
<div class="container">
<h1>Contact US Form</h1>
#if(Session::has('success'))
<div class="alert alert-success">
{{ Session::get('success') }}
</div>
#endif
{!! Form::open(['route'=>'contactus.store']) !!}
<div class="form-group {{ $errors->has('name') ? 'has-error' : '' }}">
{!! Form::label('Name:') !!}
{!! Form::text('name', old('name'), ['class'=>'form-control', 'placeholder'=>'Enter Name']) !!}
<span class="text-danger">{{ $errors->first('name') }}</span>
</div>
<div class="form-group {{ $errors->has('email') ? 'has-error' : '' }}">
{!! Form::label('Email:') !!}
{!! Form::text('email', old('email'), ['class'=>'form-control', 'placeholder'=>'Enter Email']) !!}
<span class="text-danger">{{ $errors->first('email') }}</span>
</div>
<div class="form-group">
{!! Form::label('Order ID:') !!}
{!! Form::number('orderId', old('orderId'), ['class'=>'form-control no-spinners', 'placeholder'=>'Do you have and order id?']) !!}
</div>
<div class="form-group {{ $errors->has('message') ? 'has-error' : '' }}">
{!! Form::label('Message:') !!}
{!! Form::textarea('message', old('message'), ['class'=>'form-control', 'placeholder'=>'Enter Message']) !!}
<span class="text-danger">{{ $errors->first('message') }}</span>
</div>
<div class="form-group">
<button class="btn btn-success">Contact US!</button>
</div>
{!! Form::close() !!}
Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class ContactUS extends Model
{
public $table = 'contact_us';
public $fillable = ['name','email','message'];
}
Migration
class CreateContactUsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('contact_us', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email');
$table->text('message');
$table->integer('orderId')->default('0');
$table->boolean('solved')->default(false);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('contact_us');
}
}
So the issue is that when I don't put any value on field OrderId it takes the default value 0
But if i put any number value 1 or 2 etc it still saves 0 at my database.
Any idea why is this reaction made?

Allow mass assignment for orderId field in your model,
public $fillable = ['name','email','message','orderId'];

As Deepak stated in the comments, you can check the value for null in your controller:
$data=$request->all();
$data['orderId'] = $data['orderId'] == '' ? 'No Order ID Entered' : $data['orderId'];
Alternatively, pass something falsy
$data=$request->all();
$data['orderId'] = $data['orderId'] == '' ? 0 : $data['orderId'];

Related

SQLSTATE[HY000]: General error: 1364 Field 'author_id' doesn't have a default value

I'm actually new to Laravel Framework. Have been trying to post to the Mysql Database, I was getting an error on my Author_id.
SQLSTATE[HY000]: General error: 1364 Field 'author_id' doesn't have a default value.
Have checked everywhere but all efforts were proven abortive
Here is the Migration
public function up()
{
Schema::create('posts', function (Blueprint $table) {
//$table->engine = “InnoDB”;
$table->increments('id');
$table->integer('author_id')->unsigned();
$table->foreign('author_id')->unique()->references('id')->on('users')->onDelete('restrict');
$table->string('title');
$table->string('slug')->unique();
$table->text('excerpt');
$table->text('body');
$table->unsignedInteger('user_id');
$table->string('image')->nullable();
$table->timestamps();
});
}
Here is my create.blade.php:
<section class="content">
<div class="row">
<div class="col-xs-12">
<div class="box">
<div class="box-body">
{!! Form::model($post, [
'method' => 'POST',
'url' => 'backend/blog'
]) !!}
{{-- <form method="POST" action="{{ url('blog/store') }}" enctype="multipart/form-data">
#csrf --}}
<div class="form-group {{ $errors->has('title') ? 'has-error' : '' }}">
{!! Form::label('title') !!}
{!! Form::text('title', null, ['class' => 'form-control']) !!}
#if($errors->has('title'))
<span class="help-block">{{ $errors->first('title') }} </span>
#endif
</div>
<div class="form-group {{ $errors->has('slug') ? 'has-error' : '' }}">
{!! Form::label('slug') !!}
{!! Form::text('slug', null, ['class' => 'form-control'])!!}
#if($errors->has('slug'))
<span class="help-block">{{ $errors->first('slug') }} </span>
#endif
</div>
<div class="form-group {{ $errors->has('excerpt') ? 'has-error' : '' }}">
{!! Form::label('excerpt') !!}
{!! Form::textarea('excerpt', null, ['class' => 'form-control'])!!}
#if($errors->has('excerpt'))
<span class="help-block">{{ $errors->first('excerpt') }} </span>
#endif
</div>
<div class="form-group {{ $errors->has('body') ? 'has-error' : '' }}">
{!! Form::label('body') !!}
{!! Form::textarea('body', null, ['class' => 'form-control'])!!}
#if($errors->has('body'))
<span class="help-block">{{ $errors->first('body') }} </span>
#endif
</div>
<div class="form-group {{ $errors->has('published_at') ? 'has-error' : '' }}">
{!! Form::label('published_at', 'Published Date') !!}
{!! Form::text('published_at', null, ['class' => 'form-control', 'placeholder' => 'Y-m-d H:i:s'])!!}
#if($errors->has('published_at'))
<span class="help-block">{{ $errors->first('published_at') }} </span>
#endif
</div>
<div class="form-group {{ $errors->has('category_id') ? 'has-error' : '' }}">
{!! Form::label('category_id', 'Category') !!}
{!! Form::select('category_id', App\Category::pluck('title', 'id'), null, ['class' => 'form-control', 'placeholder' => 'Choose category' ]) !!}
#if($errors->has('category_id'))
<span class="help-block">{{ $errors->first('category_id') }} </span>
#endif
</div>
<hr>
{!! Form::submit('Create new post', ['class' => 'btn btn-primary']) !!}
{!! Form::close() !!}
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</div>
</div>
<!-- ./row -->
</section>
Here is my Post Model:
class Post extends Model
{
protected $fillable = ['title', 'slug', 'excerpt', 'body', 'user_id', 'published_at', 'category_id'];
protected $dates = ['published_at'];
public function author()
{
return $this->belongsTo(User::Class);
}
public function category()
{
return $this->belongsTo(Category::class);
}
// images path
Public function getImageUrlAttribute($Value)
{
$imageUrl = "";
if ( ! is_null($this->image))
{
$imagePath = public_path(). "/img/" . $this->image;
if (file_exists($imagePath)) $imageUrl = asset("img/" . $this->image);
}
return $imageUrl;
}
For example to associate a Post to the current user (eg inside a controller method that saves the Post to db) do sth like the following:
// controller method
public function savePost( Request $request )
{
$data = $request->validate([
// your validation rules here..
]);
$post = new Post(); // from Post model
$post->fill($data);
$post->author()->associate(\Auth::user()); // relate post to current user
$post->save(); // save to db
return view('whatever_your_view_is', []);
}
If you need more information leave a comment
In Post model make the following change:
public function author()
{
return $this->belongsTo(User::Class, 'author_id'); // specify the column which stores the author in posts table
}
See documentation on defining relationships.

Laravel 5.4 update user profile not working

I am trying to update the profile of the user who is logged in. I like to create a function that the user that has logged in when he/she wants to update or edit his/her own profile. So I got no errors. But the problem is it wont update and it just refresh my browser but nothing happens.
Here is the code on my controller
public function edit($id)
{
// $applicant = $this->applicantRepository->findWithoutFail($id);
$applicant = Applicant::where('id',$id)->get()->last();
if (empty($applicant)) {
Flash::error('Applicant');
return redirect(route('applicant.home'));
}
return view('applicant-dashboard.edit')->with('applicant', $applicant);
}
public function update($id, UpdateApplicantRequest $request)
{
$applicant = $this->applicantRepository->findWithoutFail($id);
if (empty($applicant)) {
Flash::error('Applicant not found');
return redirect(route('applicant.home'));
}
$input = $request->all();
$applicant = $this->applicantRepository->update([
'name' => $input['name'],
'address' => $input['address'],
'cellphone_no' => $input['cellphone_no']], $id);
Flash::success('Profile updated successfully.');
return redirect(route('applicant.edit'));
}
Here is the code in my routes:
Route::get('/edit/{id}', 'HomeController#edit')->name('applicant.edit');
Route::post('/update', 'HomeController#update')->name('applicant.update');
Here is the code in my views:
edit.blade.php
#extends('applicant-dashboard.layouts.app')
#section('content')
<section class="content-header">
<h1>
Applicant Profile
</h1>
</section>
<div class="content">
{{-- #include('adminlte-templates::common.errors') --}}
<div class="box box-primary">
<div class="box-body">
<div class="row" style="padding-left: 20px">
{!! Form::model($applicant, ['route' => ['applicant.update', $applicant->id], 'method' => 'post']) !!}
#include('applicant-dashboard.fields')
{!! Form::close() !!}
</div>
</div>
</div>
</div>
#endsection
and in fields.blade.php
{!! Form::hidden('id', null, ['class' => 'form-control input-sm','required']) !!}
<!-- Name Field -->
<div class="row" style="padding-right: 15px">
<div class="form-group col-sm-4">
{!! Form::label('name', 'Name:') !!}
{!! Form::text('name', null, ['class' => 'form-control input-sm','required']) !!}
</div>
</div>
<div class="row" style="padding-right: 15px">
<!-- Address Field -->
<div class="form-group col-sm-4">
{!! Form::label('address', 'Address:') !!}
{!! Form::text('address', null, ['class' => 'form-control input-sm','required']) !!}
</div>
</div>
<!-- Cellphone Field -->
<div class="row" style="padding-right: 15px">
<div class="form-group col-sm-4">
{!! Form::label('cellphone_no', 'Cellphone:') !!}
{!! Form::text('cellphone_no', null, ['class' => 'form-control input-sm','required']) !!}
</div>
</div>
<div class="row" style="padding-right: 15px">
<!-- Submit Field -->
<div class="form-group col-sm-12">
{!! Form::submit('Save', ['class' => 'btn btn-primary']) !!}
Cancel
</div>
</div>
code in my model for validation:
public static $rules = [
'name' => 'required',
'email' => 'required|unique:applicants',
'password' => 'required',
'password_confirmation' => 'required|same:password'
];
and the UpdateApplicantRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use App\Models\Applicant;
class UpdateApplicantRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return Applicant::$rules;
}
}
I am looking for help.
Thanks in advance.
There can be several options. Firstly you need to make sure that right url mapping is created, secondly if the validation is not failing and thirdly if any other middleware is redirecting, for example user is not logged in.
Change the beginning of update method to be
public function update($id, Request $request) {
dd($request->all());
If you do not see dd() output then mapping is not right. If you see then validation fails.
Check php artisan route:list and see what middleware is assigned to this route.
Right now it looks like email and password are missing from the fields. Usually you have different validation rules when creating and when updating.
Also I advise to have displaying validation errors in your template.

Getting error when click Submit in Laravel 5?

Controller File Code : EmergencyContactsController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\EmergencyContacts;
class EmergencyContactsController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function create(){
return view('patient/emergencycontacts');
}
public function store(array $data){
echo '<pre>'; print_r($data); die();
}
}
Routes File Code:
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController#index');
Route::get('/patient/emergency-contacts' , 'patient/EmergencyContacts#index' ) ;
Route::get('/emergencycontacts_create' , 'patient/EmergencyContacts#create' ) ;
//Route::post('/emergncycontacts_store' , 'patient/EmergencyContacts#store' ) ;
Route::post('/emergencycontacts_store', ['uses' => 'patient/EmergencyContacts#store', 'as' => 'emergencycontacts_store']);
Route::resource('/patient/emergency-contacts', 'EmergencyContactsController');
Blade file Code : patient/emergencycontacts.blade.php
{!! Form::open(array('route' => 'emergencycontacts_store', 'class' => 'form')) !!}
<div class="form-group">
{!! Form::label('Salutation') !!}
{{ Form::select('salutation', ['Mr.', 'Mrs.', 'Miss.','Ms.']) }}
</div>
<div class="form-group">
{!! Form::label('First Name') !!}
{!! Form::text('firstname', null, array('required', 'class'=>'form-control', 'placeholder'=>'First Name')) !!}
</div>
<div class="form-group">
{!! Form::label('Last Name') !!}
{!! Form::text('lastname', null, array('required', 'class'=>'form-control', 'placeholder'=>'Last Name')) !!}
</div>
<div class="form-group">
{!! Form::label('Relationship') !!}
{{ Form::select('relationship', ['Father', 'Mother', 'Husband','Wife','Son','Daughter','Uncle','Aunty','Other']) }}
</div>
<div class="form-group">
{!! Form::label('Phone') !!}
{!! Form::text('phone', null, array('required'ReflectionException in Container.php line 719: Class App\Http\Controllers\patient/EmergencyContacts does not exist, 'class'=>'form-control', 'placeholder'=>'Phone')) !!}
</div>
<div class="form-group">
{!! Form::label('Fax') !!}
{!! Form::text('fax', null, array('class'=>'form-control', 'placeholder'=>'Fax')) !!}
</div>
<div class="form-group">
{!! Form::submit('Save',array('class'=>'btn btn-primary')) !!}
</div>
{{ Form::close() }}
When I try to submit it give me the following error. I am new in laravel.
Getting error:
ReflectionException in Container.php line 719: Class App\Http\Controllers\patient/EmergencyContacts does not exist
Update the controller's path given in the routes/web.php file:
'EmergencyContactsController#...'
Store function:
public function store(Request $request)
{
echo '<pre>';
print_r($request->all());
echo '</pre>';
}

$errors not showing in Laravel 5.4

I am using a fresh install of Laravel 5.4 now and I also installed https://github.com/appzcoder/crud-generator. I generated a Tickets CRUD using the generator. I was able to publish the "tickets" table to mysql database with "php artisan migrate"
I am currently stuck trying to make the $errors show if there is a missing input to one of the text inputs.
TicketsController.php
<?php
namespace App\Http\Controllers\Users;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Ticket;
use Illuminate\Http\Request;
use Session;
class TicketsController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\View\View
*/
public function index(Request $request)
{
$keyword = $request->get('search');
$perPage = 25;
if (!empty($keyword)) {
$tickets = Ticket::where('user_id', 'LIKE', "%$keyword%")
->orWhere('subject', 'LIKE', "%$keyword%")
->orWhere('description', 'LIKE', "%$keyword%")
->paginate($perPage);
} else {
$tickets = Ticket::paginate($perPage);
}
return view('user.tickets.index', compact('tickets'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\View\View
*/
public function create()
{
return view('user.tickets.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
*
* #return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function store(Request $request)
{
$requestData = $request->all();
Ticket::create($requestData);
Session::flash('flash_message', 'Ticket added!');
return redirect('tickets');
}
}
View
<div class="panel panel-default">
<div class="panel-heading">Create New Ticket</div>
<div class="panel-body">
<button class="btn btn-warning btn-xs"><i class="fa fa-arrow-left" aria-hidden="true"></i> Back</button>
<br />
<br />
#if ($errors->any())
<ul class="alert alert-danger">
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
#endif
{!! Form::open(['url' => '/tickets', 'class' => 'form-horizontal', 'files' => true]) !!}
#include ('user.tickets.form')
{!! Form::close() !!}
</div>
</div>
form.blade.php
<div class="form-group {{ $errors->has('user_id') ? 'has-error' : ''}}">
{!! Form::label('user_id', 'User Id', ['class' => 'col-md-4 control-label']) !!}
<div class="col-md-6">
{!! Form::number('user_id', null, ['class' => 'form-control']) !!}
{!! $errors->first('user_id', '<p class="help-block">:message</p>') !!}
</div>
</div><div class="form-group {{ $errors->has('subject') ? 'has-error' : ''}}">
{!! Form::label('subject', 'Subject', ['class' => 'col-md-4 control-label']) !!}
<div class="col-md-6">
{!! Form::text('subject', null, ['class' => 'form-control']) !!}
{!! $errors->first('subject', '<p class="help-block">:message</p>') !!}
</div>
</div><div class="form-group {{ $errors->has('description') ? 'has-error' : ''}}">
{!! Form::label('description', 'Description', ['class' => 'col-md-4 control-label']) !!}
<div class="col-md-6">
{!! Form::text('description', null, ['class' => 'form-control']) !!}
{!! $errors->first('description', '<p class="help-block">:message</p>') !!}
</div>
</div>
<div class="form-group">
<div class="col-md-offset-4 col-md-4">
{!! Form::submit(isset($submitButtonText) ? $submitButtonText : 'Create', ['class' => 'btn btn-primary']) !!}
</div>
</div>
If don't input the subject text input, I am prompted with page error:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'subject' cannot be null (SQL: insert into `tickets` (`user_id`, `subject`, `description`, `updated_at`, `created_at`) values (1, , dsa, 2017-03-08 13:05:22, 2017-03-08 13:05:22))
Instead of the $errors functionality
Do i need to include something in my TicketsController? and Middleware?
Any help is appreciated.
For this too work,
$this->validate($request, [
'subject' => 'required',
]);
Write above code in action method and then check.
Here is how you can preform validation in laravel

Laravel 5 : Submit form doesnt work

I can't submit a form with laravel. Nothing even happens, no errors is shown. Page just stays the same as it was.
This is my route file:
Route::resource('/', 'WebsiteController');
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
This is file with form:
<div class="col-lg-12">
{!! Form::open(['url' => '/']) !!}
<div class="row">
<div class="col-md-6">
<div class="form-group wow fadeInLeft">
{!! Form::text('name',null,['class'=>'form-control','placeholder'=>'Your name *','id'=>'name']) !!}
</div>
<div class="form-group wow fadeInLeft">
{!! Form::text('email',null,['class'=>'form-control','placeholder'=>'Your email *','id'=>'email']) !!}
</div>
<div class="form-group wow fadeInLeft">
{!! Form::text('phone',null,['class'=>'form-control','placeholder'=>'Your phone *','id'=>'phone']) !!}
</div>
</div>
<div class="col-md-6">
<div class="form-group wow fadeInRight">
{!! Form::textarea('message',null,['class'=>'form-control','placeholder'=>'Your message *','id'=>'message']) !!}
</div>
</div>
<div class="clearfix"></div>
<div class="col-lg-12 text-center wow bounceIn">
{!! Form::submit('Click Me!') !!}
</div>
</div>
{!! Form::close() !!}
#if ($errors->any())
<ul class='alert alert-danger' style='list-style: none;'>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
#endif
</div>
This is my CreateContactRequest file:
<?php namespace App\Http\Requests;
use App\Http\Requests\Request;
class CreateContactRequest extends Request {
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'name' => 'required|min:3',
'phone' => 'required',
'email' => 'required|email',
'message' => 'required'
];
}
}
And finally, this is my store method in WebsiteController:
public function store(CreateContactRequest $request)
{
$this->createContact($request);
}
Included files on top of the WebsiteController file:
use App\Contact;
use App\Http\Requests;
use App\Http\Requests\CreateContactRequest;
use Illuminate\HttpResponse;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Request;
Any help is welcomed and appreciated.

Categories