getting all the data except image in laravel error - laravel

<form id="add-record" enctype="multipart/form-data">
#csrf
<div class="success">
</div>
<div class="form-group row">
<label for="name" class="col-sm-3 label-name col-form-label">Full Name</label>
<div class="col-sm-9 input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-user"></i></span>
</div>
<input type="text" class="form-control input" id="name" name="name" placeholder="Full Name">
</div>
</div>
<div class="row error">
<div class="col-sm-9 offset-sm-3">
<span class="text-danger" id="name-error"></span>
</div>
</div>
<div class="form-group row">
<label for="datepicker" class="col-sm-3 col-form-label">Date of birth</label>
<div class="col-sm-9 input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-calendar"></i></span>
</div>
<input type="text" class="form-control input" id="datepicker" name="dateofbirth" placeholder="">
</div>
</div>
<div class="row error">
<div class="col-sm-9 offset-sm-3">
<span class="text-danger" id="dateofbirth-error"></span>
</div>
</div>
<div class="form-group row">
<label for="course" class="col-sm-3 col-form-label">Gender</label>
<div class="col-sm-9 input-group">
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" id="male" value="Male" checked>
<label class="form-check-label" for="male">
Male
</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" id="female" value="Female">
<label class="form-check-label" for="female">
Female
</label>
</div>
</div>
</div>
<div class="form-group row">
<label for="address" class="col-sm-3 col-form-label">Address</label>
<div class="col-sm-9 input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-home"></i></span>
</div>
<input type="text" class="form-control input" id="address" name="address" placeholder="Address">
</div>
</div>
<div class="row error">
<div class="col-sm-9 offset-sm-3">
<span class="text-danger" id="address-error"></span>
</div>
</div>
<div class="form-group row">
<label for="email" class="col-sm-3 col-form-label">Email</label>
<div class="col-sm-9 input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-envelope"></i></span>
</div>
<input type="email" class="form-control input" id="email" name="email" placeholder="yourmail#email.com">
</div>
</div>
<div class="row error">
<div class="col-sm-9 offset-sm-3">
<span class="text-danger" id="email-error"></span>
</div>
</div>
<div class="form-group row">
<label for="phone" class="col-sm-3 col-form-label">Phone Number</label>
<div class="col-sm-9 input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-phone"></i></span>
</div>
<input type="text" class="form-control input" id="phone" name="phone" placeholder="+3784773847">
</div>
</div>
<div class="row error">
<div class="col-sm-9 offset-sm-3">
<span class="text-danger" id="phone-error"></span>
</div>
</div>
<div class="form-group row">
<label for="course" class="col-sm-3 col-form-label">Course Name</label>
<div class="col-sm-9 input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-book-open"></i></span>
</div>
<input type="text" class="form-control input" id="course" name="course" placeholder="Course name">
</div>
</div>
<div class="row error">
<div class="col-sm-9 offset-sm-3">
<span class="text-danger" id="course-error"></span>
</div>
</div>
<div class="form-group row">
<label for="image-file" class="col-sm-3 col-form-label">Your Image</label>
<div class="col-sm-9 input-group">
<input type="file" class="form-control-file input-image" name="image" id="image-file">
</div>
</div>
<div class="row error">
<div class="col-sm-9 offset-sm-3">
<span class="text-danger" id="image-error"></span>
</div>
</div>
<div class="form-group row">
<div class="col-sm-9 offset-sm-3 input-group">
<input type="submit" class="btn btn-primary">
</div>
</div>
</form>
strong text
When i dd($request->all()); in store function in controller, i get all other values but not image.. It even doesn't shows image=null when i dd(); array:8 [ "_token" => "C27oLkk8wDTcBnZDA38nPCte4SY18HqXqxcFDcrI" "name" => null "dateofbirth" => null "gender" => "Male" "address" => null "email" => null "phone" => null "course" => null ]
Iam using ajax request Although i input the image it shows the image is required.. What am i doing wrong here??
$validator = Validator::make($request->all(), [
'name' => 'required|min:2',
'dateofbirth' => 'required|date',
'gender' => 'required',
'address' => 'required',
'email' => 'required|email',
'phone' => 'required|numeric',
'course' => 'required',
'image' => 'required|image|mimes:jpeg,png,jpg',
]);
if($validator->fails()) {
return response()->json([
'errors' => $validator->errors(),
]);
}
$name = $request['name'];
$dateofbirth = $request['dateofbirth'];
$gender = $request['gender'];
$address = $request['address'];
$email = $request['email'];
$phone = $request['phone'];
$course = $request['course'];
if($request->hasFile('image')) {
$img_name = time() . '.' .$request->file('image')->getClientOriginalExtension();
$destinationPath = public_path('/assets/images/');
$request->file('image')->move($destinationPath, $img_name);
$image = $img_name;
}
Student::create([
'name' => $name,
'dateofbirth' => $dateofbirth,
'gender' => $gender,
'address' => $address,
'email' => $email,
'phone' => $phone,
'course' => $course,
'image' => $image,
]);

