Laravel inserting "null" into database from form input. - php

This is a strange problem i've run into. I have a form that takes in First, Last, Title, Email, and Phone which takes that data and inputs into a ContactPerson table I have set up in a database.
When I fill out the form, and hit submit, only the Title, Email, and Phone number get inserted correctly into the database. The first and last names get inserted as NULL.
Here's some of my code that I have using PHPstorm and Laravel 2.5.3
My Create a New Contact view:
<h1 style="text-align:center;">Add A New Contact Person</h1>
<hr/>
{!! Form::open(['url' => '/create']) !!}
<span style="text-align:center;align-content:right;display:block; margin-right:auto;margin-left:auto;">
<div class="form">
{!! Form::label('first', 'First Name: ') !!}
{!! Form::text('First', null, ['class' => 'form']) !!}
</div>
<div class="form">
{!! Form::label('last', 'Last Name: ') !!}
{!! Form::text('Last', null, ['class' => 'form']) !!}
</div>
<div class="form">
{!! Form::label('title', 'Title: ') !!}
{!! Form::text('Title', null, ['class' => 'form']) !!}
</div>
<div class="form">
{!! Form::label('email', 'Email: ') !!}
{!! Form::text('Email', null, ['class' => 'form']) !!}
</div>
<div class="form">
{!! Form::label('phone', 'Phone: ') !!}
{!! Form::text('Phone', null, ['class' => 'form']) !!}
</div>
{!! Form::submit('Submit', ['class' => 'btn btn-primary form']) !!}
</span>
{!! Form::close() !!}
Here is my controller called ResourceController I have created:
class ResourceController extends Controller
{
public function resource()
{
$contacts = ContactPerson::all();
return view('pages.resource', compact('contacts'));
}
public function create()
{
return view('pages.create');
}
public function store(Requests\CreateNewContactRequest $request)
{
ContactPerson::create($request->all());
return redirect('resource');
}
}
Here's the validation I have set up in the CreateNewContactRequest class for the form:
public function rules()
{
return [
'First' => 'required|min:2',
'Last' => 'required|min:1',
'Title' => 'required|min:2',
'Email' => 'required|Email|unique:users',
'Phone' => 'required|numeric|min:9'
];
}
Here's what it looks like when I fill out/submit the form.
After hitting submit it redirects to the database dump:
the view of the database after insertion:

Looking at your dump details, your field names need to match your form names or visa versa, so your form names need to change to say:
<div class="form">
{!! Form::label('first', 'First Name: ') !!}
{!! Form::text('First_Name', null, ['class' => 'form']) !!}
</div>
<div class="form">
{!! Form::label('last', 'Last Name: ') !!}
{!! Form::text('Last_Name', null, ['class' => 'form']) !!}
</div>
EG for field name First_Name your input needs to be named the same name="First_Name"
Also making sure your fillable details are also correct
protected $fillable = ['First_Name','Last_Name','Title','Email','Phone'];

Related

Input::hasFile() not working

I am trying to check if the image that i am trying to upload is getthing processed, but when i try to use de Input::hasFile('upimg') to check it out it doesnt do anything. This is my form:
{!! Form::open(array('route' => array('uploadimage'), 'method' => 'POST')) !!}
{!! csrf_field() !!}
<div class="form-group">
{!! Form::label('newimg', 'Choose Image to upload:', ['class' => 'control-label']) !!}
{!! Form::file('upimg', null) !!}
</div>
<div class="form-group">
{!! Form::label('directory', 'Choose directory:', ['class' => 'control-label']) !!}
{!! Form::select('newimage', [ '' => 'none'] + $imagesdir , '', ['class' => 'form-control']) !!}
</div>
{!! Form::submit('Upload', ['class' => 'btn btn-primary']) !!}
{!! Form::close() !!}
And this is the code i am using to check the file:
public function doUpload()
{
if (Input::hasFile('upimg')){
echo 'uploaded';
};
}
As you can see i am trying to check:
{!! Form::file('upimg', null) !!}
If i am not wrong its suppose to give mi back the echo but nothing happens. Why is this not working? what am i doing wrong?
Be sure you have an 'file' => true option in your form definition like below:
{!! Form::open(['route' => ['uploadimage'], 'file' => true]) !!}
This option causes that your form will be render with enctype="multipart/form-data" option in HTML form tag. See documentation: HTML enctype
You don't have to add method => 'POST' to your definition of form, because Laravel 5 sents forms with POST method by default.
Please let me know if this solution will not work for you.
For checking files on server side you can use methods of Request object like in documentation of Laravel: Files in Laravel

Laravel 5 validation rule required_with:password_confirmation

