How insert statement works in open source akaunting script? - laravel

I have downloaded an open source accounting script from akaunting.com. This source code is developed in Laravel. I am trying to add one more field in the items table, but I am not able to find the insert statement in this script.
Here is the controller code. After this I am not getting any idea.
public function store(Request $request)
{
$item = Item::create($request->input());
// Upload picture
if ($request->file('picture')) {
$media = $this->getMedia($request->file('picture'), 'items');
$item->attachMedia($media, 'picture');
}
$message = trans('messages.success.added', ['type' => trans_choice('general.items', 1)]);
flash($message)->success();
return redirect()->route('items.index');
}

After a long search I got the solution.
In app/models/common/item.php we can add extra fields. The text box name and database column name should be the same.
protected $fillable = ['company_id', 'name', 'sku', 'description', 'sale_price', 'purchase_price', 'quantity', 'category_id', 'tax_id', 'enabled','expiry_date'];

Related

Data that has been edited is not updated into database

i had some problem for updating my data, i was able to catch the file that was going to be updated by using dd and they are there, but when i was submitting the form the data remains the same, nothing change and no error whatsoever, here are my store(update) controller :
public function store(Request $request)
{
//dd($request);
$request->validate([
'attachment_name' => 'required|file|image|mimes:jpeg,png,jpg,gif,svg|max:10048',
]);
$storedImage = $request->attachment_name->store('public/image/');
MediaOrder::updateOrCreate(['id' => $request->id],
[
'nomor'=> $request->nomor,
'nomor_reference'=> $request->nomor_reference,
'periode_start'=> $request->periode_start,
'periode_end'=> $request->periode_end,
'category_id'=> $request->category_id,
'type_id'=> $request->type_id,
'agency_code'=> $request->agency_code,
'agency_name'=> $request->agency_name,
'advertiser_code'=> $request->advertiser_code,
'advertiser_name'=> $request->advertiser_name,
'brand_code'=> $request->brand_code,
'brand_name'=> $request->brand_name,
'nett_budget'=> $request->nett_budget,
'gross_value'=> $request->gross_value,
'nett_cashback'=> $request->nett_cashback,
'nett_bundling'=> $request->nett_bundling,
'version_code'=> $request->version_code,
'spot'=> $request->spot,
'accountexecutive_name'=> $request->accountexecutive_name,
'group_id'=> $request->group_id,
'userto_name'=> $request->userto_name,
'notes'=> $request->notes,
'attachment_name'=> $storedImage,
]);
flash_success_store('Media Order successfully updated.');
if ($request->ajax()) {
return redirect_ajax_notification('media-order.index');
} else {
return redirect_ajax('media-order.index');
}
}
i already find and change it myself but to no avail, maybe someone can have a solution?, thank you for your time.
The most common reason that the model is not updated or entered is that you do not make the attributes fillable in the model itself. Go to your model MediaOrder and check if you have set all attributes fillable.
protected $fillable = [..];

Cannot insert data in laravel 8