You can try this
$validator = Validator::make($request, [
'name' => 'required|min:2',
'dateofbirth' => 'required|date',
'gender' => 'required',
'address' => 'required',
'email' => 'required|email',
'phone' => 'required|numeric',
'course' => 'required',
'image' => 'required|file|mimetypes:image/jpeg,image/png',
]);
if($validator->fails()) {
return response()->json([
'errors' => $validator->errors(),
]);
}
//store image
$path = $request->image->store('images');
//it will store your images at `storage/app/public/images` folder with dynamically generated image name, be sure create images folder there
Student::create([
'name' => $request->name,
'dateofbirth' => $request->dateofbirth,
'gender' => $request->gender,
'address' => $request->address,
'email' => $request->email,
'phone' => $request->phone,
'course' => $request->course,
'image' => $path,
]);
Execute this command from command line
php artisan storage:link
it will create symbolic link of storage/app/public to public/storage folder.
now you can use your image in view like this
{{asset('storage/images/test.jpeg')}}
If you have to read that file in controller then you can use it like this
Storage::disk('public')->get('images/test.jpeg');
Always store your files in storage folder. All public files should be stored at storage/app/public
For details check here https://laravel.com/docs/5.6/filesystem#introduction

Related

How to Retain same value entered in input fields after laravel validation fails

My Blade File Code :-
<div class="col-md-6">
<div class="form-group">
<label for="city">Assigned Hour<span class="text-danger">*</span></label>
<div class="dateBox">
<input type="number" name="assigned_hour[[]" class="form-control newAssignedHour" autocomplete="off" value="" required>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="city">Consumed Hour<span class="text-danger">*</span></label>
<div class="dateBox">
<input type="number" name="consumed_hours[[]" class="form-control newConsumedHour" autocomplete="off" value="" required>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group c-label datepicker-wrap">
<label for="city">Date<span class="text-danger">*</span></label>
<div class="dateBox">
<input type="text" name="date[]" class="form-control input-daterange newDate" id="dateInput" autocomplete="off" value="" required>
<span href="" class="dateCalender emp-cost-i">
<i class="fa fa-calendar"></i> </span>
</div>
</div>
</div>
my Controller :-
$valid = request()->validate([
'project_id' => 'required|int|exists:projects,project_id',
'email_id' => 'required|email',
'emp_id' => 'required|int|exists:contacts,employee_id',
'project_name' => 'required|string|exists:projects,name',
'GMWO' => 'required',
'employee_name' => 'required|string',
'newJobIds' => 'required|array',
'newJobNames' => 'required|array',
'newAssignedHours' => 'required|array',
'newConsumedHours' => 'required|array',
'newDates' => 'required|array'
]);
Can Anyone Suggest How to Retain the old Value for these fields. {{ old('field_name') }} that doesn't work for this.
thanks in Advance
Please try with the below method when validation gets failed and is redirected to form in the controller
->withInput()
For more reference see the below link
https://laravel.com/docs/9.x/responses#redirecting-with-input

SQLSTATE[23000]: Integrity constraint violation in livewire

