I'm trying to insert data to Database, but got the error "Creating default object from empty value" and still don't understand, this error come from?
in My Controller
public function store(Request $request)
{
$request->validate([
'amount' => 'required',
'method' => 'required',
]);
$payrolls = new Payroll();
$payrolls->employee_id = auth()->user()->id;
$payrolls->account_id = auth()->user()->id;
$payrolls->employee_name = $request->get('employee_name');
$payrolls->description = $request->get('description');
$payrolls->account = $request->get('account');
$payrolls->amount = $request->get('amount');
$payrolls->method = $request->get('method');
$payrolls->save();
return response()->json(['created' => true]);
}
Any help? Thanks......
As #arm stated, you're having a typo in your code, which leads to the error you're getting.
The code below should make it working.
I would also suggest you to use $request->input('****'); instead of dynamic variables like you're doing $request->account;
public function store(Request $request)
{
$request->validate([
'amount' => 'required',
'method' => 'required',
]);
$payrolls = new Payroll();
$payrolls->employee_id = auth()->user()->id;
$payrolls->account_id = auth()->user()->id;
$payrolls->employee_name = $request->input('employee_name');
$payrolls->description = $request->input('description');
$payrolls->account = $request->input('account');
$payrolls->amount = $request->input('amount');
$payrolls->method = $request->input('method');
$payrolls->save();
return response()->json(['created' => true]);
}
You could also have a look at the Payroll::create(), which makes it easier to create a entry in the DB, instead of making a new Payroll(), and saving at the end. https://laravel.com/docs/5.7/eloquent#mass-assignment
Related
I am trying to store logged user's id but I am getting this error
ErrorException
array_map(): Argument #2 should be an array
This is the code in the controller
public function store(Request $request)
{
if (!auth()->check()) {
abort(403, 'Only authenticated users can create new posts.');
}
$data = request()->validate([
'id' => $id = Auth::id(),
'content' => 'required',
'topic' => 'required',
'hashtag' => 'required'
]);
$check = Tweets::create($data);
return Redirect::to("form")->withSuccess('Great! Form successfully submit with validation.');
}
The error is in this line of code.
'id' => $id = Auth::id(),
I know that should be a string but to explain to you what I am trying to do, and I still have not found any solution.
Do it Like this.
public function store(Request $request)
{
if (!auth()->check()) {
abort(403, 'Only authenticated users can create new posts.');
}
$request->validate([
'content' => 'required',
'topic' => 'required',
'hashtag' => 'required'
]);
$data = $request->all();
$data['id'] = Auth::id();
$check = Tweets::create($data);
return Redirect::to("form")->withSuccess('Great! Form successfully submit with validation.');
}
Delete this
'id' => $id = Auth::id(),
and add
$data['id'] = Auth::id();
before
$check = Tweets::create($data);
That should work
I've currently got the following store function
public function store()
{
$data = request()->validate([
'name' => 'required',
'description' => 'required',
'url' => ['required', 'url'],
'image' => ['nullable', 'image'],
]);
$DB1 = new \App\Part1();
$DB1->name = $data['name'];
$DB1->save();
$DB2 = new \App\Part2();
$DB2->db1_id = $DB1->id;
$DB2->description = $data['description'];
$DB2->url = $data['url'];
$DB2->image = $data['image'];
$DB2->save();
}
Every time I've got an empty image I get the following error:
ErrorException
Undefined index: image
I thought the nullable rule would be enough.
The only work around I found is to check if the image is empty but it feels like I am doing it wrong:
if (request('image')) {
$image = $data['image'];
} else {
$image = NULL;
}
Use isset or empty method or ?? operator
public function store()
{
$data = request()->validate([
'name' => 'required',
'description' => 'required',
'url' => ['required', 'url'],
'image' => ['nullable', 'image'],
]);
$DB1 = new \App\Part1();
$DB1->name = $data['name'];
$DB1->save();
$DB2 = new \App\Part2();
$DB2->db1_id = $DB1->id;
$DB2->description = $data['description'];
$DB2->url = $data['url'];
$DB2->image = isset($data['image']) ? $data['image'] : null;
// or $DB2->image = !empty($data['image']) ? $data['image'] : null;
// or $DB2->image = $data['image'] ?? $data['image'];
$DB2->save();
}
Hope this helps you
simply use the new PHP7 feature for in line checking and acting :
$DB2->image = $data['image']?? NULL;
its not about wrong or not, it is about the good and the better.
Now the ?? mean if the $data['image'] is null(false) then simply set NULL to $DB2->image.
I want to store data through api. It's working but problem is when I add validation it does not give me corresponding message . How can I fix it? Thanks in advance
Here is my route
Route::post('api/add_user', 'TestApiController#store');
Here is my controller
public function store(Request $request)
{
$validation = Validator::make(Request::all(), [
'name' => 'required',
'phone' => 'required',
'email' => 'required'
]);
if ($validation->errors()) {
return $errors->toJson();
} else {
$testApi = new testApi();
$testApi->name = $request->name;
$testApi->phone = $request->phone;
$testApi->email = $request->email;
$testApi->save();
return "ok";
}
}
to handle that your method should be like this :
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required',
'phone' => 'required',
'email2' => 'required|email'
]);
if($validator->fails()){
// here we return all the errors message
return response()->json(['errors' => $validator->errors()], 422);
}
$testApi = new testApi();
$testApi->name = $request->name;
$testApi->phone = $request->phone;
$testApi->email = $request->email;
$testApi->save();
// 201 http code means that the server has proceced your request correctly
return response()->json([], 201);
}
You don't have to manually do this. simply
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'phone' => 'required',
'email' => 'required'
]);
$testApi = new testApi();
$testApi->name = $request->name;
$testApi->phone = $request->phone;
$testApi->email = $request->email;
$testApi->save();
return "ok";
}
this will automatically handles validation and returns error message when invalid.
Update
if you wanna stick with your approach. this is where you need to change.
if ($validation->fails()) {
return $validation->errors();
}
Give me an idea to call the form fields and controller in the route file and store them into the WHMCS i.e., add the client details to WHMCS. Find below the Route along with the form fields.
Route::get('/create', function () {
$users = Whmcs::AddClient([
'firstname' => Input::get('firstname'),
'lastname' => Input::get('lastname'),
'email' => Input::get('email'),
'address1' => Input::get('address1'),
'city' => Input::get('city'),
'state' => Input::get('state'),
'postcode' => Input::get('postcode'),
'country' => Input::get('country'),
'phonenumber' => Input::get('phonenumber'),
'password2' => Input::get('password2'),
'responsetype' => 'json',
]);
return $users;
});
Find below the controller code
class ClientController extends Controller
{
public function insertform(){
return view('clientlayout.main.signup');
}
public function create(){
$firstname = trim(htmlentities($_POST["firstname"]));
}
}
Perhaps the following may help point you in the right direction:
Adapt to your requirements and place inside your controller.
public function createUser($request)
{
//Create user
$newUser = new User;
$newUser->username = $request->username;
$newUser->first_name = $request->first_name;
$newUser->last_name = $request->last_name;
$newUser->email = $request->email;
$newUser->password = bcrypt($request->password);
$newUser->last_login_at = Carbon::now();
$newUser->save();
//Manually assign the role_id so no escalating privileges.
$newUser->assignRole('user');
return $newUser;
}
First of all you have to follow MVC method in laravel
Route
Route::match(['get','post'],'/create', 'ControllerName#functionname');
controller
public function create(Request $request){
$id = modelname::modelfunctionname($request->Input());
print "<pre>";
print_r ($request->input());
print "</pre>"; exit;
}
$request->input() you will get the form fields
In Your model
public static function modelfunctionname($input){
$create = DB::table('admins')->insertGetId(array(
'firstname' => $input['firstname'],
'lastname' => $input['lastname']
like this Do it for remaining field
));
return $create;
}
I have a Laravel Lumen API. I'm seeing an issue with the update functionality.
In my controller, the code for updating an item is:
public function update(Request $request, $id)
{
$this->validate($request, [
'name' => 'required',
'description' => 'required',
'completed' => 'required',
]);
$todo = Todo::find($id);
$todo->name = $request->name;
$todo->description = $request->description;
$todo->completed = $request->completed;
$todo->save();
return response()->json(['status' => 'success']);
}
I can update the todo item using:
http://lumen-todo.app/api/51?name=test&description=test&completed=1
however was hoping I could send the parameters in a json body, like this
PUT http://lumen-todo.app/api
{
"id": 1
"name": "Test",
"description": "Test",
"completed": 1,
}
For adding items, it works via a json body, so don't understand why it does not work for updates. For info, the 'add item' controller code is here:
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'description' => 'required',
'completed' => 'required'
]);
$todo = new Todo();
$todo->name = $request->name;
$todo->description = $request->description;
$todo->completed = $request->completed;
$todo->save();
return response()->json(['status' => 'success']);
}
If you want to get the json data from request payload, validate and store it, use
public function store(Request $request)
{
$data = $request->json()->all();
$this->validate($data, [
'name' => 'required',
'description' => 'required',
'completed' => 'required'
]);
$resource = $this->model->find($id);
$resource->fill($request);
$resource->save();
return response()->json(['status' => 'success']);
}
Instead of doing this:
$todo = new Todo();
$todo->name = $request->name;
$todo->description = $request->description;
$todo->completed = $request->completed;
$todo->save();
Do, this:
use App\Todo;
protected $model;
public function __construct(Todo $model) {
$this->model = $model;
}
$resource = $this->model->find($id);
$resource->fill($request);
$resource->save();
Also, you can do json_decode() function to change your json params to array and use that to validate and save data.