I want to insert data into order table, but the data is not inserted into the database. My code is as follows, there is no error shown. How to fix it?
$saveorder= new Order;
$saveorder->customer_id = $request->input('customer_id');
$saveorder->vendor_id = $request->input('vendor_id');
$saveorder->order_date= Carbon::now()->isoFormat('YYYY-MM-DD');
$saveorder->pickup_date=$request->input('pickup_date');
$saveorder->order_status="Pending";
$saveorder->shipping_address=$request->input('shipping_address');
$saveorder->amount=$request->input('amount');
$saveorder->payment=$request->input('payment');
$saveorder->delivery_method=$request->input('delivery_method');
$saveorder->delievery_fee=5.00;
$saveorder->order_notes=$request->input('order_notes');
$saveorder->save();
modelBelow is order model.
use HasFactory;
protected $table = 'order';
protected $guarded = ['id'];
protected $fillable = [
'order_date',
'pickup_date',
'order_status',
'shipping_address',
'amount',
'payment',
'delivery_method',
'delivery_fee',
'phone',
'order_notes',
'customer_id',
'vendor_id',
];
protected $casts = [
'id' => 'integer',
];
migration Below are my migration file.
Schema::create('order', function (Blueprint $table) {
$table->increments('id');
$table->date('order_date');
$table->date('pickup_date');
$table->string('order_status');
$table->string('shipping_address');
$table->decimal('amount', 10, 2);
$table->string('payment');
$table->string('delivery_method');
$table->string('delivery_fee');
$table->string('phone');
$table->string('order_notes');
$table->unsignedInteger('customer_id');
$table->unsignedInteger('vendor_id');
$table->timestamps();
});
No error is shown, laravel save() function does not work.
You need to debug your code a bit. Follow the steps below.
First, update your blade file by adding below code. This will display all the errors related to validation
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Second, wrap your method to save the data in try-catch block. It will show you all errors related to your code inside the function to save the data.
try {
// your code goes here
} catch (Exception $e) {
info($e->getMessage());
}
$saveorder= new Order();
$saveorder->customer_id = $request->customer_id;
$saveorder->vendor_id = $request->vendor_id;
$saveorder->order_date= Carbon::now()->isoFormat('YYYY-MM-DD');
$saveorder->pickup_date=$request->pickup_date;
$saveorder->order_status="Pending";
$saveorder->shipping_address=$request->shipping_address;
$saveorder->amount=$request->amount;
$saveorder->payment=$request->payment;
$saveorder->delivery_method=$request->delivery_method;
$saveorder->delievery_fee=5.00;
$saveorder->order_notes=$request->order_notes;
$saveorder->save();
you should use create function its good solution and clean code and give it validated input
or collect all in new var and pass it to function create
save method it's used commonly with case update object not with insert new object in database finally make dd() for the request to ensure all inputs you are inserting are come in request and ensure data type in the database compatible
This is a proper way to save data.
// validate if you need
$data = $request->validate([
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
// otherwise
$data = $request->all();
// then add extra fields
$data['order_date'] = Carbon::now()->isoFormat('YYYY-MM-DD');
$data['order_status'] = "Pending";
$data['delievery_fee'] = 500;
// and save
Order::create($data);
class Order extends Model
{
public $guarded = []; // make sure you validate the data if you use this. and remove $protected if you have.
}

Laravel 6 validate multiple columns

Using the following code to create and update records with Laravel 6, how to add a unique validation that combines 'iso' and 'division' columns must unique, for both update and create? Also how to update the 'updated_at' column automatically without 'touch' it?
public function upsert(Request $request)
{
$this->authorize('manage','App\Admin\Division');
$this->validate($request,[
'records.iso' => 'required|regex:/^[A-Z]{2}$/',
'records.division' => 'required|min:2|max:3',
'records.remarks' => 'min:2|max:255|string|nullable',
],
[ 'records.iso.required'=>'Country iso Requied',
'records.iso.regex'=>'Country iso format : AA',
'records.division.required'=>'Division Code must entered',
'records.division.min'=>'Division Code minimum 2 characters',
'records.division.max'=>'Division Code maximum 3 characters',
],
);
$validatedData = $request->records;
if($validatedData['id']){ // have id, old record -> update
Division::where('id', $validatedData['id'])->update($validatedData);
//*******/ To correct updated_at no auto updated
$results = Division::find($validatedData['id']);
$results->touch();
//****** */ End of correction
}else{ // no id -> create record
$validatedData['auth'] = Auth::id();
$results = Division::create($validatedData);
}
return ['divisions' => $results];
}
All the validation rules apply for each field, i think you can do a foreach to workaround and compact the code, something like:
foreach ($records as $key => $record) {
$fields['record'.$key] = 'iso', 'division';
$rules['record'.$key] = 'required|min:2';
}
$validator = Validator::make($fields, $rules);
In the rules array you can put all the shared rules, but you have to create the other complex validation rules after this, so i think that your validation now is just fine.
And with the updated_at field, use the updateOrCreate
$results = Division::updateOrCreate(
['id', $validatedData['id'],
[$validatedData]
);
Adapt the above example for your code.

How to display multiple images that stored as array in laravel?

please help me to display image that stored as array in database
my controller:
( filename is my image column name in database)
public function store(Request $request)
{
$this->validate($request, [
'filename' => 'required',
'filename.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
// Start multiple image upload code
if($request->hasfile('filename'))
{
foreach($request->file('filename') as $image)
{
$name=$image->getClientOriginalName();
$image->move(public_path().'/images/', $name);
$data[] = $name;
}
}
// End multiple image upload code
$houses= new House();
$houses->division = $request->input('division');
$houses->city = $request->input('city');
$houses->area = $request->input('area');
$houses->owner_name = $request->input('owner_name');
$houses->house_name = $request->input('house_name');
$houses->type = $request->input('type');
$houses->from = $request->input('from');
$houses->rent = $request->input('rent');
$houses->phone = $request->input('phone');
$houses->address = $request->input('address');
$houses->description = $request->input('description');
$houses->filename=json_encode($data); **// This for image upload**
$houses->save();
return back()->with('success', 'Your House has been successfully');
}
image column
First array cast the filename column in your model. For more: Array & JSON Casting
protected $casts = [
'filename' => 'array',
];
After that, whenever you fetch filename from House model, laravel will automatically convert the json data to array. Loop through the array and display the images.
$house = House::find(1);
foreach($house->filename as $filename) {
echo public_path().'/images/', $filename;
}
If you want to retrieve then display the images stored as an array what I'd suggest is casting the filename attribute to json/array in the model.
You can do that in your House model like this:
class House extends Model
{
protected $casts = [
'filename' => 'array',
];
}
To display it in a view you can loop through the casted array:
#foreach($house->filename as $image)
<img src="{{ url('link/to/assets/') . $image }}"
#endforeach
See more in the docs about casting here:
https://laravel.com/docs/5.7/eloquent-mutators#array-and-json-casting
A side point on image uploads, you may want to give uploaded files a unique name rather than using the user's filename so there's no conflict if a user uploads a document with the same name twice.
Laravel handles this all for you in the store() method seen here: https://laravel.com/docs/5.7/requests#storing-uploaded-files. You can create your own names if preferred using storeAs().

how sluggify a model with cviebrock slugs laravel

I just ran into a simple problem.
I just installed this package and I wish to sluggify the entire model.
I have upgraded m model definition as instructed:
protected $sluggable = array(
'build_from' => 'fullname',
'save_to' => 'slug',
);
public function getFullnameAttribute()
{
return $this->firstnames . '-' . $this->surname;
}
But now I am lost...
how to sluggify all the records in my table?
Ok, I know.
As the package's author wrote in readme.md, each record can be reslugged on save.
So I came op with this crude but working solution:
in my index method:
$object = Author::get();
foreach($object as $o)
{
$o->save();
}

Resources