I have a problem with validation rule in edit form. My form fields are name, email, password and password_confirmation. My UpdateUserRequest class return this rules:
return [
'name' => ['required', 'max:50', 'min:3'],
'email' => ['required', 'email', 'unique:users,email,' .$this->route('users')],
'password' => ['required_with:password_confirmation', 'confirmed']
];
And update method in UsersController is:
public function update(Requests\UpdateUserRequest $request, $id)
{
$user = $this->users->findOrFail($id);
$user->fill($request->only('name', 'email', 'password'))->save();
return redirect(route('backend.users.edit', $user->id))->with('status', 'User has been updated.');
}
And this is a form:
{!! Form::model($user, [
'method' => $user->exists ? 'put' : 'post',
'route' => $user->exists ? ['backend.users.update', $user->id] : ['backend.users.store']
]) !!}
<div class="form-group">
{!! Form::label('name') !!}
{!! Form::text('name', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('email') !!}
{!! Form::email('email', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('password') !!}
{!! Form::password('password', ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('password_confirmation') !!}
{!! Form::password('password_confirmation', ['class' => 'form-control']) !!}
</div>
{!! Form::submit($user->exists ? 'Save User' : 'Create New User', ['class' => 'btn btn-primary btn-sm']) !!}
Password validate rule required_with:password_confirmation should allow user to leave empty fields password and password_confirmation if he does not want to change it, but this doesn't work. When I leave the field empty, the empty value is hashed and stored in database. All other validations work fine, but not when user leaves empty value in password and password_confirmation. Why this isn't working? What am I doing wrong?
You will need to updated the db seperate without using fill etc as it will always get the password value empty or not and then add it, so try:
$user = $this->users->findOrFail($id);
$user->name = $request->get('name');
$user->email = $request->get('emil');
if(!empty($request->get('password')) {
$user->password = $request->get('password');
}
$user->save();
Something like that so you are checking if the PW needs to also be updated etc.
Basically you need to verify if it need to be entered or not, your method takes all the requested values and will update no matter if they are empty or note.

Laravel Passing Data From One View to Another View

I am thinking of making a landing page from the home page, which will direct the guest to the register page. I thought of making two forms for sending data and two submit buttons in them, let's say reader and writer and according to the button they use to go to the register form page, I want to pass the profession string from the button in the landing page and then, place it into the register form in /auth/register.
{!! Form::open(array('url' => '/auth/register', 'profession' => 'writer')) !!}
{!! Form::submit('Writer', array('class' => 'btn btn-warning')) !!}
{!! Form::close() !!}
{!! Form::open(array('url' => '/auth/register', 'profession' => 'reader')) !!}
{!! Form::submit('Reader', array('class' => 'btn btn-default')) !!}
{!! Form::close() !!}
It is not directing me to the page app.com/auth/register. But it works when I directly type the link.
What I thought was using $profession in /auth/register/ and access the value and use it as a hidden field in the registeration form.
(using laravel 5.1)
Edit:
In view source:
<form method="POST" action="http://app.com/auth/register" accept-charset="UTF-8" profession="writer"><input name="_token" type="hidden" value="dZXQsNI1BGQ39JjDLFUEkSQzL5bTNwe8o3rpiSQL">
<input class="btn btn-warning" type="submit" value="Writer">
</form>
<form method="POST" action="http://app.com/auth/register" accept-charset="UTF-8" profession="reader"><input name="_token" type="hidden" value="dZXQsNI1BGQ39JjDLFUEkSQzL5bTNwe8o3rpiSQL">
<input class="btn btn-default" type="submit" value="Reader">
</form>
Edit 2:
{!! Form::open(array('url' => '/auth/register', 'profession' => 'writer')) !!}
{!! link_to('/auth/register', 'Writer', array('class' => 'btn btn-default')) !!}
{!! Form::close() !!}
I tried this instead. At least, now it is directing the page but I still can't access the data value of profession
Edit 3:
Routes:
Route::get('auth/register', 'Auth\AuthController#getRegister');
Route::post('auth/register', 'Auth\AuthController#postRegister');
Route::get('/', function()
{
return view('pages.home');
});
and https://app.com/auth/register is working.
Here's a step by step walkthrough on how to implement it. I tested it. So it works. This is for 'writer', but you could replicate it as you had originally planned for other professions.
I assume you've registered the Laravel Collective package since you're using the curly braces and exclamation points.
Step 1:
In your landing page view, where you have the writer button, add a hidden field with the string 'writer'. Like this:
{!! Form::open(['route' => ['writer_path']]) !!}
{!! Form::hidden('profession', 'writer') !!}
{!! Form::submit('Writer', array('class' => 'btn btn-warning')) !!}
{!! Form::close() !!}
Not that in the open field we are using a named route ('writer_path').
Step 2:
Register a route and a controller on your routes.php file, like this:
Route::post('auth/register', [
'as' => 'writer_path',
'uses' => 'SampleController#displayForm'
]);
Step 3:
In your sample controller, you define the displayForm method.
Within that method you first obtain the value you passed from the landing page view.
If you don't know how to create a controler, you can do
php artisan make:controller SampleController
from the command line
Because the value arrives as an array, you have to obtain the string 'writer' from the array and then pass it to the new view (the view with the registration form for the writer).
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
class SampleController extends Controller
{
/**
* Display a listing of the resource.
*
* #return Response
*/
public function displayForm()
{
$input = Input::get();
$profession = $input['profession'];
return view('writerregistration', ['profession' => $profession]);
}
}
Last Step:
In the new view which you will create as writerregistration.blade.php, you will display the form with the field you just passed ('profession') which contains the string 'writer'. Like this:
{!! Form::open() !!}
{!! Form::label('username', 'Username:') !!}
{!! Form::text('username', null, ['class' => 'form-control']) !!}
{!! Form::label('profession', 'Profession:') !!}
{!! Form::text('profession', $profession, ['class' => 'form-control']) !!}
{!! Form::label('email', 'Email:') !!}
{!! Form::text('email', null, ['class' => 'form-control']) !!}
{!! Form::label('passowrd', 'Password:') !!}
{!! Form::password('password', ['class' => 'form-control']) !!}
{!! Form::label('password_confirmation', 'Password Confirmation:') !!}
{!! Form::password('password_confirmation', ['class' => 'form-control']) !!}
{!! Form::submit('Sign Up', ['class' => 'btn btn-primary']) !!}
{!! Form::close() !!}
Presto, you've populated the field in the registration form for the writer with the info on the hidden field that belonged to the writer button in the landing page.

Laravel 5 Populate a form from two different tables

I stumbled upon a problem while creating a CRUD application in Laravel 5. In the edit section of a product I have 2 inputs that are populated from 'products' table and I have a dropdown list that needs to be populated with data from the categories table. The problem is that I don't know how to aproch the dropdown list. I generated the Form::model for the two inputs but I'm stuck at the dropdown list.
Controller
public function edit($id)
{
$products_edit = products::find($id);
return View::make('products.edit')->with('products_edit', $products_edit);
}
View
{!! Form::model($products_edit, array('route' => array('products.update', $products_edit->id), 'method' => 'PUT')) !!}
<div class="form-group">
{!! Form::label('name', 'Nume') !!}
{!! Form::input('text', 'name', $products_edit->product_name, array('class' => 'form-control')) !!}
</div>
<div class="form-group">
{!! Form::label('price', 'Cost') !!}
{!! Form::input('number', 'price', $products_edit->product_price, array('class' => 'form-control')) !!}
</div>
<div class="form-group">
{!! Form::label('category', 'Categorie') !!} <br />
{!! Form::select('category', <!-- insert var here -->, array('class' => 'form-control') !!}
</div>
You can do this at your controller:
public function edit($id)
{
$products_edit = Product::findOrFail($id);
$categories = Category::lists('name', 'id');
return view('product.edit', compact('products_edit', 'categories'));
}
In the view you still make the form model bind:
{!! Form::model($products_edit, array('route' => array('products.update', $products_edit->id), 'method' => 'PUT')) !!}
And to create the category dropdown try this:
{!! Form::label('category_id', 'Category') !!}
{!! Form::select('category_id', $categories, null, ['class' => 'form-control']) !!}
your can do thi controller:
public function edit($id)
{
$products_edit = Product::find($id);
$categories = Category::pluck('name', 'id');
return view('product.edit', compact('products_edit', 'categories'));
}

Laravel 5.0 Model::create() method creates two rows in one form request

When I fire Product::create($request->all()) method it creates two rows in a table with the same values.
Here is my Form.
{!! Form::open(['route' => 'product.store', 'method' => 'post']) !!}
<!-- Title Form Input -->
<div class="form-group">
{!! Form::label('title', 'Title:', ['class' => 'control-label']) !!}
{!! Form::text('title', null, ['class' => 'form-control']) !!}
</div>
<!-- Description Form Input -->
<div class="form-group">
{!! Form::label('description', 'Description:', ['class' => 'control-label']) !!}
{!! Form::textarea('description', null, ['class' => 'form-control', 'id' => 'source']) !!}
</div>
<!-- Category Form Input -->
<div class="form-group">
{!! Form::label('category', 'Category:', ['class' => 'control-label']) !!}
{!! Form::text('category', 'Test Cat', ['class' => 'form-control']) !!}
</div>
<!-- create Form -->
<div class="form-group">
{!! Form::submit('create', ['class' => 'btn btn-primary']) !!}
</div>
{!! Form::close() !!}
Here is my store method
public function store(ProductRequest $request)
{
Product::create($request->all());
// $productTran = $request->only(['title', 'description']);
// $productTran['product_id'] = $product->id;
}
Here is my Product.php (Model)
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model {
protected $table = 'products';
protected $fillable = ['category'];
}
And here is my ProductRequest class
class ProductRequest extends FormRequest {
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'title' => 'required'
];
}
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
}
I'm using it exatly the way you do, and didn't happen to me.
I don't know if this have any relationship, but in your model, the fillable var you need to put ['title', 'description', 'category'] for working correctly.
Or, at less, ['title'] that is the only required value.
Why you don't put dd($request); and show us what is inside.

Categories