How to Create Multiple input with laravel API? - laravel

I want to make an report API with the option of being able to do multiple inputs for violators data, crime scene photo data and personnel data.
I've tried to code like below, but still can't do multiple input. What is the correct way to create multiple inputs in laravel API (with file upload) ?
Controller
public function store(ReportRequest $request)
{
try {
$report = Report::create([
'category_id' => $request->category_id,
'user_id' => Auth::user()->id,
'title' => $request->title,
'description' => $request->description,
'incident_date' => $request->incident_date,
'injured_victims' => $request->injured_victims,
'survivors' => $request->survivors,
'dead_victims' => $request->dead_victims,
'location' => $request->location,
'latitude' => $request->latitude,
'longitude' => $request->longitude
]);
if ($request->category_id !== 4 && $request->violator_photo) {
$violators = $request->file('violator_photo');
$violators = [];
foreach($violators as $key => $value) {
if($request->hasFile('violator_photo')) {
$violator_photo = $request->hasFile('violator_photo');
$fileName = time().'_'.$violator_photo[$key]->getClientOriginalName();
$filePath = $violator_photo[$key]->storeAs('images/pelanggar', $fileName, 'public');
}
$data = new Violator();
$data->report_id = $report->id;
$data->name = $request->violator_name[$key];
$data->photo = $filePath[$key];
$data->age = $request->violator_age[$key];
$data->phone = $request->violator_phone[$key];
$data->save();
}
}
$files = $request->file('crime_scene_photo');
$files = [];
foreach($files as $key => $value) {
if($request->hasFile('crime_scene_photo')) {
$crime_scene_photo = $request->hasFile('crime_scene_photo');
$name = time().'_'.$crime_scene_photo[$key]->getClientOriginalName();
$path = $crime_scene_photo[$key]->storeAs('images/tkp', $name, 'public');
}
$data = new CrimeScenePhoto();
$data->report_id = $report->id;
$data->path = $path[$key];
$data->caption = $request->caption[$key];
$data->save();
}
if (\Auth::user()->unit_id == 2 && $request->personel) {
foreach ($request->personel as $key => $value) {
$report->members()->sync($request->personel[$key]);
}
}
return response()->json([
'status' => '200',
'message' => 'success',
'data' => [
$report,
$request->all()
],
]);
} catch (\Exception$err) {
return $this->respondInternalError([$err->getMessage(), $request->all()]);
}
}
And here is how I tested in postman.

Solved. i changed my code to like this and it work.
public function store(ReportRequest $request)
{
try {
$report = Report::create([
'category_id' => $request->category_id,
'user_id' => Auth::user()->id,
'title' => $request->title,
'description' => $request->description,
'incident_date' => $request->incident_date,
'injured_victims' => $request->injured_victims,
'survivors' => $request->survivors,
'dead_victims' => $request->dead_victims,
'location' => $request->location,
'latitude' => $request->latitude,
'longitude' => $request->longitude
]);
if ($request->hasFile('violator_photo')) {
foreach($request->file('violator_photo') as $key => $value) {
$vio_photo = $request->file('crime_scene_photo');
$fileName = time().'_'.$vio_photo[$key]->getClientOriginalName();
$filePath = $vio_photo[$key]->storeAs('images/pelanggar', $fileName, 'public');
Violator::create([
'report_id' => $report->id,
'name' => $request->violator_name[$key] ?? null,
'photo' => $filePath ?? null,
'age' => $request->violator_age[$key] ?? null,
'phone' => $request->violator_phone[$key] ?? null
]);
}
}
if ($request->hasFile('crime_scene_photo')) {
foreach($request->file('crime_scene_photo') as $key => $value) {
$crime_scene_photo = $request->file('crime_scene_photo');
$name = time().'_'.$crime_scene_photo[$key]->getClientOriginalName();
$path = $crime_scene_photo[$key]->storeAs('images/tkp', $name, 'public');
CrimeScenePhoto::create([
'report_id' => $report->id,
'path' => $path ?? null,
'caption' => $request->caption[$key] ?? null
]);
}
}
if (\Auth::user()->unit_id == 2 && $request->personel_id) {
foreach ($request->personel_id as $key => $value) {
$report->members()->attach($request->personel_id[$key]);
}
}
return response()->json([
'status' => '200',
'message' => 'success',
'data' => [
$report, $report->members, $report->violators, $report->photos
],
]);
} catch (\Exception$err) {
return $this->respondInternalError([$err->getMessage(), $request->all()]);
}
}

Related