In Livewire component i have a form inside the modal to edit the information.
When I click on the button, the modal will open and display the item information inside the inputs.
The problem is that if one or all of the inputs do not change their value and the edit button is clicked, it gives the following error that says the values are empty!!. And the inputs must be changed so that there are no errors
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'network' cannot be null (SQL: update `networks` set `network` = ?, `networkName` = ?, `address` = ?, `address_regex` = ?, `tag_memo` = ?, `tag_regex` = ?, `min_withdraw` = ?, `max_withdraw` = ?, `fee` = ?, `deposit` = inactive, `withdraw` = inactive, `networks`.`updated_at` = 2021-06-09 10:18:52 where `id` = 8)
component code:
<?php
namespace App\Http\Livewire\Backend\Currency;
use App\Models\Network;
use Livewire\Component;
class Networks extends Component
{
protected $listeners = ['refreshNetwork' => '$refresh'];
public $confirming;
public $editId;
public $networkEdit;
public $networkNameEdit;
public $address_networkEdit;
public $address_regexEdit;
public $tag_memo_networkEdit;
public $tag_regexEdit;
public $min_withdrawEdit;
public $max_withdrawEdit;
public $feeEdit;
public $depositEdit = false;
public $withdrawEdit = false;
public function editForm($id,$action)
{
if ($network = Network::where('id' , $id)->first()) {
$this->editId = $id;
$this->dispatchBrowserEvent('editNetworkModal', $networkData = [
'network' => $network->network,
'networkName' => $network->networkName,
'address_network' => $network->address,
'address_regex' => $network->address_regex,
'tag_memo_network' => $network->tag_memo_network,
'tag_memo_regex' => $network->tag_memo_regex,
'min_withdraw' => $network->min_withdraw,
'max_withdraw' => $network->max_withdraw,
'fee' => $network->fee ,
'deposit' => $network->deposit,
'withdraw' => $network->withdraw,
]);
}else{
$this->alert('warning', 'شبکه مورد نظر پیدا نشد !', [
'position' => 'center',
'timer' => 2000,
'toast' => false,
'text' => '',
'confirmButtonText' => 'خب',
'cancelButtonText' => 'خب',
'showCancelButton' => false,
'showConfirmButton' => false,
]);
}
}
public function Update($action)
{
if ($action == 'edit')
{
Network::where('id' , $this->editId)->update([
'network' => $this->networkEdit,
'networkName' => $this->networkNameEdit,
'address' => $this->address_networkEdit,
'address_regex' => $this->address_regexEdit,
'tag_memo' => $this->tag_memo_networkEdit,
'tag_regex' => $this->tag_regexEdit,
'min_withdraw' => $this->min_withdrawEdit,
'max_withdraw' => $this->max_withdrawEdit,
'fee' => $this->feeEdit,
'deposit' => $this->depositEdit == false ? 'inactive' : 'active',
'withdraw' => $this->withdrawEdit== false ? 'inactive' : 'active',
]);
$this->emit('refreshNetwork');
$this->dispatchBrowserEvent('hideEditNetworkModal');
$this->alert('success', 'شبکه با موفقیت ویرایش شد.', [
'position' => 'center',
'timer' => 2000,
'toast' => false,
'text' => '',
'confirmButtonText' => 'خب',
'cancelButtonText' => 'خب',
'showCancelButton' => false,
'showConfirmButton' => false,
]);
}
}
public function render()
{
return view('livewire.backend.currency.networks');
}
}
modal:
<div wire:key="B" class="modal fade" tabindex="-1" id="editNetworkModal">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">ویرایـش شبکـه انتقال</h5>
<a href="#" class="close" data-dismiss="modal" aria-label="Close">
<em class="icon ni ni-cross"></em>
</a>
</div>
<div class="modal-body">
<form action="#" class="form-validate is-alter">
<div class="row gy-3">
<div class="col-md-6">
<div class="form-group">
<label class="form-label" for="full-name">شبکه ارز</label>
<div class="form-control-wrap">
<input wire:model.defer="networkEdit" type="text" class="form-control" placeholder="مثال : BNB" id="networkEdit" required>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="form-label" for="email-address">نام شبکه</label>
<div class="form-control-wrap">
<input wire:model="networkNameEdit" id="networkNameEdit" type="text" class="form-control" placeholder="مثال: BEP20" required>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="form-label" for="phone-no">ادرس</label>
<div class="form-control-wrap">
<input wire:model="address_networkEdit" type="text" class="form-control" id="address_networkEdit">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="form-label" for="phone-no">اعتبار سنجی آدرس شبکه به وسیله عبارات منظم</label>
<div class="form-control-wrap">
<input wire:model="address_regexEdit" type="text" class="form-control" id="address_regexEdit">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="form-label" for="phone-no">آدرس Memo یا Tag</label>
<div class="form-control-wrap">
<input wire:model="tag_memo_networkEdit" type="text" class="form-control" id="tag_memo_networkEdit">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="form-label" for="phone-no">اعتبار سنجی Memo شبکه به وسیله عبارات منظم</label>
<div class="form-control-wrap">
<input wire:model="tag_regexEdit" type="text" class="form-control" id="tag_regexEdit">
</div>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="form-label" for="phone-no">حداقل برداشت</label>
<div class="form-control-wrap">
<input wire:model="min_withdrawEdit" type="text" class="form-control" id="min_withdrawEdit">
</div>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="form-label" for="phone-no">حداکثر برداشت</label>
<div class="form-control-wrap">
<input wire:model="max_withdrawEdit" type="text" class="form-control" id="max_withdrawEdit">
</div>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="form-label" for="phone-no">کارمزد برداشت</label>
<div class="form-control-wrap">
<input wire:model="feeEdit" type="text" class="form-control" id="feeEdit">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<div class="custom-control custom-switch">
<input wire:model="depositEdit" type="checkbox" class="custom-control-input" id="depositEdit">
<label class="custom-control-label" for="deposit">واریـز به این آدرس</label>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<div class="custom-control custom-switch">
<input wire:model.defer="withdrawEdit" type="checkbox" class="custom-control-input" id="withdrawEdit">
<label class="custom-control-label" for="withdraw">برداشت به این آدرس</label>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer bg-light">
<button wire:click="Update('edit')" class="btn btn-round btn-outline-primary ">
<div wire:loading wire:target="Update">
<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
</div>
<span class="w-100px">ویرایـش شبکـه</span>
</button>
<button data-dismiss="modal" aria-label="Close" class="btn btn-round btn-outline-secondary w-90px"><span>بستن</span></button>
</div>
</div>
</div>
</div>
and js code to set value for inputs and open modal:
window.addEventListener('editNetworkModal', event => {
$("#editNetworkModal").modal('show');
$('#networkEdit').val(event.detail.network);
$('#networkNameEdit').val(event.detail.networkName);
$('#address_networkEdit').val(event.detail.address_network);
$('#address_regexEdit').val(event.detail.address_regex);
$('#tag_memo_networkEdit').val(event.detail.tag_memo_network);
$('#tag_regexEdit').val(event.detail.tag_regex);
$('#min_withdrawEdit').val(event.detail.min_withdraw);
$('#max_withdrawEdit').val(event.detail.max_withdraw);
$('#feeEdit').val(event.detail.fee);
$('#depositEdit').val(event.detail.deposit);
$('#withdraw').val(event.detail.withdraw);
console.log(event.detail)
});
$this->dispatchBrowserEvent('editNetworkModal', $networkData = [
'network' => $network->network,
One of the goals of Livewire, is forget about JS for this kind of things. Binding the property with wire:model you don't need at all use JS, even pass this db information through the event. With a simple method that retrieve the data from db and assign it to the public properties is enough for you get this in frontend
public function editForm($id,$action)
{
$this->getModelData($id);
$this->dispatchBrowserEvent('openEditModal');
}
public function getModelData($modelId)
{
$model = Model::find($modelId);
$this->property1 = $model->property1;
//......
}

Showing success message but not stored into database laravel

Here is the code for controller:
public function save_product(Request $request){
$request->validate([
'product_name' => 'required',
'product_price' => 'required',
'product_category' => 'required',
'description' => 'nullable',
'image1' => 'required',
'image2' => 'nullable',
'image3' => 'nullable',
], [
'product_name.required' => 'Product name field required',
'product_price.required' => 'Asking price field required',
'product_category.required' => 'Product category field required',
'image1.required' => 'You need a upload image-1 field',
]);
if($request->hasFile('image1') || $request->hasFile('image2') || $request->hasFile('image3')){
$file1 = $request->file('image1');
$file2 = $request->file('image2');
$file3 = $request->file('image3');
$text1 = $file1->getClientOriginalExtension();
$text2 = $file2->getClientOriginalExtension();
$text3 = $file3->getClientOriginalExtension();
$fileName1 = time().'.'.$text1;
$fileName2 = time().'.'.$text2;
$fileName3 = time().'.'.$text3;
$file1->move('uploads/product_image', $fileName1);
$file2->move('uploads/product_image', $fileName2);
$file3->move('uploads/product_image', $fileName3);
$product = Product::create([
'image1'=>$fileName1,
'image2'=>$fileName2,
'image3'=>$fileName3,
'product_category' => trim($request->input('product_category')),
'product_name' => trim($request->input('product_name')),
'product_price' => trim($request->input('product_price')),
'description' => trim($request->input('description')),
]);
}
return redirect()->route('add_product')
->with('success','Successfully added Product!');
}
Here is the code for blade template:
#extends('admin.layouts.master')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-12">
#include('pages.partials.flash_message')
</div>
</div>
</div>
<div class="card card-default">
<div class="card-header card-header-border-bottom">
<h2>Add Product</h2>
</div>
<div class="card-body">
<form action="{{route('save_product')}}" method="POST">
#csrf
<div class="form-group">
<label for="exampleFormControlSelect12">Select Category</label>
<input type="text" class="form-control" placeholder="Enter Arrival Time"
id="exampleFormControlSelect12" name="product_category" list="product_category"
autocomplete="off">
<datalist class="form-control" id="product_category" style="display: none" >
<option value="Women Clothes"></option>
<option value="Jewellery"></option>
<option value="Shoes"></option>
<option value="Sun Glass"></option>
<option value="Hair Band"></option>
</datalist>
</div>
<div class="form-group">
<label for="inputGroupFile02">Upload Product Image-1</label>
</div>
#if ($errors->has('image1'))
<span class="text-danger" style="font-weight: bold">{{ $errors->first('image1') }}
</span>
#endif
<div class="input-group my-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroupFileAddon01">Upload Image</span>
</div>
<div class="custom-file">
<input type="file" name="image1" class="custom-file-input" id="inputGroupFile01"
aria-describedby="inputGroupFileAddon01">
<label class="custom-file-label" for="inputGroupFile01">Choose file</label>
</div>
</div>
<div class="form-group">
<label for="inputGroupFile02">Upload Product Image-2</label>
<small>*Optional</small>
</div>
#if ($errors->has('image2'))
<span class="text-danger" style="font-weight: bold">{{ $errors->first('image2') }}
</span>
#endif
<div class="input-group my-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroupFileAddon01">Upload Image</span>
</div>
<div class="custom-file">
<input type="file" name="image2" class="custom-file-input" id="inputGroupFile02"
aria-describedby="inputGroupFileAddon01">
<label class="custom-file-label" for="inputGroupFile01">Choose file</label>
</div>
</div>
<div class="form-group">
<label for="inputGroupFile02">Upload Product Image-3</label>
<small>*Optional</small>
</div>
#if ($errors->has('image3'))
<span class="text-danger" style="font-weight: bold">{{ $errors->first('image3') }}
</span>
#endif
<div class="input-group my-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroupFileAddon01">Upload Image</span>
</div>
<div class="custom-file">
<input type="file" name="image3" class="custom-file-input" id="inputGroupFile03"
aria-describedby="inputGroupFileAddon01">
<label class="custom-file-label" for="inputGroupFile01">Choose file</label>
</div>
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Product Name or Title</label>
<input type="text" name="product_name" class="form-control"
id="exampleFormControlInput1" placeholder="Enter Product Name or Title">
#if ($errors->has('product_name'))
<span class="text-danger" style="font-weight: bold">{{ $errors-
>first('product_name') }}</span>
#endif
</div>
<div class="form-group">
<label for="exampleFormControlInput2">Asking Price</label>
<input type="number" name="product_price" class="form-control"
id="exampleFormControlInput2" placeholder="Enter Asking Price">
#if ($errors->has('product_price'))
<span class="text-danger" style="font-weight: bold">{{ $errors-
>first('product_price') }}</span>
#endif
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Product Description</label>
<textarea class="form-control" name="product_description"
id="exampleFormControlTextarea1" rows="3"></textarea>
</div>
<div class="form-footer pt-4 pt-5 mt-4 border-top">
<button type="submit" class="btn btn-primary btn-default">Submit</button>
</div>
</form>
</div>
</div>
#endsection
Route:
Route::post('/admin/add_product','App\Http\Controllers\Admin\AdminController#save_product')
->name('save_product')->middleware('admin');
Model:
protected $fillable = [
'product_name',
'product_category',
'product_price',
'description',
'image1',
'image2',
'image3',
];
Migration:
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('product_name');
$table->string('product_category');
$table->string('product_price');
$table->text('description')->nullable();
$table->string('image1');
$table->string('image2')->nullable();
$table->string('image3')->nullable();
$table->timestamps();
});
}
I can't find any error in my code please help me to find out. Thanks in advance.
You have to make separate if conditions for each image. Try this:
$fileName1='';
$fileName2='';
$fileName3='';
if($request->hasFile('image1')) {
$file1 = $request->file('image1');
$text1 = $file1->getClientOriginalExtension();
$fileName1 = time() . '.' . $text1;
$file1->move('uploads/product_image', $fileName1);
}
if($request->hasFile('image2')) {
$file2 = $request->file('image2');
$text2 = $file2->getClientOriginalExtension();
$fileName2 = time() . '.' . $text2;
$file2->move('uploads/product_image', $fileName2);
}
if($request->hasFile('image3')) {
$file3 = $request->file('image3');
$text3 = $file3->getClientOriginalExtension();
$fileName3 = time() . '.' . $text3;
$file3->move('uploads/product_image', $fileName3);
}
$product = Product::create([
'image1'=>$fileName1,
'image2'=>$fileName2,
'image3'=>$fileName3,
'product_category' => trim($request->input('product_category')),
'product_name' => trim($request->input('product_name')),
'product_price' => trim($request->input('product_price')),
'description' => trim($request->input('description')),
]);
if($product){
return redirect()->route('add_product')->with('success','Successfully added Product!');
}
else{
return redirect()->back()->with('error','Error!');
}
using enctype="multipart/form-data" inside form tag .

