Dynamically object record Save into database using laravel - php

Respected Sir/Ma'am
I have record in below format and want to save this into
database,the property of this particular object is not similar often, It's changeable,
Sometime it could be more and sometime it could be less
the property of this object is changeable,Sometime it could be
more and sometime it could be less
{
"name":"nabnit jha",
"email":"028nabnit#gmail.com",
"password":"123456",
"c_password":"123456",
"imgUrl":"sonujha.jpg"
}
Simply i will do this if object property is not dynamic
public function insert($data, $modelName)
{
$modelName->name = $data->name;
$modelName->email = $data->email;
$modelName->password = $data->password;
$modelName->img_url = $data->imgUrl;
$modelName->save();
return response()->json([
'message' => "Record Inserted Successfully"
]);
}
what I DO In dynamic case, I use this but not work please help me
public function insert($data, $modelName)
{
foreach ($data as $key => $value) {
$modelName->$key = $value;
}
$modelName->save();
return response()->json([
'message' => "Record Inserted Successfully"
]);
}

data must be array
public function insert($data, $modelName)
{
$modelName->fill($data)->save(); // or use forceFill()
return response()->json([
'message' => "Record Inserted Successfully"
]);
}

If someone has same issue then take $data = $request->input() and use foreach loop
For more detail follow bellow step
Step 1
class SignUp extends Controller
{
//
protected $users;
public function __construct(Crud $crud)
{
$this->users = $crud;
$this->Model = new RegisterSignUp;
}
public function singleUpload(Request $request)
{
$validatedData = Validator::make(
$request->all(),
[
'name' => 'required',
'email' => 'required|email',
'password' => 'required',
'c_password' => 'required|same:password'
]
);
if ($validatedData->fails()) {
return response()->json([
'message' => "Validation Error"
]);
}
$model_name = $this->getModel();
$result = $this->users->insert($request->input(), $model_name);
return $result;
return response()->json([
'message' => "Record Inserted Successfully"
]);
}
public function getModel()
{
return $this->Model;
}
}
Step 2
public function insert($data, $modelName)
{
foreach ($data as $key => $value) {
if ($key != 'c_password') {
$modelName->$key = $value;
}
}
$modelName->save();
return response()->json([
'message' => "Record Inserted Successfully"
]);
}

Related

how to user lumen eloquent updateorcreate function

i'm trying this updateorcreate method and for some reason id does not insert nothing into database, here is my code example, it enters into catch but it does not display any error msg.
public function insertFacturiFluxFurnizor(Request $request)
{
$user = auth()->user();
$idFluxReceptie = $request->input('idFluxReceptie');
$facturi = $request->input('facturi');
try {
foreach ($facturi as $factura) {
$facturiWms = FacturiWms::updateOrCreate([
'codFactura' => $factura['codFactura']
], [
'fluxReceptie' => $idFluxReceptie,
'idFurnizor' => $factura['idFurnizor'],
'fiscalId' => $factura['fiscalId'],
'codFactura' => $factura['codFactura'],
'dataFactura' => $factura['dataFactura'],
'userId' => $user->userId
]);
}
return response()->json(['facturiWms' => $facturiWms, 'message' => 'CREATED'], 201);
} catch (\Exception $e) {
return response()->json(['message' => $e], 409);
}
}
}

Hi i get this "Error Call to a member function update() on boolean" when updating image in Laravel

