How to save data when I delete a row or id? - laravel

My form is like this I have four row in database
May admin delete 2 rows or id.
How to save it
public function important_store(SettingRequest $request)
{
$importants = collect([]);
if ($request->importants) {
foreach ($request->helps as $help) {
$model = Important::updateOrCreate([
'title' => $help['title']
], [
'link' => $help['link']
]);
$importants->push($model);
}
}
Help::whereNotIn('id', $importants->pluck('id'))->delete();
return redirect()->back();
}

Related

How to create a validation when importing CSV in Laravel using Maatwebsite?

How to create a validation when importing CSV. I'm using the "maatwebsite/excel": "^3.1" if the imported csv column header name is not exact with the database column it should display some validation. This is my reference LaravelDaily
/
Laravel-8-Import-CSV
Importing CSV
public function parseImport(CsvImportRequest $request)
{
if ($request->has('header')) {
$headings = (new HeadingRowImport)->toArray($request->file('csv_file'));
$data = Excel::toArray(new AwardeesImport, $request->file('csv_file'))[0];
} else {
$data = array_map('str_getcsv', file($request->file('csv_file')->getRealPath()));
}
if (count($data) > 0) {
$csv_data = array_slice($data, 0, 6);
$csv_data_file = CsvData::create([
'csv_filename' => $request->file('csv_file')->getClientOriginalName(),
'csv_header' => $request->has('header'),
'csv_data' => json_encode($data)
]);
} else {
return redirect()->back();
}
return view('admin.import-csv.import-fields', [
'headings' => $headings ?? null,
'csv_data' => $csv_data,
'csv_data_file' => $csv_data_file
])->with('success', 'The CSV file imported successfully');;
}
When parsing CSV
public function processImport(Request $request)
{
$data = CsvData::find($request->csv_data_file_id);
$csv_data = json_decode($data->csv_data, true);
foreach ($csv_data as $row) {
$awardees = new SIS();
foreach (config('app.db_fields') as $index => $field) {
if ($data->csv_header) {
$awardees->$field = $row[$request->fields[$field]];
} else {
$awardees->$field = $row[$request->fields[$index]];
}
}
$awardees->save();
}
return redirect()->action([ImportController::class, 'index'])->with('success', 'Import finished.');
}
CsvImportRequest
public function rules()
{
return [
'csv_file' => 'required|mimes:csv,txt'
];
}
config/app.php
'db_fields' => [
'email_address',
'surname',
'first_name',
'middle_name',
'course',
'year_level',
'contact_number',
'gwa_1st',
'gwa_2nd',
'applying_for',
'remarks',
'comments'
]
if one of those field is missing it should show the validation error

how to perform bulk update with change check in laravel?

I am using laravel, I am using this code in the update function. works fine, but is it possible to save lines of code with bulk insertion?
Example: $product->update($request->all());
But first check if they have sent new data to update.
My Function Update:
public function update(ProductUpdateRequest $request, Product $product)
{
$data = Product::findOrFail($product->id);
$data->category_id = $request->category_id;
$data->name_product = $request->name_product;
$data->description = $request->description;
$data->stock = $request->stock;
$data->price_buy = $request->price_buy;
$data->price_sale = $request->price_sale;
$data->status = $request->status;
if ($data->isDirty()) {
$data->update($request->all());
return response()->json([
'color' => 'green',
'message' => 'CATEGORY EDIT'
]);
} else {
return response()->json([
'color' => 'red',
'message' => 'NO CHANGE DETECTED'
]);
}
}
You can use fill() method to fill the model with data without committing to database. Do the dirty check and then save. Eg:
public function update(ProductUpdateRequest $request, Product $product)
{
$product->fill($request->all()); //no need to use product->find since $product with the id is already injected
if ($product->isDirty()) {
$product->update($request->all()); //or use $product->save(); since model is alraedy filled with new data
return response()->json([
'color' => 'green',
'message' => 'CATEGORY EDIT'
]);
} else {
return response()->json([
'color' => 'red',
'message' => 'NO CHANGE DETECTED'
]);
}
}
Do note that save method actually checks if the model is dirty. So, if you do not want to send custom messages based on whether the model was changed or not, you could just call save() instead of update() without the dirty check.

Insert value in table relationship Laravel

I want to insert some value in db, but I get an error, and I am not sure why.
Trying to get property 'lkp_relationship_correlation' of non-object**
$person = new Person();
foreach ($request->relationship_values as $item) {
$relationship = new Relationship();
$relationship->fill([
'lkp_relationship_correlation_id' => $item->lkp_relationship_correlation,
'relative_fullname' => $item->relatives_surname,
'relative_surname' => $item->relatives_full_name,
'relative_id' => 3,
]);
$relationship->person()->associate($person)->save();
};
public function person()
{
return $this->hasMany(Person::class, 'person_id');
}
public function relationship()
{
return $this->belongsTo(Relationship::class);
}
dd($item);
array:3 [ "lkp_relationship_correlation" => 11 "relatives_surname"
=> "Simona" "relatives_full_name" => "Simona Arabu" ]
Given that $item is an array, you can't do this:
$item->lkp_relationship_correlation
You can access the lkp_relationship_correlation value like:
$item['lkp_relationship_correlation']