Upload image using CodeIgniter 4

PLease help me on how to upload image in the folder and the same time in the database with a random name.
There's an error: Call to a member function getName() on null.
Heres my code in controller
`public function actionInsert()
{
$destination = new DestinationModel();
$name=$this->request->getVar('name');
$place=$this->request->getVar('place');
$location=$this->request->getVar('location');
$category=$this->request->getVar('category');
$description=$this->request->getVar('description');
$latitude=$this->request->getVar('latitude');
$longitude=$this->request->getVar('longitude');
$image=$this->request->getFile('image');
$imageName = $image->getName();
$image->move('im/destination', $imageName);
if($place == 'Calapan City')
{
$place = 'Calapan';
}else if($category == 'Destination')
{
$category ='Destination';
}
$data = [
'name' => $name,
'place' => $place,
'location' => $location,
'category' => $category,
'image' => $place. '/'. $imageName,
'description' => $description,
'latitude' => $latitude,
'longitude' => $longitude
];
$destination->save($data);
return view('adding_place');
}`

laravel multiple images update function

i am new for laravel, i am not able to save the files in database on update function can any one help me for this,I have two related tables where one is a ticekt table and the other a one a documents table. In the documents table are the columns id, doc_name,doc_path,user_id and service_id. I'm trying to edit multiple images when editing a service. documents table not updating remaining things update successful
Cread service code
public function store(Request $request)
{
$rules = [
'email' => 'required|string|max:255',
'typeofservice' => 'required',
'companyname' => 'required',
'representative'=> 'required',
'phone' => 'required',
'services' => 'required',
'applicant' => 'required',
//'document' => 'required',
//'document.*' => 'required',
'remark' => 'required',
];
$validator = Validator::make($request->all(),$rules);
if($validator->fails()){
return back()->with('warning','please Fill manadatory fields');
} else {
//$dates = ;
//dd($dates);
$ticket = new Ticket([
'user_id' => Auth::user()->id,
'ticket_id' => strtoupper(str_random(10)),
'email'=>$request->input('email'),
'typeofservice' => $request->input('typeofservice'),
'companyname' => $request->input('companyname'),
'representative' => $request->input('representative'),
'phone' => $request->input('phone'),
'services' => $request->input('services'),
'applicant' => $request->input('applicant'),
'remark' => $request->input('remark'),
'ticket_submit_date' => date('d-M-Y'),
'status' => "1",
]);
//dd($ticket);
$ticket->save();
$userId = Auth::id();
$last_id = DB::getPdo()->lastInsertId();
if($ticket) {
if($request->hasfile('documents')) {
foreach($request->file('documents') as $doc)
{
$name = $doc->getClientOriginalName();
$destinationPath = 'public/documets/';
$documentPath = date('YmdHis') . "." . $doc->getClientOriginalExtension();
$doc->move($destinationPath, $documentPath);
Document::create([
'doc_name' => $name,
'doc_path' => $documentPath,
'user_id' => $userId,
'ser_id' => $last_id,
]);
}
}
//return $last_id;
$ticket_details = DB::table('ticket')->where('id','=',$last_id)->first();
$users = User::where('id','=',$ticket_details->user_id)->first();
$ticketid = $ticket_details->ticket_id;
$username = $users->first_name.' '.$users->last_name;
$mdata = ['ticketid'=>$ticketid,'name'=>$username];
$user['to']= $users->email;
Mail::send('emails.user_create_application',$mdata,function($message) use ($user){
$message->to($user['to']);
$message->subject('User Create Application');
});
return back()->with("success","Service Requiest Created Successfully! your tracking id:#$ticket->ticket_id" );
}
}
}
For uddate function given below
public function udateuserticket(Request $request, $id){
$rules = [
'email' => 'required|string|max:255',
'typeofservice' => 'required',
'companyname' => 'required',
'representative'=> 'required',
'phone' => 'required',
'services' => 'required',
'applicant' => 'required',
//'document' => 'required',
//'document.*' => 'required',
'remark' => 'required',
];
$email = $request->email;
$typeofservice = $request->typeofservice;
$companyname = $request->companyname;
$representative = $request->representative;
$phone = $request->phone;
$services = $request-> services;
$applicant = $request->applicant;
$remark = $request->remark;
$updateuserticket = Ticket::where('id','=',$id)->update([
'email' => $email,'typeofservice' =>$typeofservice, 'companyname' => $companyname, 'representative' => $representative,'phone' => $phone,'services' => $services, 'applicant' => $applicant, 'remark' => $remark ]);
$userId = Auth::id();
$last_id = DB::getPdo()->lastInsertId();
if($updateuserticket){
if($request->hasfile('documents')) {
foreach($request->file('documents') as $doc)
{
$name = $doc->getClientOriginalName();
$destinationPath = 'public/documets/';
if(File::exists($destinationPath)){
File::delete($destinationPath);
}
$documentPath = date('YmdHis') . "." . $doc->getClientOriginalExtension();
$doc->move($destinationPath, $documentPath);
Document::create([
'doc_name' => $name,
'doc_path' => $documentPath,
'user_id' => $userId,
'ser_id' => $last_id,
]);
}
}
$ticket_details = DB::table('ticket')->where('id','=',$last_id)->first();
//$users = User::where('id','=',$ticket_details->user_id)->first();
//$ticketid = $ticket_details->ticket_id;
//$username = $users->first_name.' '.$users->last_name;
return redirect('showtickets')->with('success','Ticket Updated Successfully!');
}
}
for view
#foreach( $documents as $doc )
<div class="col-md-6">
<input id="documents" type="file" class="form-control" name="documents[]" value="" required>
<img src="{{ url('/') }}/public/documets/{{ $doc->doc_path }}" alt="user-img" class="img-width" style="width:30px;height:30px;">
</div>
#endforeach
This one update only details not able to update documents can you please guid anyone where i am wrong