Can someone help me with this Laravel problem?
I get Error Call to a member function update() on boolean, when I edit and update Image for an ad.
So when I create a new Ad the image will store but when updating the Ad with a new image the old image stays and I get this error for this line in storeImage.
private function storeImage($ad){
if (request()->has('image')) {
$ad->update([
'image' => request()->image->store('uploads', 'public'),
]);
$image = Image::make(public_path('storage/' . $ad->image))->fit(300, 300, null, 'top-left');
$image->save();
}
}
This is my AdsController
public function edit($id)
{
$ad = Ad::find($id);
return view('ads.edit_ad', compact('ad', 'id'));
}
public function update(Request $request, $id)
{
$ad = Ad::find($id);
$user_id = Auth::user()->id;
$rules = [
'ad_title' => 'required',
'ad_description' => 'required',
'purpose' => 'required',
'image' => 'sometimes|file|image|max:5000',
];
$this->validate($request, $rules);
$title = $request->ad_title;
$is_negotialble = $request->negotiable ? $request->negotiable : 0;
$data = [
'title' => $request->ad_title,
'description' => $request->ad_description,
'type' => $request->type,
'price' => $request->price,
'purpose' => $request->purpose,
'address' => $request->address,
'user_id' => $user_id,
];
$updated_ad = $ad->update($data);
if ($updated_ad){
$this->storeImage($updated_ad);
}
return redirect()->back()->with('success','Ad Updated');
}
public function destroy(Ad $ad)
{
$ad->delete();
return redirect()->back()->with('success','Ad Deleted');
}
/**
* Listing
*/
public function listing(Request $request){
$ads = Ad::all();
$roles = Role::all();
return view('listing', compact('ads'));
}
public function myAds(){
$user = Auth::user();
$ads = $user->ads()->orderBy('id', 'desc')->paginate(20);
return view('ads.my_ads', compact('ads'));
}
private function storeImage($ad){
if (request()->has('image')) {
$ad->update([
'image' => request()->image->store('uploads', 'public'),
]);
$image = Image::make(public_path('storage/' . $ad->image))->fit(300, 300, null, 'top-left');
$image->save();
}
}
At the bottom of your update() function, try to change this:
if ($updated_ad){
$this->storeImage($updated_ad);
}
to this:
if ($updated_ad){
$this->storeImage($ad);
}
The Eloquent models update() function returns a boolean of whether the update completed successfully. After running the update() function on the $ad variable, it is mutated and contains the updated data, and you can use it as an argument in your storeImage() function.

Lumen count(): Parameter must be an array or an object that implements Countable

I tried creating a multiple image upload along with a post, but I constantly get an error on count function when I try to count the elements in the array. For the single image, the code works fine if I remove that array and counts. Lumen latest version, PHP version 7.3 but I downgraded it to 7.1.
Code:
<?php
class PostController extends Controller {
public function __construct() {
$this->middleware('auth');
}
public function index() {
return Auth::user()->post;
}
public function show($post_id) {
$post = Post::findOrFail($post_id);
if (Auth::user()->id !== $post->user_id) {
return response()
->json(['status' => 'error', 'message' => 'unauthorized'], 401);
}
return $post;
}
public function store(Request $request) {
$post = new Post;
$post->setConnection('mysql1');
$user = User::where('token', $request->token)
->first();
if ($user) {
$post1 = $post->create(['post_id' => rand() , 'title' => $request->title, 'cooked_time' => $request->cooked_time, 'user_id' => $request->token, 'location' => $user['name'], 'dispose_time' => strtotime('+01 hours', strtotime($request->cooked_time)) , 'food_type' => $request->food_type, 'description' => $request->description, 'serve_quantity' => $request->serve_quantity, 'lat' => $request->lat, 'long' => $request->long, ]);
$post = Post::where('user_id', $request->token)
->orderBy('id', 'DESC',)
->limit('1')
->get();
if ($request->hasFile('image')) {
// $image_array = [];
$image_array = $request->file('image');
$array_len = count($image_array);
for ($i = 0;$i < $array_len;$i++) {
$image_size = $image_array[$i]->getClientSize();
$image_ext = $image_array[$i]->getClientOriginalExtension();
$new_image_name = rand(123456, 99999999) . "." . $image_ext;
if (!function_exists('public_path')) {
/**
* Return the path to public dir
*
* #param null $path
*
* #return string
*/
function public_path($path = null) {
return rtrim(app()->basePath('public/' . $path) , '/');
}
}
$destination_path = public_path('/images');
$image_array[$i]->move($destination_path, $new_image_name);
$image = new PostImage;
$images->image_name = $new_image_name;
$images->post_id = $post1['post_id'];
$images->save();
}
}
return response()
->json(['message' => 'success', 'user' => $user['name'], 'post' => $post1, ], 200);
}
}
public function update(Request $request, $post_id) {
$post = Board::find($post_id);
if (Auth::user()->id !== $post_id->user_id) {
return response()
->json(['status' => 'error', 'message' => 'unauthorized'], 401);
}
$post->update($request->all());
return response()
->json(['status' => 'success', 'post' => $post], 200);
}
public function destroy($id) {
$post = Post::find($post_id);
if (Auth::user()->id !== $post->user_id) {
return response()
->json(['status' => 'error', 'message' => 'unauthorized'], 401);
}
if (Post::destroy($id)) {
return response()->json(['status' => 'success', 'message' => 'Post Deleted Successfully'], 200);
}
return response()
->json(['status' => 'error', 'message' => 'Something Went Wrong']);
}
}
http://php.net/manual/en/migration72.incompatible.php#migration72.incompatible.warn-on-non-countable-types
Try to change
count($image_array)
To
count((is_countable($image_array)?$image_array:[]))
And use this trick for all count() calls