Save One-to-Many Relationship in Laravel 6

I have two Table that Transfer and Product that link One-to-Many Relationship. I'm to create relationship between Transfer and Product like Pics Below.
that get Selected Dropdown Product when Click Search.... and When Click Create save relationship Product into Transfers..
My Transfer Model
public function products()
{
return $this->hasMany(\App\Product::class);
}
My Product Model
public function transfer()
{
return $this->belongsTo(\App\Transfer::class);
}
in TransferController
public function store(Request $request)
{
$request->validate([
'from_location' => 'required',
'to_location' => 'required',
'status' => 'required',
'description' => 'nullable',
'shipping_charge' => 'nullable',
]);
$transfer = new Transfer();
$transfer->branch_id = auth()->user()->id;
$transfer->from_location = $request->input('from_location');
$transfer->to_location = $request->input('to_location');
$transfer->status = $request->input('status');
$transfer->shipping_charge = $request->input('shipping_charge');
$transfer->save();
// $products = new Product();
// $products->name = $request->input('')
return response()->json(['created' => true]);
}
I think its a dummy question, but i stuck 3 days with it. I'll appreciate of all Ur help...
You need to post the product_ids to backend that you selected,
and just update the relationship:
...
$transfer->shipping_charge = $request->input('shipping_charge');
$transfer->save();
Product::whereIn('id', $product_ids)->update(['transfer_id' => $transfer->id]);
If your products are all new, you can use saveMany:
$products = array(
new Product(['name' =>'product1', ...]),
new Product(['name' => 'product2', ...])
);
...
$transfer->save();
$transfer->products()->saveMany($products);

Using pluck() helper function in laravel

I'm building a small application on laravel 5.5 where I'm getting a list of multiple users with there information, from the forms as below format:
{
"name":"Test",
"description":"Test the description",
"users":[
{
"value":"XYZabc123",
"name":"Nitish Kumar",
"email":"nitishkumar#noeticitservices.com"
},
{
"value":"MFnjMdNz2DIzMJJS",
"name":"Rajesh Kumar Sinha",
"email":"rajesh#noeticitservices.com"
}
]
}
I just want to get the value key form the users array via laravel collection something like this:
$userIds = $request->users->pluck('value');
so that I can put them into query:
$user = User::all()->whereIn('unique_id', $userIds);
May be I'm doing most of the things wrong but my main motive is to use laravel collection or helper functions and make a cleaner code for this:
$teamData['name'] = $request->name;
$teamData['description'] = $request->description;
$teamData['unique_id'] = str_random();
$users = $request->users;
$team = Team::create($teamData);
if($team)
{
$userIds = [];
foreach ($users as $user)
{
$getUser = User::where('unique_id', $user['value'])->get()->first();
$userIds [] = $getUser->id;
}
$team->users()->attach($userIds);
return response()->json(['message' => 'Created Successfully'], 200);
}
return response()->json(['message' => 'Something went wrong'], 500);
I'm still learning collections, any suggestions is appreciated. Thanks
Data that come from $request (form) isn't a collection. It's an array. If you need it to be collection, you should convert it to collection first.
PS. If you have multiple DB actions in single method, It's good to have DB transaction.
\DB::transaction(function () use ($request) {
// convert it to collection
$users = collect($request->users);
$team = Team::create([
'name' => $request->name,
'description' => $request->description,
'unique_id' => str_random(),
]);
$team->users()->attach($users->pluck('value')->toArray());
});
// HTTP Created is 201 not 200
return response()->json(['message' => 'Created Successfully'], 201);
or you'll need something like this:
return \DB::transaction(function () use ($request) {
$users = collect($request->users);
$team = Team::create([
'name' => $request->name,
'description' => $request->description,
'unique_id' => str_random(),
]);
$team->users()->attach($users->pluck('value')->toArray());
return response()->json([
'message' => 'Created Successfully',
'data' => $team,
], 201);
});
I just want to get the value key form the users array via laravel collection
Just use map then:
$userIds = $request->users->map(function($user) {
return $user->value; // or $user['value'] ? not sure if this is an array
});
Edit:
if $request->users is not a collection, make it one before calling map:
$users = collect($request->users);
$userIds = $users->map(function($user) {
return $user->value; // or $user['value'] ? not sure if this is an array
});

Resources