I am new in Laravel.
This is my laravel controller:
public function store()
{
$validator = Validator::make($data = Input::all(), City::$rules);
if ($validator->fails())
{
return Redirect::back()->withErrors($validator)->withInput();
}
$image_temp=Input::file('image');
$name = Input::file('image')->getClientOriginalName();
$data['image']='';
if(Image::make($image_temp->getRealPath())->save('public/up/city/'.$name)){
$data['image']='up/city/'.$name;
}
City::create($data);
return Redirect::route('admin.cities.index');
}
and This is my model:
class City extends \Eloquent {
protected $primaryKey='city_id';
// Add your validation rules here
public static $rules = [
'title' => 'required',
'image' => 'mimes:jpeg',
'parent_id' => 'required',
'name' => 'required',
'english_name'=>'unique:cities,english_name|required'
];
// Don't forget to fill this array
protected $fillable = ['name', 'parent_id', 'english_name','population','phone_prefix','image'];
}
And I have a form I use {{ $errors->first('inputName','<p class="error">:message</p>') }} bellow my form inputs, when I send form without filling inputs I get error under each form input. But when I fill out all form inputs and then submit the Laarvel validation return fail (I mean mass assignment not working and not registering, and redirects back to create page.) what is the problem?
Almost always the reason for a mass assignment error is a missing attribute in the $fillable array. In your case it is title.
protected $fillable = ['title', 'name', 'parent_id', 'english_name','population','phone_prefix','image'];
^
Edit
Apparently the problem was actually that the title in the $rules array, which should have been name...
Related
I've an update form that contains an image and other data to be updated I changed the default route key to use the name instead of the default key which is the ID and I made a separate form request to validate my requests It works fine when posting new record unfortunately it keeps failing with the name field which is unique field; I've checked all threads on github and in stackoverflow with no use although I have the same project in laravel 5.5 and it works fine and now I'm stuck with laravel 6
hereis my form
let data = new FormData();
data.append('name', this.channel.name);
data.append('base_color', this.channel.baseColor);
data.append('complementary_color', this.channel.complementaryColor);
if (this.file){
data.append('avatar', this.file);
}
data.append('_method', 'PUT');
axios.post(`/dashboard/channels/${this.channel.name}`, data).then(resp => {
this.$parent.$emit('channel_updated', resp.data);
}).catch(error => {
flash(error.response.data, 'danger', 'backEndStyle');
});
and here is my route
Route::resource('/dashboard/channels', 'ChannelController');
and here is my form request
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ChannelRequest 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 [
'name' => 'required|unique:channels,name,'. $this->id,
'base_color' => 'required',
'complementary_color' => 'required',
];
}
}
here is my controller for update method
public function update(Channel $channel, ChannelRequest $request)
{
$channel->update([
'name' => $request->name,
'bg_base_color' => $request->base_color,
'bg_complementary_color' => $request->complementary_color,
]);
return response($channel->fresh(), 200);
}
Use the ignore constraint to ignore the current model when validating unique
public function rules()
{
return [
'name' => ['required', Rule::unique('channels')->ignore($this->route('channel'))],
'base_color' => 'required',
'complementary_color' => 'required',
];
}
Here i have two inputs field as name and age.
I wanna validate name but not age.
How can i send both value to store.
request()->validate([
'name' => 'required',
]);
//Here i wanna add 'age' along with 'name' in $request
//Then i must store.
Pastor::create($request->all());
The $request->all() already sends whatever is in your request. But if you like you can specifically pass request values to create method like this:
Pastor::create([
'name'=> $request->name,
'age' => $request->age
//any other fields
]);
I assume you have named your inputs like i have passed into create method and it should work.
use the Validator class Laravel has. lets say you have UserController
Use Validator;
Use App\User;
class UserController extends Controller
{
// Your Validator
protected function yourValidatorName(array $data)
{
$rules = ['name'=>'required'];
return Validator::make($data,$rules);;
}
// Your Main Function
public function yourFunctionName(Request $request)
{
$isValid = $this->yourValidatorName($request->all());
if(!isValid->fails())
{
// your code here (validation passed)
}
else
{
// your code here (validation failed)
}
}
}
You simply put a check on name field only
$this->validate($request,[
'name' => 'required|min:3|max:200',
],[
'name.required' => 'name is a required field.', // custom messages you can omit them
'name.min' => ' Name must be at least 3 characters.', // custom message for minimum characters
'name.max' => ' Name should not be greater than 200 characters.', // custom message for maximum characters
]);
Pastor::create($request->all());
Without custom messages
$this->validate($request,[
'name' => 'required|min:3|max:200',
]);
Pastor::create($request->all());
I'm staring with Laravel and I'm having troubles trying to make a simple insert, but It seems that all of my fillable fields are not being included. This is the error:
SQLSTATE[HY000]: General error: 1364 Field 'name' doesn't have a default value
(SQL: insert into `addresses` (`updated_at`, `created_at`)
values (2017-12-25 09:31:49, 2017-12-25 09:31:49))
As you can see, only created_at and updated_at are about to be inserted, I thought that maybe I forgot my fillable vars, but this is my Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Addresses extends Model
{
protected $fillable = [
'name',
'city',
'suburb',
'street',
'o_number',
'i_number',
'postal_code',
'phone_s',
'email_s',
'google_map',
'customer_id'
];
}
And the Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Addresses;
use App\Customers;
class AddressesController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function store(Request $request){
$create = Addresses::create([
'name' => request('name'),
'city' => request('city'),
'suburb' => request('suburb'),
'street' => request('street'),
'o_number' => request('o_number'),
'i_number' => request('i_number'),
'postal_code' => request('postal_code'),
'phone_s' => request('phone_s'),
'email_s' => request('email_s'),
'google_map' => request('google_map'),
'customer_id' => Customers::where('code',$request->session()->get('customer_code'))->first()->id
]);
$success = $create ? $request->session()->flash('success', '¡Registro exitoso!') : $request->session()->flash('success', 'Ooops! Algo salio mal :(');
return redirect('addresses/'.$request->session()->get('customer_code'));
}
}
Echo the request() values works! So I'm missing right now, I have some other Models and Controller working good in the same way. Please Help!
This error show because you the NAME field is required on your database. Try to edit your migration script and put default value on this field or make it nullable.
eg.
$table->string('name')->nullable();
OR
$table->string('name')->default('');
Then run a migration refresh.
Goto "phpmyadmin" >> "Variables" then find "sql_mode" edit and remove "STRICT_ALL_TABLES or STRICT_TRANS_TABLES"
It is working for me.
Hope it will help for All.
This is late answer for this question, but it might help for others.
This error can be occurred due to error in $fillable data in modal.
You can try using
protected $guarded = []
instead of
protected $fillable = [
'name',
'city',
'suburb',
'street',
'o_number',
'i_number',
'postal_code',
'phone_s',
'email_s',
'google_map',
'customer_id'
];
But You have to validate the data that you passed within the controller.
The error occurs due to the strict mode of MYSQL5.7. Please change your config/database.php in the connections.mysql section by putting 'strict' => false.
I solved it using save()
$addresses = new Addresses;
$customer_id = Customers::where('code',$request->session()->get('customer_code'))->first()->id;
$addresses->name = $request->name;
$addresses->city = $request->city;
$addresses->suburb = $request->suburb;
$addresses->street = $request->street;
$addresses->o_number = $request->onumber;
$addresses->i_number = $request->inumber;
$addresses->postal_code = $request->postal_code;
$addresses->phone_s = $request->phone_s;
$addresses->email_s = $request->email_s;
$addresses->google_map = $request->map;
$addresses->customer_id = $customer_id;
$success = $addresses->save() ? $request->session()->flash('success', '¡Registro exitoso!') : $request->session()->flash('success', 'Ooops! Algo salio mal :(');
return redirect('addresses/'.$request->session()->get('customer_code'));
It's working properly
When you use the nullable() method on a field, that field will default to NULL.
For example, add this to your migration file:
$table->string('name')->nullable();
Update:
You can add:
$table->string('name')->nullable()->default(null);
You can check Null option in table structure, like this -
Make sure request() has key 'name'.Replace request('name') to random string and try again.
In my case I forgot to change - this is my code on my Controller
public function store(Request $request)
{
$message = new Message();
$message->name = $request->input('name');
$message->name = $request->input('message');
$message->save();
}
I made a duplication of the 'name' that's why it happened and made this
public function store(Request $request)
{
$message = new Message();
$message->name = $request->input('name');
$message->message = $request->input('message');
$message->save();
}
This way the solution to the problem.
I was having this problem because I didn't add a correct column under $fillable list.
class Chirp extends Model
{
use HasFactory;
protected $fillable = [
'message', // This line should be added.
];
}
I have a issue, Please take a look below.
I have a edit user profile section where we update user account, i want to check if no image exists in table & user too not provided image then we have to validate the image & show an error. if there is already a image exists in table then no image validation suppose to check. Everything works good except image validation.
i am using from request for validation. below is my validation rules in request file.
public function rules()
{
return [
'user_type' =>'required',
'first_name' =>'required|max:100',
'last_name' =>'required|max:100',
'email' =>'required|email|max:100',
'image' =>'required|image',
'zip_code' =>'required|numeric|min:5',
];
}
I am using Laravel 5.2, Thanks in advance.
Finally i figure out the solution using help of #Amir. below is the complete solutions of this issue.
//add this in user model
public function notHavingImageInDb(){
return (empty($this->image))?true:false;
//return true;
}
//import the User model & Auth class in request class.
use App\User;
use Auth;
//add this in from request
public function rules()
{
$user = User::find(Auth::id());
$rules = [
'user_type' =>'required',
'first_name' =>'required|max:100',
'last_name' =>'required|max:100',
'email' =>'required|email|max:100',
'image' =>'image',
'zip_code' =>'required|numeric|min:5',
];
if ($user->notHavingImageInDb()){
$rules['image'] = 'required|image';
}
return $rules;
}
Now all done.
In the above code we check if the column has some value or not in validation, if yes then model function return true, this make the if condition active in request class, else, if condition remain inactive. works like charm.
Thanks
take a look at Conditionally Adding Rules:
so something like:
$v->sometimes(['image'], 'required|image', function($input) use ($user) {
return $user->notHavingImageInDb();
});
you can also use plain logic like:
public function rules()
{
$roles = [
'user_type' =>'required',
'first_name' =>'required|max:100',
'last_name' =>'required|max:100',
'email' =>'required|email|max:100',
'image' =>'image',
'zip_code' =>'required|numeric|min:5',
];
if ($user->notHavingImageInDb())
$rules['image'] = 'required|image';
return $rules
}
You can create another request class and name it UserUpdateRequest with artisan
like
php artisan make:request UserUpdateRequest
in this request class you just have to remove 'required' it will be like that
'image' => 'image'
and set UserUpdateResuest as parameter to update method like
public function update(UserUpdateRequest $userUpdateRequest, $id){
//
}
I am trying to validate an update user profile form, whereby the validation should check that the email doesn't exist already, but disregard if the users existing email remains.
However, this continues to return validation error message 'This email has already been taken'.
I'm really unsure where I'm going wrong. Otherwise, the update form works and updates perfectly.
HTML
{{ Form::text('email', Input::old('email', $user->email), array('id' => 'email', 'placeholder' => 'email', 'class' => 'form-control')) }}
Route
Route::post('users/edit/{user}', array('before' => 'admin', 'uses' => 'UserController#update'));
User Model
'email' => 'unique:users,email,{{{ $id }}}'
Your rule is written correctly in order to ignore a specific id, however, you'll need to update the value of {{{ $id }}} in your unique rule before attempting the validation.
I'm not necessarily a big fan of this method, but assuming your rules are a static attribute on the User object, you can create a static method that will hydrate and return the rules with the correct values.
class User extends Eloquent {
public static $rules = array(
'email' => 'unique:users,email,%1$s'
);
public static function getRules($id = 'NULL') {
$rules = self::$rules;
$rules['email'] = sprintf($rules['email'], $id);
return $rules;
}
}
You can accomplish this with the sometimes function of the validator
Something like:
$validator->sometimes('email', 'unique:users,email', function ($input) {
return $input->email == Input::get('email');
});
See http://laravel.com/docs/4.2/validation#conditionally-adding-rules for more info