Laravel return value of updating a model - laravel

what I want to do is when the update is done, the data of the whole Model is returned.
I am registering and updating the database.
what i want when the data is updated i want it to return me all the data.
return response()->json($category);
the return returns 1, what I want to do is show the updated data instead of 1
$category = Category::where('id', $id)->update([
'title' => $request->title,
'slug' => $request->slug,
'is_home' => $request->is_home,
'language' => $request->language,
'status' => $request->status,
]);
return response()->json($category);

Create an instance of your object Category and save, that should work
$category = Category::find($id);
$category->title = $request->title;
$category->slug = $request->slug;
$category->is_home = $request->is_home;
$category->language = $request->language;
$category->status = $request->status;
$category->save();
return response()->json($category);
The return of the update() method is a boolean, not the object.

Related

Laravel store (nullable validation error)

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.

why my updateOrInsert doesn't work laravel

I use updateOrInsert to avoid duplicate data, why doesn't the Update function work and always insert data?
foreach($datas as $data){
DB::table('users')->updateOrInsert([
'user_connect_id' => $user->connect_id,
'description' => $data['description'],
'created_by' => $login->name,
'modified_by' => $login->name,
'created_at' => Carbon::now(),
]);
}
Check out [updateOrInsert] this documentation (https://laravel.com/api/6.x/Illuminate/Database/Query/Builder.html#method_updateOrInsert). You need two parameters. One is the matching attributes (i.e., the attributes you would use to identify your record in case it exists), the other is your array (the new values you wish to insert or update the record with).
updateOrInsert(array $attributes, array $values = [])
Example
DB::table('users')->updateOrInsert(
[
'user_connect_id' => $user->connect_id
],
[
'user_connect_id' => $user->connect_id,
'description' => $data['description'],
'created_by' => $login->name,
'modified_by' => $login->name,
'created_at' => Carbon::now(),
]);
There are two arguments in updateOrInsert method.The updateOrInsert method accepts two arguments: an array of conditions by which to find the record, and an array of column and value pairs containing the columns to be updated.
For e.g :
DB::table('users')
->updateOrInsert(
['email' => 'john#example.com', 'name' => 'John'],
['votes' => '2']
);
Check this link for syntax : Laravel Doc
// Inseart code
public function create()
{
return view('admin.category.create');
}
public function store(Request $request)
{
$this->validate($request,[
'name' => 'required'
]);
$category = new Category();
$category->name = $request->name;
$category->slug = str_slug($request->name);
$category->save();
Toastr::success('Category Successfully Saved','Success');
return redirect()->route('admin.category.index');
}
// Update code
public function edit($id)
{
$category =Category::find($id);
return view('admin.category.edit',compact('category'));
}
public function update(Request $request, $id)
{
$this->validate($request,[
'name' => 'required|unique:categories'
]);
$category = Category::find($id);
$category->name = $request->name;
$category->slug = str_slug($request->name);
$category->save();
Toastr::success('Category Successfully Updated','Success');
return redirect()->route('admin.category.index');
}

"Creating default object from empty value"

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

what could be wrong as there is no error displayed and the code isn't processed: enum in Laravel

Migration
In my migration, I have following passed to the database
$table->enum('product_name', ['chocolate', 'Candy','biscuits', 'Berry']);
$table->string('description');
$table->string('product_no');
$table->timestamps();
in my model I have this below the fillable and a function to select a choice.
protected $fillable =[
'product_no','description'
];
protected $product_name = ['chocolate', 'Candy','biscuits', 'Berry'];
public function getProduct_name()
{
return $this->product_name;
}
The problem is I don't know how to handle this in controller and Postman. It is not displaying any error
public function store(Request $request)
{
$this->validate($request, [
'product_no' => 'nullable|product_no',
'description' => 'required|string',
]);
$product = new Product();
$product->product_no = $request->product_no;
$product->description = $request->description;
$product->product_name = $request->$model->getProduct_name();
if (auth()->user()->products()->save($product))
return response()->json([
'success' => true,
'data' => $product->toArray()
]);
else
return response()->json([
'success' => false,
'message' => 'product could not be added'
], 500);
}
What I intend to achieve is to create a front-end in Angular with a drop down to select the product_name (from the list hard-coded) and description and product_no are fillable. However from Postman, I just entered the values for the three fields i.e. product_name, description and product_no
It seems you forgot to replace method and variable names when you copy the votes code
$product = new Product();
$product->product_no = $request->product_no;
$product->description = $request->description;
$product->product_name = $request->$model->getProduct_name();
if (auth()->user()->votes()->save($vote))
--------------------^^^^^^^-------^^^^^--
return response()->json([
'success' => true,
'data' => $product->toArray()
]);
That should be
if (auth()->user()->products()->save($product))
Also there is another field (product_name) that you're trying to save but it's not fillable.
protected $fillable =[
'product_no','description', 'product_name'
];
And also, you may want to consider that using same pattern when naming your variables and methods. You can say getProductName or get_product_name instead of getProduct_name.

How to call the form fields in a route file in laravel

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;
}

Resources