creating default object from empty value in laravel 5 - laravel-5

I'm trying to make two functions in controller that have post action and that are in the same page.
My Controller
public function store(Request $request)
{
$status = DB::table('analytics')->where('dienstleistung', '!=', '')->get();
//Save data
$rules = [
'site_id' => 'required',
'dienstleistung' => 'required',
'objekt' => 'required',
'zimmer' => 'required',
'vorname' => 'required',
'name' => 'required',
'strasse' => 'required',
'ort' => 'required',
'plz' => 'required',
'tel' => 'required',
'email' => 'required|email',
'reinigungstermin' => 'required',
'gekommen' => 'required',
'message' => 'required',
'status' => 'required',
'answer' => 'required',
'notiz' => 'required',
'userId' => 'required',
];
$validator = Validator::make(Input::all(), $rules);
if($validator->fails()) {
return Redirect::to('anfrage')
->withErrors($validator)
->withInput();
}
else {
$anfrage = new Analytic();
$anfrage->site_id = Input::get('site_id');
$anfrage->dienstleistung = Input::get('dienstleistung');
$anfrage->objekt = Input::get('objekt');
$anfrage->zimmer = Input::get('zimmer');
$anfrage->vorname = Input::get('vorname');
$anfrage->name = Input::get('name');
$anfrage->strasse = Input::get('strasse');
$anfrage->ort = Input::get('ort');
$anfrage->plz = Input::get('plz');
$anfrage->tel = Input::get('tel');
$anfrage->email = Input::get('email');
$anfrage->reinigungstermin = Input::get('reinigungstermin');
$anfrage->gekommen = Input::get('gekommen');
$anfrage->message = Input::get('message');
$anfrage->status = Input::get('status');
$anfrage->answer = Input::get('answer');
$anfrage->notiz = Input::get('notiz');
$anfrage->userId = Input::get('userId');
try {
$anfrage->save();
flash()->success(trans('app.success'));
return Redirect::to('anfrage');
} catch (\Exception $e) {
Log::writeException($e);
return Redirect::to('anfrage')
->withErrors($e->getMessage())
->withInput();
}
}
}
public function editItem(Request $request) {
$anfrages = Analytic::find($request['id'] );
$anfrages->status = $request->status;
$anfrages->answer = $request->answer;
$anfrages->notiz = $request->notiz;
$anfrages->save();
return response ()->json( $anfrages );
}
My route:
Route::post('anfrage', 'AnfrageController#store');
Route::post ( 'anfrage', 'AnfrageController#editItem' );
EditItem function is OK, it makes changes when I want to edit data, but when I want to store data, message being displayed is:
creating default object from empty value
So, I need to leave active only one of these function, both are not working.

Related

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

Get url variable in a request validation file