Error column not found, but I did not declare the column?

I'm inserting a record to a polymorphic imageable table, however it says column thread_id not found. I have not declared this thread_id column and I don't know where it's pulling it from. Here is the code it's trying to run.
protected static function bootRecordImage()
{
if (auth()->guest()) return;
foreach (static::getMethodToRecord() as $event) {
static::$event(function ($model) use ($event) {
$body = request()->body;
preg_match_all('/<img .*?(?=src)src=\"([^\"]+)\"/si', $body, $matches);
$images = $matches[1];
if($event == 'created') {
foreach ($images as $image) {
$model->images()->create([
'user_id' => auth()->id(),
'imageable_id' => $model->id,
'imageable_type' => get_class($model),
'path' => $image
]);
}
}
if($event == 'deleting') {
foreach ($images as $image) {
$model->images()->delete([
'user_id' => auth()->id(),
'imageable_id' => $model->id,
'imageable_type' => get_class($model),
'path' => $image
]);
if (File::exists(public_path($image))) {
File::delete(public_path($image));
}
}
}
});
}
}
My store method:
public function store(Request $request, Channel $channel, Spam $spam)
{
if (!auth()->user()) {
return back()->withInput()->with('flash', 'Sorry! You must be logged in to perform this action.');
}
if (!auth()->user()->confirmed) {
return back()->withInput()->with('flash', 'Sorry! You must first confirm your email address.');
}
$this->validate($request, [
'title' => 'required',
'body' => 'required',
'channel_id' => 'required|exists:channels,id',
'g-recaptcha-response' => 'required'
// yes it's required, but it also needs to exist on the channels model, specifically on the id
]);
$response = Zttp::asFormParams()->post('https://www.google.com/recaptcha/api/siteverify', [
'secret' => config('services.recaptcha.secret'),
'response' => $request->input('g-recaptcha-response'),
'remoteip' => $_SERVER['REMOTE_ADDR']
]);
// dd($response->json());
if (! $response->json()['success']) {
throw new \Exception('Recaptcha failed');
}
$spam->detect(request('title'));
$spam->detect(request('body'));
$thread = Thread::create([
'user_id' => auth()->id(),
'channel_id' => request('channel_id'),
'title' => request('title'),
'body' => request('body'),
//'slug' => str_slug(request('title'))
]);
return redirect('/forums/' . $thread->channel->slug . '/' . $thread->slug);
}
As you can see, no where is a thread_id mentioned, yet in the error it looks like it's trying to insert into a thread_id column that I've never declared.
Thanks for reading.
I put the polymorphic relation in the model and the trait. Remove it from the Model and you're good to go.

Cannot use object of type Gloudemans\Shoppingcart\CartItem as array