Saving some user information to a different table in laravel

I have tried to add to do some modification to Registration Controller. I want to add some users record to a different table but I can't get it right. I'm able to capture all the field using dd($data). But I am unable to save the data to the userRecord Table.
In Registration controller
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
'phoneno' => ['required', 'string', 'min:11']
'areas' => ['required', 'string']
]);
}
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
$user->attachRole('user');
$userRecord = new UserRecords();
$userRecord->phoneno = $data->phoneno;//additional fields
$userRecord->email= $data->email;
$userRecord->areas= $data->areas;//additional fields
$userRecord->save();
}
My model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class userRecords extends Model
{
protected $fillable = [
'name', 'email','phoneno','location',
];
}
My View
#extends('layouts.app')
#section('content')
<div class="container mt-4">
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card">
<div class="card-header bg-info text-white">{{ __('Register') }}</div>
<div class="card-body">
<form method="POST" action="{{ route('register') }}">
#csrf
<div class="form-group row">
<label for="name" class="col-md-4 col-form-label text-md-right">{{ __('Name') }}</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control #error('name') is-invalid #enderror" name="name" value="{{ old('name') }}" required autocomplete="name" autofocus>
#error('name')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="name" class="col-md-4 col-form-label text-md-right">{{ __('Phone Number') }}</label>
<div class="col-md-6">
<input id="phoneno" type="text" class="form-control">
</div>
</div>
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ old('email') }}" required autocomplete="email">
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="name" class="col-md-4 col-form-label text-md-right">{{ __('Your Location') }}</label>
<div class="col-md-6">
<select name="areas" id="areas" class="form-control">
#foreach($areas as $item)
<option value="{{ $item->area }}">{{ $item->area}}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control #error('password') is-invalid #enderror" name="password" required autocomplete="new-password">
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="password-confirm" class="col-md-4 col-form-label text-md-right">{{ __('Confirm Password') }}</label>
<div class="col-md-6">
<input id="password-confirm" type="password" class="form-control" name="password_confirmation" required autocomplete="new-password">
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Register') }}
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
Trying to get property 'phoneno' of non-object
$data is an array. But, you get values of $data as object. You should change $data->phoneno into $data['phoneno'], $data->email into $data['email'], $data->areas into $data['areas'].
2.
But not sure whether it will throw another error since I wanted to avoid using Auth tables
I think you can open another topic to clarify this.
A few things you need to set correct
Your model is userRecords so when newing up an instance new userRecords
$data is an array so access properties/elements with array syntax $data['email']
You need to return $user from create method
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
$user->attachRole('user');
$userRecord = new userRecords();
$userRecord->phoneno = $data['phoneno'];//additional fields
$userRecord->email= $data['email'];
$userRecord->areas= $data['areas'];//additional fields
$userRecord->save();
return $user;
}