I am using the url with an id variable to update a record:
Route::patch('ProjectsRevenueUpdateAjax/{id}'...
And I have my controller for this:
public function updateRevenue(ProjectRevenueUpdateRequest $request,$id)
{
// When using stdClass(), we need to prepend with \ so that Laravel won't get confused...
$result = new \stdClass();
$inputs = $request->all();
$projectRevenueToUpdate = ProjectRevenue::find($id);
$projectRevenueToUpdate->update($inputs);
$result->result = 'success';
$result->msg = 'Record updated successfully';
return json_encode($result);
}
So I'm calling the validation through another file which is ProjectRevenueUpdateRequest:
public function rules()
{
$id = $this->id;
$revenue = ProjectRevenue::find($id);
$project_id = $revenue->project_id;
$year = $this->year;
$product_code = $this->product_code;
return [
'project_id' => 'required|unique:project_revenues,project_id,'.$id.',id,year,'.$year.',product_code,'.$product_code,
'year' => 'required|unique:project_revenues,year,'.$id.',id,project_id,'.$project_id.',product_code,'.$product_code,
'product_code' => 'required|unique:project_revenues,product_code,'.$id.',id,year,'.$year.',project_id,'.$project_id,
'jan' => 'required',
'feb' => 'required',
'mar' => 'required',
'apr' => 'required',
'may' => 'required',
'jun' => 'required',
'jul' => 'required',
'aug' => 'required',
'sep' => 'required',
'oct' => 'required',
'nov' => 'required',
'dec' => 'required',
];
}
My problem is that it cannot get the $id = $this->id from the url in my request validation file. How can I do that?

Cannot save my uploaded image to local disk folder

I am currently building a CRUD application using Laravel. It requires me to upload images and information but seems like there are some problems on storing the images to the localdisk folder.
Here is my controller code:
public function store(Request $request)
{
$lostitem =new Admin();
$this->validate($request, [
'date' => 'required',
'TimeFound' => 'required',
'AreaWhereFound' => 'required',
'image' => 'required',
'Remark' => 'required',
'DateClaimed' => 'required',
'TimeClaimed' => 'required',
'CategoryID'=>'required'
]);
$uuid = Str::uuid()->toString();
// $record = new Admin;
// return view('students.create');
$lostitem->code = $uuid;
$lostitem->date = $request->date;
$lostitem->TimeFound = $request->TimeFound;
$lostitem->AreaWhereFound = $request->AreaWhereFound;
$lostitem->image = $request->image;
if($request->hasfile('image'))
{
$filenameWithExt=$request->file('image')->getClientOriginalName();
$filename=pathinfo($filenameWithExt,PATHINFO_FILENAME);
$extension =$request->file('image')->getClientOriginalExtension();
$fileNameToStore=$filename.'_' .time().'.'.$extension;
$path=$request->file('image')->storeAs('public/images',$fileNameToStore);
// $file = $request->file('image');
// $extension =$file->getClientOriginalExtension();//getting image extensionimage
// $filename=time() ."." .$extension;
// $file->move('uploads',$filename->getClientOriginal);
// //getting from data base
}
else
{
// $lostitem->image = "";
$fileNameToStore='noimage.jpg';
}
$lostitem->image = $request->image ;
$lostitem->Remark = $request->Remark;
$lostitem->DateClaimed = $request->inputDateClaimed;
$lostitem->TimeClaimed = $request->TimeClaimed;
$lostitem->CategoryID = $request->CategoryID;
$lostitem->save();
return redirect(route('LostItem_add'))->with('successMsg', 'Record added!');
}
The other information is saved. I hope to get help.
Change Your controller code to this:
public function store(Request $request)
{
$lostitem =new Admin();
$this->validate($request, [
'date' => 'required',
'TimeFound' => 'required',
'AreaWhereFound' => 'required',
'image' => 'required',
'Remark' => 'required',
'DateClaimed' => 'required',
'TimeClaimed' => 'required',
'CategoryID'=>'required'
]);
$uuid = Str::uuid()->toString();
$lostitem->code = $uuid;
$lostitem->date = $request->date;
$lostitem->TimeFound = $request->TimeFound;
$lostitem->AreaWhereFound = $request->AreaWhereFound;
$lostitem->image = $request->image;
if($request->hasfile('image')){
$filenameWithExt=$request->file('image')->getClientOriginalName();
$filename=pathinfo($filenameWithExt,PATHINFO_FILENAME);
$extension =$request->file('image')->getClientOriginalExtension();
$fileNameToStore=$filename.'_' .time().'.'.$extension;
$path=$request->file('image')->move(public_path('images/'),$fileNameToStore);
}
else{
$fileNameToStore='noimage.jpg';
}
$lostitem->image = $request->image ;
$lostitem->Remark = $request->Remark;
$lostitem->DateClaimed = $request->inputDateClaimed;
$lostitem->TimeClaimed = $request->TimeClaimed;
$lostitem->CategoryID = $request->CategoryID;
$lostitem->save();
return redirect(route('LostItem_add'))->with('successMsg', 'Record added!');
}
And then access your image in the blade like this
<img src="{{ asset('images/'.$item->image) }}">
And make sure that you do have an folder named "images" in the public directory
Save the path of image in database
public function store(Request $request)
{
$lostitem =new Admin();
$this->validate($request, [
'date' => 'required',
'TimeFound' => 'required',
'AreaWhereFound' => 'required',
'image' => 'required',
'Remark' => 'required',
'DateClaimed' => 'required',
'TimeClaimed' => 'required',
'CategoryID'=>'required'
]);
$uuid = Str::uuid()->toString();
$lostitem->code = $uuid;
$lostitem->date = $request->date;
$lostitem->TimeFound = $request->TimeFound;
$lostitem->AreaWhereFound = $request->AreaWhereFound;
$lostitem->image = $request->image;
if($request->hasfile('image')){
$filenameWithExt=$request->file('image')->getClientOriginalName();
$filename=pathinfo($filenameWithExt,PATHINFO_FILENAME);
$extension =$request->file('image')->getClientOriginalExtension();
$fileNameToStore=$filename.'_' .time().'.'.$extension;
$path=$request->file('image')->move(public_path('images/'),$fileNameToStore);
}
else{
$fileNameToStore='noimage.jpg';
}
$lostitem->image = $path ;
$lostitem->Remark = $request->Remark;
$lostitem->DateClaimed = $request->inputDateClaimed;
$lostitem->TimeClaimed = $request->TimeClaimed;
$lostitem->CategoryID = $request->CategoryID;
$lostitem->save();
return redirect(route('LostItem_add'))->with('successMsg', 'Record added!');
}
& show it
<img src="{{ asset('images/'.$item->image) }}">

Validation error in api response in laravel 5.6

I want to store data through api. It's working but problem is when I add validation it does not give me corresponding message . How can I fix it? Thanks in advance
Here is my route
Route::post('api/add_user', 'TestApiController#store');
Here is my controller
public function store(Request $request)
{
$validation = Validator::make(Request::all(), [
'name' => 'required',
'phone' => 'required',
'email' => 'required'
]);
if ($validation->errors()) {
return $errors->toJson();
} else {
$testApi = new testApi();
$testApi->name = $request->name;
$testApi->phone = $request->phone;
$testApi->email = $request->email;
$testApi->save();
return "ok";
}
}
to handle that your method should be like this :
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required',
'phone' => 'required',
'email2' => 'required|email'
]);
if($validator->fails()){
// here we return all the errors message
return response()->json(['errors' => $validator->errors()], 422);
}
$testApi = new testApi();
$testApi->name = $request->name;
$testApi->phone = $request->phone;
$testApi->email = $request->email;
$testApi->save();
// 201 http code means that the server has proceced your request correctly
return response()->json([], 201);
}
You don't have to manually do this. simply
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'phone' => 'required',
'email' => 'required'
]);
$testApi = new testApi();
$testApi->name = $request->name;
$testApi->phone = $request->phone;
$testApi->email = $request->email;
$testApi->save();
return "ok";
}
this will automatically handles validation and returns error message when invalid.
Update
if you wanna stick with your approach. this is where you need to change.
if ($validation->fails()) {
return $validation->errors();
}