I save image in database as array ["product-04.jpg"]. I don't know how to display image to view. I used Crinsane/LaravelShoppingcart and got the following error: "Cannot use object of type Gloudemans\Shoppingcart\CartItem as array". Can everyone help me?
ProductController I saved image in db:
if($request->hasFile('images')){
$files = $request->file('images');
$extension = ['png','jpg','gif','jepg'];
foreach ($files as $key => $item) {
$nameFile = $item->getClientOriginalName();
$exFiles = $item->getClientOriginalExtension();
if(in_array($exFiles, $extension)){
$item->move(public_path().'/upload/images',$nameFile);
$arrNameFile[] = $nameFile;
}
}
}
if($arrNameFile){
$dataInsert = [
'name_product' => $nameProduct,
'categories_id' => json_encode($categories),
'colors_id' => json_encode($colors),
'sizes_id' => json_encode($sizes),
'brands_id' => $brand,
'price' => $price,
'qty' => $qty,
'description' => $description,
'image_product' => json_encode($arrNameFile),
'sale_off' => $sale,
'status' => 1,
'view_product' => 0,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => null
];
if($pd->addDataProduct($dataInsert)){
$request->session()->flash('addPd','success');
return redirect()->route('admin.products');
} else {
$request->session()->flash('addPd','Fail');
return redirect()->route('admin.addProduct');
}
} else {
$request->session()->flash('addPd','Can not upload image');
return redirect()->route('admin.addProduct');
}
}
CartController: I add products and want to show list products in cart
public function addCart(Request $request, $id)
{
$product = Products::select('name_product', 'id', 'price', 'qty', 'image_product')->find($id);
if(!$product) return redirect('/');
Cart::add([
'id' => $id,
'name' => $product->name_product,
'qty' => 1,
'price' => $product->price,
'options' => [
'images' => json_decode($product->image_product, true),
]
]);
return redirect()->back();
}
public function getListCart(){
$products = Cart::content();
return view('frontend.cart.showCart', compact('products'));
}
And view i get image in src : {{ URL::to('/') }}/upload/images/{{ $product->image_product[0] }}

(Illegal string offset) for import data to database

I'm trying to import an excel to my database table 'barangs' but it has an error saying "Illegal string offset 'kode_barang'". i dont know again to fix this error.
import data from excel to database with laravel maatwebsite
my controller
public function import(Request $request)
{
$this->validate($request,[
'select_file' => 'required|mimes:xls,xlsx'
]);
$path = $request->file('select_file')->getRealPath();
$data = Excel::load($path)->get();
if ($data->count() > 0) {
foreach ($data->toArray() as $key => $value) {
foreach ($value as $row) {
$insert_data[] = array(
'kodeBarang' => $row['kode_barang'],
'namaBarang' => $row['nama_barang'],
'stock' => $row['stock'],
'hargaJual' => $row['harga_jual'],
'kategory' => $row['kategory']
);
}
}
if (!empty($insert_data)) {
barang::table('barangs')->insert($insert_data);
}
}
return back()->with('success','berhasil di upload');
}
and i get error message like this
Illegal string offset 'kode_barang'
in barangController.php line 55 at HandleExceptions->handleError(2,
'Illegal string offset \'kode_barang\'',
'C:\xampp\htdocs\penjualan\app\Http\Controllers\barangController.php',
55, array('request' => object(Request), 'path' =>
'C:\xampp\tmp\phpE998.tmp', 'data' => object(RowCollection), 'key'
=> 0, 'value' => array('kode_barang' => 331211, 'nama_barang' => 'coba import', 'stock' => 2, 'harga_jual' => 3000, 'kategory' => 'Minuman',
null), 'row' => 'coba import', 'insert_data' =>
array(array('kodeBarang' => null, 'namaBarang' => null, 'stock' =>
null, 'hargaJual' => null, 'kategory' => null))))
You can solve this issue using the following code.
foreach ($data->toArray() as $key => $value) {
foreach ($value as $row_key => $row) {
$insert_data[] = array(
'kodeBarang' => $row[0],
'namaBarang' => $row[1],
'stock' => $row[2],
'hargaJual' => $row[3],
'kategory' => $row[4]
);
}
}
Add condition to check null row.
foreach ($data->toArray() as $key => $value) {
foreach ($value as $row_key => $row) {
if(!isset($row[0])) {
$insert_data[] = array(
'kodeBarang' => $row[0],
'namaBarang' => $row[1],
'stock' => $row[2],
'hargaJual' => $row[3],
'kategory' => $row[4]
);
}
}
}
Or
foreach ($data->toArray() as $key => $value) {
foreach ($value as $row_key => $row) {
if(!isset($row['kode_barang'])) {
$insert_data[] = array(
'kodeBarang' => $row['kode_barang'],
'namaBarang' => $row['nama_barang'],
'stock' => $row['stock'],
'hargaJual' => $row['harga_jual'],
'kategory' => $row['kategory']
);
}
}
}

Resources