Add Items using CSV file - Laravel

I am able to save products into my groups using the group id using the save function
but now i want to do that using an excel file. I am having issues with how to do that. Any help will be appreciated. Thank you.
Controller
public function save($id, Request $request)
{
$group = Group::whereId($id)->firstorFail();
$product = new Product(array(
'name' => $request->get('name'),
'price' => $request->get('price'),
));
$group->products()->save($product);
}
public function import($id, Request $request)
{
$group = Group::whereId($id)->firstorFail();
if($request->file('imported-file'))
{
$path = $request->file('imported-file')->getRealPath();
$data = Excel::load($path, function($reader)
{
})->get();
if(!empty($data) && $data->count())
{
foreach ($data->toArray() as $row)
{
if(!empty($row))
{
$dataArray[] =
[
'name' => $row['name'],
'price' => $row['price'],
];
}
}
if(!empty($dataArray))
{
Item::insert($dataArray);
}
}
}
}
Route
Route::post('import/{id?}', 'ItemController#import');
Model for Product
Product
public function groups()
{
return $this->belongsToMany('App\Group','group_product','product_id','group_id')
->withTimestamps();
}
Model for group
Group
public function products()
{
return $this->belongsToMany('App\Product','group_product','group_id','product_id')
}
You need saveMany
$dataArray[] =
new App\Product([
'name' => $row['name'],
'price' => $row['price'],
]);
$group->products()->saveMany($dataArray);

store other data in signup function Laravel 5.3

I'm modifying the signup function that store user's data( email and password). I wish to include more data such as phone number, name and national ID. I tried but in mysql database it doesn't show anything. Here is what I have done :
public function signup(Request $request)
{
$credentials = $request->only([
'national_id' ,
'name' ,
'phone',
]);
$validator = Validator::make($credentials, [
'name' => 'required',
'email' => 'sometimes|email|unique:users',
'password' => 'sometimes|min:6|confirmed',
'password_confirmation' => 'sometimes|min:3',
'national_id' => 'required','unique:national_id',
]);
if ($validator->fails()) {
throw new ValidationHttpException($validator->errors()->all());
}
try {
$user = $this->users->create($request->except('roles', 'permissions'));
if (!$user->id) {
return $this->response->error('could_not_create_user', 500);
}
$hasToReleaseToken = Config::get('boilerplate.signup_token_release');
if ($hasToReleaseToken) {
$user->national_id = $request->national_id;
return $this->login($request);
}
return $this->response->created();
} catch (\Exception $e) {
return $this->response->error($e->getMessage(), 500);
}
}
when I dd($request->national_id it shows me the national_id data in postman, but in my database it's NULL.

Categories