Laravel, adding data to database after verifying ReCaptcha

I'm using ReCaptcha in my Laravel project, done it with this
tutorial.
I need to create a page where user can post his message after checking captcha.
I have created a modal dialog where user can fill in data like this :
<form class="form-horizontal" action="" method="post">
<div class="form-group error">
<label for="messageName" class="col-sm-3 control-label">Name</label>
<div class="col-sm-9">
<input type="text" class="form-control has-error" id="name" name="name" placeholder="Your name" value=""
ng-model="message.name" ng-required="true">
<span class="help-inline"
ng-show="GBM.text.$invalid && GBM.text.$touched">Required</span>
</div>
</div>
<div class="form-group error">
<label for="messageEmail" class="col-sm-3 control-label">Email</label>
<div class="col-sm-9">
<input type="email" class="form-control has-error" id="email" name="email" placeholder="E-mail" value=""
ng-model="message.email" ng-required="true">
<span class="help-inline"
ng-show="GBM.email.$invalid && GBM.email.$touched">Required</span>
</div>
</div>
<div class="form-group error">
<label for="messageLink" class="col-sm-3 control-label">Web</label>
<div class="col-sm-9">
<input class="form-control" rows="3" class="form-control has-error" id="web" name="web" placeholder="Link for your web" value="" ng-model="message.web" ng-required="false" >
</div>
</div>
<div class="form-group error">
<label for="messageText" class="col-sm-3 control-label">Comment</label>
<div class="col-sm-9">
<textarea class="form-control" rows="3" class="form-control has-error" id="comment" name="comment" placeholder="Your comment" value="" ng-model="message.text" ng-required="true" ></textarea>
<span class="help-inline"
ng-show="GBM.text.$invalid && GBM.text.$touched">Required</span>
</div>
</div>
{!! csrf_field() !!}
<!-- recaptcha -->
{{Request::is('contactd')}}
<div class="form-group">
<div class="col-md-9">
<div class="g-recaptcha" data-sitekey="{{env('GOOGLE_RECAPTCHA_KEY')}}"></div>
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-9 control-label"></label>
<div class="col-md-9">
<button type="submit" name="send" class="btn btn-primary btn-lg btn-block">Add new message <span class="fa fa-paper-plane-o"></span></button>
</div>
</div>
</form>
For a route I got it like this:Route::post('contact','ContactController#store');
And here is the problem, in my controller i got this code to verify captcha:
public function store(ReCaptchataTestFormRequest $request){
return "Captcha done right! ";}
And this code to save data to database
public function store(Request $request)
{
$this->validate($request, [ 'name' => 'required|max:255' ]);
$this->validate($request, [ 'email' => 'required | email' ]);
$this->validate($request, [ 'comment' => 'required' ]);
$ip = $_SERVER['REMOTE_ADDR'];
$browser = $_SERVER['HTTP_USER_AGENT'];
$guestbook = Guest_books::create([
'name' => $request->input('name'),
'email' => $request->input('email'),
'web' => $request->input('web'),
'comment' => $request->input('comment'),
'ip' => $ip,
'browser' => $browser
]);
return $guestbook;
}
So the question is: What to write in Controller for project to verify Captcha and then post it to database?
The tutorial you've followed teaches you how to create a custom validation rule which you can then use when validating requests, either through a Form Request or directly in your controller.
The mistake you've made in your controller is that you've called validate multiple times, instead you should pass it an array containing all of your rules, including your recaptcha rule, e.g:
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|max:255',
'email' => 'required|email',
'comment' => 'required',
'g-recaptcha-response' => 'required|recaptcha',
]);
// ...
}
Additionally, you should note that the store method should always return a redirect.

Resources