use cookie to store and retrieve order data in laravel

use cookie to store and retrieve order data in laravel
I want to use cookie to store and retrieve order data in store order:
public function store(Request $request, $serviceId) {
$request->validate([
'company_id' => 'required',
'user_id' => 'required',
'individual_count' => 'required',
'date' => 'required',
'time' => 'required',
'total_price' => 'required',
'is_home' => 'required',
]);
$request['date'] = date('Y-m-d H:i:s', strtotime($request->date . $request->time));
$request['total_price'] = explodeBySpace($request->total_price)[0];
$request['service_id'] = Hashids::decode($serviceId)[0];
session([ 'totalOrderPrice' => $request['total_price'] ]);
session([ 'companyName' => $request->company_name ]);
session([ 'individualCount' => $request->individual_count ]);
session([ 'orderDate' => $request['date'] ]);
// dd($request->all());
$created = Orders::create($request->all());
if ($created) {
session(['orderId' => $created->id]);
Cookie::make('orderId', $created->id, 180); // ?
return redirect()->route('payment.method');
}
return redirect()->route('web.orders.create', $serviceId)->with('alert', 'error');
}
to retrieve order data for payment operation :
public function storeReceipt(Request $request, $method) {
$request->validate([
'price' => 'required|numeric',
]);
$request['order_id'] = $request->cookie('orderId');
$request['method'] = $method;
$created = Payment::create($request->all());
return $created->count() > 0
? redirect()->route('home')->with('alert', 'success')
: redirect()->route('payment/method/create', 'receipt')->with('alert', 'error');
}
but this error occurs
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'order_id' cannot be null
what is the wrong
Hi you can try Cookie::get(); to retrieve the cookies
public function storeReceipt(Request $request, $method) {
$request->validate([
'price' => 'required|numeric',
]);
$request['order_id'] = Cookie::get('orderId');
$request['method'] = $method;
$created = Payment::create($request->all());
return $created->count() > 0
? redirect()->route('home')->with('alert', 'success')
: redirect()->route('payment/method/create', 'receipt')->with('alert', 'error');
}

Resources