I created a multistep form but I didn't use Ajax in it because I have no idea about Ajax. I have had to code a lot in my controller and routes for the way I created it which is probably not optimized. I'm new to Laravel so I can't find any solution.
How can I do this with ajax?
Controller
public function InitialCreateReport(Request $request){
$request->session()->forget('report');
$data['fiscalyear'] = FiscalYear::all();
$data['month'] = Months::all();
$data['report_type'] = ReportType::all();
$data['report'] = $request->session()->get('report');
return view('adc.reports.create-report', $data);
}
public function PostInitialCreateReport(Request $request){
$validatedData = $request->validate([
'fiscalyear' => 'required',
'month' => 'required',
'report_type' => 'required',
]);
if (empty($request->session()->get('report'))) {
$report = new Report();
$report->fill($validatedData);
$request->session()->put('report', $report);
} else {
$report = $request->session()->get('report');
$report->fill($validatedData);
$report->session()->put('report', $report);
}
return redirect()->route('adc.create.rent.certificate');
}
public function CreateRentCertificateReport(Request $request)
{
$data['report'] = $request->session()->get('report');
$data['reports'] = Report::distric()->status(1)->get();
return view('adc.reports.start-create-report', $data);
}
public function PostCreateRentCertificateReport(Request $request)
{
$report = $request->session()->get('report');
$request->session()->put('report', $report);
return redirect()->route('adc.preview.rent.certificate.report');
}
public function PreviewRentCertificateReport(Request $request){
$report = $request->session()->get('report');
return view('adc.reports.preview-rent-certificate-report', compact('report', $report));
}
public function PostPreviewRentCertificateReport(Request $request){
$report = $request->session()->get('report');
return redirect()->route('adc.save.rent.certificate.report');
}
public function SaveRentCertificateReport(Request $request){
$report = $request->session()->get('report');
return view('adc.reports.save-rent-certificate-report', compact('report', $report));
}
public function PostSaveRentCertificateReport(Request $request)
{
$report = $request->session()->get('report');
$reports = new Report;
$reports->column_one = $report->sum('column_one');
$reports->column_two = $report->sum('column_two');
$reports->fiscal_year = $report->fiscalyear;
$reports->month = $report->month;
$reports->report_type = $report->report_type;
$reports->save();
$notification = array(
'message' => 'Report Created Successfully',
'alert-type' => 'success'
);
return redirect()->route('adc.pending.report')->with($notification);
}
Route
Route::get('/initial/create/report', [AdcController::class,'InitialCreateReport'])->name('inital.create.report');
Route::post('/initial/create/report', [AdcController::class,'PostInitialCreateReport'])->name('inital.create.report.post');
Route::get('/create/rent/certificate/report', [AdcController::class, 'CreateRentCertificateReport'])->name('create.rent.certificate');
Route::post('/create/rent/certificate/report', [AdcController::class, 'PostCreateRentCertificateReport'])->name('create.rent.certificate.report.post');
Route::get('/preview/rent/certificate/report', [AdcController::class, 'PreviewRentCertificateReport'])->name('preview.rent.certificate.report');
Route::post('/preview/rent/certificate/report', [AdcController::class, 'PostPreviewRentCertificateReport'])->name('preview.rent.certificate.report.post');
Route::get('/save/rent/certificate/report', [AdcController::class, 'SaveRentCertificateReport'])->name('save.rent.certificate.report');
Route::post('/save/rent/certificate/report', [AdcController::class, 'PostSaveRentCertificateReport'])->name('save.rent.certificate.report.post');
Related
I am using Laravel-5.8 as backend for an application. I have written all the Api for the endpoints.
Laravel: ApiController
protected function guard()
{
return Auth::guard();
}
public function returnResponse($success, $data, $errorCode = 0, $message = false) {
$response = array();
$response['success'] = $success;
$response['message'] = isset($message) ? $message : '';
if ($errorCode) {
$response['errorCode'] = isset($errorCode) ? $errorCode : 0;
}
$response['data'] = $data;
return response()->json($response, 200);
}
public function login() {
$authenticated = false;
$remember = request('remember') ? true : false;
if (Auth::guard('web')->attempt(['email' => request('email'), 'password' => request('password')], $remember)) {
$authenticated = true;
}
if ($authenticated == true) {
$user = Auth::guard('web')->user();
$date = date('Y-m-d');
$success['userId'] = $user->id;
$success['avatar'] = url('/storage/user') . '/' . $user->avatar;
// $success['points'] = $user->userPoints->sum('points');
$success['email'] = $user->email;
$success['token'] = $user->createToken('MyApp')->accessToken;
return $this->returnResponse(true, $success);
} else {
$success = array();
return $this->returnResponse(false, $success, 1, 'Invalid User Credential');
}
}
api.php
Route::group([
], function () {
Route::post('login', 'ApiController#login');
Route::post('register', 'ApiController#register');
Route::post('forgetPassword', 'ApiController#forgetPassword');
Route::group([
'middleware' => 'auth:api'
], function() {
Route::get('logout', 'AuthController#logout');
Route::get('user', 'AuthController#user');
});
});
When I test the login Post Request on the POSTMAN, I got the error shown below:
What could have caused the error?
i think you have declare index() multiple times in your controller so please check and if there is multiple times declaration of index() then just remove anyone.
I have problem with edit and update with 2 table using query builder.
--->After i press button submit--->the data insert new row---> not update current data.
This is my function edit(only for view old data)
public function edit(Request $request, $id){
$tax_rate = TaxRate::find($id);
$tax_rate_details = TaxRateDetail::where('tax_rate_id', $id)->get();
$country = Country::all();
$geo_zones = GeoZone::all();
//dd($tax_rate);
//dd($tax_rate_details);
//dd($geo_zones);
if(!$tax_rate) {
return redirect('/');
}
return view('tax_management.edit',['country' => $country , 'tax_rate'=>$tax_rate , 'geo_zones'=>$geo_zones, 'tax_rate_details'=>$tax_rate_details]);
}
This is my update(i do validation and the saveTax is the saving part)
public function update(Request $request, $id){
$this->validate($request,[
'country_id'=> 'required',
'tax_type' => 'required',
'name' => 'required|max:100',
'code' => 'required|max:50'
]);
//dd($request->input());
DB::beginTransaction();
try{
$tax_rate = TaxRate::find($id);
$tax_rate_details = TaxRateDetail::where('tax_rate_id', $id)->get();
$this->saveTax($request, $tax_rate);
DB::commit();
return redirect()->route('tax_management.index');
} catch (\Exception $ex){
//dd($ex);
DB::rollback();
return back()->withInput()->withErrors('Fail to save');
}
}
This is my function save()
private function saveTax(Request $request, $tax_rate){
$tax_rate->country_id = $request->input('country_id');
$tax_rate->geo_zone_id = $request->input('geo_zone_id');
$tax_rate->tax_type = $request->input('tax_type');
$tax_rate->name = $request->input('name');
$tax_rate->code = $request->input('code');
$tax_rate->description = $request->input('description');
if(!empty($request->input('active'))){
$tax_rate->active =1;
} else {
$tax_rate->active =0;
}
$tax_rate->save();
if($tax_rate->tax_rate_id) {
TaxRateDetail::where('tax_rate_id', $tax_rate->tax_rate_id)->delete();
}
if($request->input('tax_rate_details')){
foreach ($request->input('tax_rate_details') as $key => $value) {
$tax_rate_detail = new TaxRateDetail();
$tax_rate_detail->tax_rate_id = $tax_rate->tax_rate_id;
$tax_rate_detail->priority = $value['priority'];
$tax_rate_detail->date_from = $value['date_from'];
$tax_rate_detail->date_to = $value['date_to'];
$tax_rate_detail->rate = $value['rate'];
$tax_rate_detail->type = $value['type'];
$tax_rate_detail->active = $value['active'];
//dd($tax_rate_detail);
$tax_rate_detail->save();
}
}
}
I want to save edit update with old(id). not create new. Please help thank you. I don't know where the code gone wrong.
When trying to filter with only username or email code works fine.But when i am trying to filter with both email and username it returns empty.what i am missing
User model
public function scopeEmail($query, $email)
{
$query->where('email','=', $email);
}
public function scopeUsername($query, $username)
{
$query->where('username','=', $username);
}
Controller:
public function filter(Request $request)
{
$q = User::query();
$email = $request->input('email');
$username= $request->input('username');
if (isset($email))
{
// simple where here or another scope, whatever you like
$q->Email($request->input('email'));
}
if (isset($username))
{
$q->Username($request->input('username'));
}
//execute
$results = $q->get();
return response()->json(['issError'=>0, 'errorCode'=>0,'message'=>$results],200);
}
Use When to make filter easy:
public function filter(Request $request)
{
$q = User::query();
$email = $request->input('email');
$username= $request->input('username');
$q->when($email,function ($query){
$query->where('email',$email);
});
$q->when($username,function ($query){
$query->where('username',$username);
});
$results = $q->get();
return response()->json(['issError'=>0, 'errorCode'=>0,'message'=>$results],200);
}
Use simple where in if statements
public function filter(Request $request)
{
$q = User::query();
$email = $request->input('email');
$username= $request->input('username');
if (isset($email))
{
// simple where here or another scope, whatever you like
$q = $q->where('email', $request->input('email'));
}
if (isset($username))
{
$q = $q->where('username', $request->input('username'));
}
//execute
$results = $q->get();
return response()->json(['issError'=>0, 'errorCode'=>0,'message'=>$results],200);
}
Try this
public function filter(Request $request)
{
$q = User::query();
$email = $request->input('email');
$username= $request->input('username');
if (!is_null($email))
{
$q = $q->where('email', $email);
}
if (!is_null($username))
{
$q = $q->where('username', $username));
}
$results = $q->get();
return response()->json(['issError'=>0, 'errorCode'=>0,'message'=>$results],200);
}
I have an update post form, where I need to update the name of the post in posts table and the associated text within the text table. I can't seem to get it to work at all.
Model - Post.php
public function text()
{
return $this->hasOne('Text');
}
Model - Text.php
public function post()
{
return $this->belongsTo('Post');
}
Controller - PostController.php
public function updateQuestionForm($id)
{
$post = Post::find($id);
$input = Input::all();
$rules = array(
'text' => 'required',
);
$validation = Validator::make($input, $rules);
if ($validation->fails()) {
return Redirect::back()->withErrors($validation)->withInput();
} else {
$post->title = Input::get('title');
$post->save();
$text = $post->text();
$text->text = Input::get('text');
$post->text()->save($text);
$message = "Post updated";
return Redirect::to('question/'.$post->id.'/'.$post->slug.'/')->with('message', $message);
}
}
I have been toiling around to no avail of Solutions Please help. It seems my View cannot read the $code and $user variable respectively from my Controller
Here is the part of my controller that the $code and $user Variables are been instantiated respectively:
UserController.php
public function varifyMail($code){
if(User::where('varification_code','=',$code)->update(['varification_status'=>1])){
return Redirect::route('login')
->with('success', 'Account varified.');
}else{
return Redirect::route('login')
->with('error', 'Varification Failed.Try again');
}
);
$validation = Validator::make(Input::all(),$rules);
if($validation->fails()){
return Redirect::route('login')
->with('error', 'Invalid Email Address. Try again.');
}else{
$code = str_random(25);
$userUpdate = ['recovery_code' => $code];
User::where('email','=',Input::get('email'))->update($userUpdate);
$data = ['code'=>$code];
//send mail
Mail::send('emails.recover',$data,function($message){
$message->to(Input::get('email'))->subject('Recover Your Account.');
});
return Redirect::route('login')
->with('success', 'Request Send successfully.Please Recover Your Account.');
//return User::where('email','=',Input::get('email'))->get();
}
Auth::login($user);
return View::make('users.edit')
->with('title','Update Cridentials')
->with('user',User::where('id','=',$user->id)->first());
}else{
return Redirect::route('login')
->with('error', 'Recovery Failed.Try again');
}
And this is my view:
Adminverify.blade.php
<div class="header-content"><webversion>Web Version</webversion><span class="hide"> | <preferences lang="en">Update preferences</preferences> | </span>
But whenever I try using it it get this error:
ErrorException
Undefined variable: code (View: C:\wamp\www\secureserver\app\views\emails\adminverify.blade.php)
Any Help will be highly Appreciated Thanks!
Thanks for your prompt response but it happens to be that it did not work but here is my entire Controller with the Varify changed to Verify as cadmium suggested so we can be sure what exactly could be the challenge.
class UserController extends BaseController {
private function verify($email){
$verify = User::where('email','=',$email)->first();
if(! is_null($verify)){
if($verify->role_id==2){
return $verify->distributor_approve & $verify->varification_status;
}else{
return $verify->varification_status;
}
}else{
return 0;
}
}
/**
* login page
* #return void
*/
public function login()
{
return View::make('users.login')
->with('title', 'Log in');
}
/**
* process to login a user
* #return void
*/
public function doLogin()
{
$rules = array
(
'email' => 'required|email',
'password' => 'required'
);
$validation = Validator::make(Input::all(), $rules);
if($validation->fails())
return Redirect::route('login')
->withInput()
->withErrors($validation);
else
{
$credentials = array
(
'email' => Input::get('email'),
'password' => Input::get('password')
);
if($this->verify(Input::get('email')) && Auth::attempt($credentials))
{
Session::put('role', Auth::user()->role_id);
//return User::where('id','=',Auth::user()->id)->first();
if(User::where('id','=',Auth::user()->id)->first()->first_login == 0){
return Redirect::route('info.create',[Auth::user()->id]);
}
return Redirect::intended('/');
}
else
return Redirect::route('login')
->withInput()
->with('error', 'Error in Email Address or Password.');
}
}
/**
* logout a user
* #return void
*/
function logout()
{
Auth::logout();
Session::forget('role');
return Redirect::route('login')
->with('success', 'You have been logged out.');
}
public function show(){
$pages= Page::orderby('title')->get();
if(Auth::check()){
if(Auth::user()->role_id==1){
return View::make('public.pages.admin')
->with('title', "Home");
}
}
return View::make('public.pages.show')
->with('title', "Home")
->with('pages',$pages);
}
public function register()
{
return View::make('users.register')
->with('title', 'Register');
}
public function doRegister()
{
//return Input::all();
$rules = array
(
'username' => 'required|min:3|max:15',
'email' => 'required|email|unique:users',
'password' =>'Required|Confirmed',
'password_confirmation' =>'Required',
'role' => 'Required',
'agree' => 'Required',
'recaptcha_response_field' => 'required|recaptcha'
);
$validation = Validator::make(Input::all(), $rules);
if($validation->fails())
return Redirect::route('register')
->withInput()
->withErrors($validation);
else
{
if(Input::get('role')==3){
$user = new User;
$user->user_name = Input::get('username');
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));
$user->role_id = Input::get('role');
$code = str_random(25);
$user->varification_code = $code;
$data = ['username'=>Input::get('username'),'code'=>$code];
Mail::send('emails.validate',$data,function($message){
$message->to(Input::get('email'))->subject('Please Verify Your Email.');
});
if($user->save())
return Redirect::route('home')
->with('success', "Verify Your Account.");
else
return Redirect::back()->withInput()->withErrors($validation)->with('error', 'Some error occured. Try again.');
}else{
$user = new User;
$user->user_name = Input::get('username');
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));
$user->role_id = Input::get('role');
$user->distributor_status = 1;
$code = str_random(25);
$user->varification_code = $code;
$data = ['username'=>Input::get('username'),'code'=>$code];
Mail::send('emails.validate',$data,function($message){
$message->to(Input::get('email'))->subject('Please Verify Your Email.');
});
if($user->save())
return Redirect::route('home')
->with('success', "Request Send successfully.Please Verify Your Email.");
else
return Redirect::back()->withInput()->withErrors($validation)->with('error', 'Some error occured. Try again.');
}
}
}
public function edit(){
return View::make('users.edit')
->with('title','Update Cridentials')
->with('user',User::where('id','=',Auth::user()->id)->first());
}
public function update(){
$rules = array
(
'username' => 'required|min:3|max:15',
'password' =>'Required|Confirmed',
'password_confirmation' =>'Required'
);
$validation = Validator::make(Input::all(), $rules);
if($validation->fails())
return Redirect::back()
->withInput()
->withErrors($validation);
else
{
$userUpdate = ['user_name' => Input::get('username'),
'password'=>Hash::make(Input::get('password'))
];
if(User::find(Auth::user()->id)->update($userUpdate)){
Auth::logout();
Session::forget('role');
return Redirect::route('login')
->with('success', 'Your Cridentials Have Been Changed.');
}
else
return Redirect::back()->withInput()->withErrors($validation)->with('error', 'Some error occured. Try again.');
}
}
public function verifyMail($code){
if(User::where('varification_code','=',$code)->update(['varification_status'=>1])){
return Redirect::route('login')
->with('success', 'Account varified.');
}else{
return Redirect::route('login')
->with('error', 'Varification Failed.Try again');
}
}
public function passwordRecover(){
$rules = array
(
'email' => 'required|email'
);
$validation = Validator::make(Input::all(),$rules);
if($validation->fails()){
return Redirect::route('login')
->with('error', 'Invalid Email Address. Try again.');
}else{
$code = str_random(25);
$userUpdate = ['recovery_code' => $code];
User::where('email','=',Input::get('email'))->update($userUpdate);
$data = ['code'=>$code];
//send mail
Mail::send('emails.recover',$data,function($message){
$message->to(Input::get('email'))->subject('Recover Your Account.');
});
return Redirect::route('login')
->with('success', 'Request Send successfully.Please Recover Your Account.');
//return User::where('email','=',Input::get('email'))->get();
}
}
public function mailRecover($code){
$user = User::where('recovery_code','=',$code)->first();
if(! is_null($user)){
Auth::login($user);
return View::make('users.edit')
->with('title','Update Cridentials')
->with('user',User::where('id','=',$user->id)->first());
}else{
return Redirect::route('login')
->with('error', 'Recovery Failed.Try again');
}
}
/**
* Show a page
* #param string $pageUrl
* #return void
*/
public function pages($pageUrl = 'home')
{
try
{
$page = Page::where('url', '=', $pageUrl)->firstOrFail();
/*
if($page->id == 1) $layout = 'layouts.home';
else $layout = 'layouts.default';
*/
$layout = 'layouts.default';
return View::make('public.pages.publicShow')
->with('title', "$page->title")
->with('page', $page)
->with('layout', $layout);
}
catch(ModelNotFoundException $e)
{
return "Page not found.";
}
}
Somewhere in your code you need to have View::make("adminverify"). I don't see it in the code you've posted, but it's there somewhere. You need to pass the $code value to this view, like so:
View::make("adminverify")->with("code", "some code value");
Once you do that, the $code variable will be available in the template.