Can you insert declared variables in database Laravel 4 - php

I am fairly new to everything and I am wondering if it is possible to store declared variables in to database?
For example(these are placed in the nameoffilecontroller.php),
public function onewayflightshow()
{ $a=Session::get('children');
$b=Session::get('adult');
$c=Session::get('infant');
$d=Session::get('destinationto');
$e=Session::get('destinationfrom');
$f=Session::get('departure');
$results = DB::table('oneways')->get();
if (!empty($results))
foreach ($results as $user)
{
$adultFee = ($user->fare)*$b;
/*------------------------Child Fee------------------------*/
$partialFee1 = ($user->fare)*.05;
$partialFee2 = ($user->fare)-$partialFee1;
$childFee = $partialFee2*$a;
/*------------------------Infant Fee------------------------*/
$partialFee3 = ($user->fare)*.10;
$partialFee4 = ($user->fare)-$partialFee3;
$infantFee = $partialFee2*$c;
$payment = ($adultFee+$childFee+$infantFee);
var_dump($payment);
}
$rules = array(
'title' => 'required',
'lastname' => 'required',
'email' => 'required|email',
'cemail' => 'required|same:email',
'firstname' => 'required',
'middlename' => 'required',
'birthday' => 'required',
'city' => 'required',
'streetadd' => 'required',
'zipcode' => 'required|max:4',
'country' => 'required',
'home' => 'required|max:7',
'mobile' => 'required|max:12'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
$messages = $validator->messages();
return View::make('content.onewayflightfillup')->withErrors($validator);
} else {
$reserve = new Reserves;
$reserve->title = Input::get('title');
$reserve->lastname = Input::get('lastname');
$reserve->firstname= Input::get('firstname');
$reserve->middlename = Input::get('middlename');
$reserve->birthday = Input::get('birthday');
$reserve->city = Input::get('city');
$reserve->streetadd = Input::get('streetadd');
$reserve->zipcode = Input::get('zipcode');
$reserve->country = Input::get('country');
$reserve->home = Input::get('home');
$reserve->work = Input::get('work');
$reserve->fax = Input::get('fax');
$reserve->mobile = Input::get('mobile');
$reserve->email = Input::get('email');
$reserve->children = Session::get('children');
$reserve->children = Session::get('adult');
$reserve->children = Session::get('infant');
$reserve->children = Session::get('destinationfrom');
$reserve->children = Session::get('destinationto');
$reserve->children = Session::get('departure');
$reserve->$payment; <-- IS THIS EVEN POSSIBLE?
$reserve->save();
var_dump($reserve);
return View::make('content.onewayflightbooklist');
}}
I am trying to save(); everything in my database, from the session variables to the inputed values from the user but the problem is I don't know how to insert $payment into the database table. Is it even possible? If yes, what are the way/s of doing it?

You need to put it into database using:
$reserve->payment = $payment;
but of course in your table you need to have column with name payment
And obviously this:
$reserve->children = Session::get('children');
$reserve->children = Session::get('adult');
$reserve->children = Session::get('infant');
$reserve->children = Session::get('destinationfrom');
$reserve->children = Session::get('destinationto');
$reserve->children = Session::get('departure');
won't work. In each column you can insert only one data.

<?php
class Test extends Eloquent
{
public function insert()
{
$a=1;
$b=2;
$c=$a+$b;
$data = array('column_1'=>$a , 'column_2'=>$b , 'column_3'=>$c);
$query = DB::table('table_name')->insert($data);
}
}
?>
This is a model function extending eloquent ORM . call this model function in your controller

class TestController extends BaseController
{
public function test()
{
$data = Modelname::ModelFunction(); /* if the model function is static */
/* else you need to create an object for that class */
$t = new Modelname();
$data = $t->ModelFunction();
}
}

Related

ArgumentCountError when updating content in larvel

In my laravel application, I'm trying to update some content using the following controller function. But every time when I try to run the following function am getting an error
public function update_tcp(Request $request, $id)
{
try{
Session::put('tcpSession', '1');
$request->merge(['gender' => 'M']);
$this->validate($request, [
'first_name_tcp2' => 'required',
'last_name_tcp2' => 'required',
'image_id' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'user_id'=>'required',
'gender'=>'required',
'date_of_birth_tcp2'=>'required'
]);
//$input = $request->except('_method', '_token');
$input = $request->all();
unset($input['_token']);
unset($input['_method']);
if ($image = $request->file('image_id')) {
$destinationPath = 'propics/';
$profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $profileImage);
$input['image_id'] = "$profileImage";
//dd($profileImage);
}else{
//unset($input['image']);
$profileImage='default-avatar.png';
$request->merge(['image_id' => 'default-avatar.png']);
}
$data = $request->input();
$tcp = TakeCarePerson::WHERE('id','=',''.$id.'');
$tcp->first_name = $data['first_name_tcp2'];
$tcp->last_name = $data['last_name_tcp2'];
$tcp->date_of_birth = $data['date_of_birth_tcp2'];
$tcp->user_id = $data['user_id'];
$tcp->image_id = $profileImage;
$tcp->gender= $data['gender'];
$tcp->update();
return redirect()->route('participants.index')
->with('success',__('texts.Take care person updated successfully.'));
} catch(Exception $e){
return back() ->with('failedTcp',__('texts.Le fichier sélectionné doit être une image.'));
}
}
This is the error,
ArgumentCountError Too few arguments to function
Illuminate\Database\Eloquent\Builder::update(), 0 passed
Where do I need to fix in order to function my update function properly?
You are not passing data to update .Instead where find by id and then call save()
$tcp = TakeCarePerson::find($id);
$tcp->first_name = $data['first_name_tcp2'];
$tcp->last_name = $data['last_name_tcp2'];
$tcp->date_of_birth = $data['date_of_birth_tcp2'];
$tcp->user_id = $data['user_id'];
$tcp->image_id = $profileImage;
$tcp->gender= $data['gender'];
$tcp->save();
or
$tcp = TakeCarePerson::where('id','=',$id)->update([
'first_name'=> $data['first_name_tcp2'],
'last_name'=>$data['last_name_tcp2'],
'date_of_birth'=>$data['date_of_birth_tcp2'],
'user_id'=>$data['user_id'],
'image_id'=>$profileImage,
'gender'=>$data['gender']
]);

Yii2 SELECT * WHERE id = array()?

i has Query select use WHERE = array(1,2,...), i tried IN but only data of the end ID and previous ID's data does not appear. Help me, thank for all.
My code:
Controller:
public function actionGetServiceType($q = null, $id = null) {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$out = ['results' => ['id' => '', 'text' => '']];
if (!is_null($q)) {
$queryTest = new Query;
$queryTest->select('service_type_id')
->from('link_service_group_all')
->where(['IN', 'service_group_id', $id]);
$query = new Query;
$query->select('id as id, title AS text')
->from('service_type')
->where(['like', 'title', $q])
->andWhere(['IN', 'id' , $queryTest]);
$command = $query->createCommand();
$data = $command->queryAll();
$out['results'] = array_values($data);
}
return $out;
}
public function actionGetServiceType($q = null, $id = null) {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$out = ['results' => ['id' => '', 'text' => '']];
if (!is_null($q)) {
$queryTest = new Query;
$queryTest->select('service_type_id')
->from('link_service_group_all')
->where(['IN', 'service_group_id', $id]);
$queryTest = array_values($queryTest->createCommand()->queryColumn());
$query = new Query;
$query->select('id as id, title AS text')
->from('service_type')
->where(['like', 'title', $q])
->andWhere(['IN', 'id' , $queryTest]);
$command = $query->createCommand();
$data = $command->queryAll();
$out['results'] = array_values($data);
}
return $out;
}
you were missing a line like this
$queryTest = array_values($queryTest->createCommand()->queryColumn());

Laravel registration page eero

Please I have a laravel website which have been working fine then all of a sudden when a user uses a referral link to register, the page will reload and redirect back to the registration page. I tried it for few times and it works then I used the new referral link to register another new account and didn't work again ever since then. And its not showing any error message but rather bounce back to same page. I have checked the RegistrationController and all the code is still fine as same before. Please I really need this help.
Thanks in Advance
Below is my RegistrationControl
`public function getRegistrationPage(){
return view('auth.register');
}
public function storeUser(Request $request){
$this->validate($request, [
'name' => 'required|max:30',
'email' => 'required|unique:users',
'phone' => 'required|min:10|unique:users',
'username' => 'required|min:5|unique:users|regex:/^\S*$/u',
'password' => 'required|string|min:6|confirmed',
'country' => 'required',
'state' => 'required',
]);
$email_code = strtoupper(Str::random(6));
$email_time = Carbon::parse()->addMinutes(5);
$phone_code = strtoupper(Str::random(6));
$phone_time = Carbon::parse()->addMinutes(5);
$upliner = Cookie::get('referral');
$uplinerUsername = Cookie::get('referral');
$email_verify = 1;
$phone_verify = 1;
$user = new User();
if($upliner == null){
$upliner = 0;
}
else{
$chkUserRef = User::where('reference', $upliner)->first();
if($chkUserRef == null){
return redirect('register');
}else{
$user_id = $chkUserRef->id;
$upliner = $user_id;
}
}
$data['name'] = $user->name = $request['name'];
$data['email'] =$user->email = $request['email'];
$user->phone = $request['phone'];
$data['username'] = $user->username = $request['username'];
$user->reference = $request['username'];
$user->country = $request['country'];
$user->state = $request['state'];
$user->under_reference = $upliner;
$user->email_verify = $email_verify;
$user->email_code = $email_code;
$user->email_time = $email_time;
$user->phone_verify = $phone_verify;
$user->phone_code = $phone_code;
$user->phone_time = $phone_time;
$data['password'] = $user->password = bcrypt($request['password']);
$saved = $user->save();
if($saved){
//send mail to the registered user
Mail::send('emails.welcome-email', ['data' => $data], function ($message) use ($data) {
$message->from('noreply#example.com', 'example.com')
->to($data['email'], $data['username'], $data['name'])
->subject('Welcome Email');
});
//send mail to Admin
$data['adminEmail'] = "example#gmail.com";
Mail::send('emails.registration-notification', ['data' => $data], function ($message) use ($data) {
$message->from('noreply#example.com', 'example.com')
->to($data['adminEmail'], $data['username'], $data['email'], $data['name'])
->subject('User Registeration Notification');
});
//send mail to referrer
if($uplinerUsername != null){
$chkReff = User::where('username',$uplinerUsername)->first();
if($chkReff == null){
return redirect('register');
}
else{
//get the person's details and send mail
$userReff = User::where('username',$uplinerUsername)->first();
$data['userEmail'] = $userReff->email;
$data['refUsername'] = $userReff->username;
Mail::send('emails.referral-notification', ['data' => $data], function ($message) use ($data) {
$message->from('noreply#example.com', 'example.com')
->to($data['userEmail'], $data['username'],
$data['refUsername'], $data['userEmail'], $data['email'], $data['name'])
->subject('Referral Notification');
});
}
}
return redirect('login');
}
`

error is occured at the run time when 2 tables are insering in 1 function at the same time

//Controller
public function create(Request $request)
{
// dd($request->all());
$this->validate($request, [
'emp_nm' => 'required',
'emp_email' => 'required | email',
'emp_password' => 'required' ,
'mobile' => 'required | max:20' ,
'emp_type_id' => 'required',
'emp_img' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$employee = new Employee();
$employee->emp_nm = $request->input('emp_nm');
$employee->emp_email = $request->input('emp_email');
$employee->emp_password = Hash::make($request->input('emp_password'));
$employee->mobile = $request->input('mobile');
$employee->emp_type_id = $request->input('emp_type_id');
if ($request->hasfile('emp_img')) {
$file = $request->file('emp_img');
$extention = $file->getClientOriginalExtension(); // get img extension
$filename = time() . '.' . $extention;
$file->move('upload/employee/',$filename);
$employee->emp_img = $filename;
}else{
return $request;
$employee->emp_img = '';
}
$employee->save();
$id = $employee->id;
$created_at = $employee->created_at;
$updated_at = $employee->updated_at;
$post = Employee::find($id);
// $created = Employee::get('created_at');
// $updated = Employee::get('updated_at');
$employee = DB::table('employees')->get();
$admin = new Admin();
$admin->name = $request->input('emp_email');
$admin->password = $request->input('emp_password');
$admin->employee_id = $post;
// $admin->created_at = $created;
// $admin->updated_at = $updated;
$admin->save();
return redirect()->back();
}
//ERROR
SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer
value:
'{"id":1,"emp_nm":"admin","emp_email":"admin#gmail.com","emp_password":"$2y$10$NLkdEn1ohHvHKU/uummrvOrwhJ3iEy7PPfxpk9dj9u6.pOVu1' for column mycrm.admins.employee_id at row 1 (SQL: insert into
admins (name, password, employee_id, updated_at,
created_at) values (admin#gmail.com, admin#1234#,
{"id":1,"emp_nm":"admin","emp_email":"admin#gmail.com","emp_password":"$2y$10$NLkdEn1ohHvHKU/uummrvOrwhJ3iEy7PPfxpk9dj9u6.pOVu10YTa","mobile":9426399403,"emp_type_id":"1","emp_img":"1581590201.jpg","created_at":"2020-02-13
10:36:41","updated_at":"2020-02-13 10:36:41"}, 2020-02-13 10:36:41,
2020-02-13 10:36:41))
In the Controller the code is inserting 2 tables at the same time now it is return the error of date formate if i am assign date so it is..
Unexpected data found.
Trailing data
so how i can solve this error??
Your code is wrong $admin->employee_id = $post;
Try to use $admin->employee_id = $post->id;
Your first table insertion is correct. But when you insert record in the admin is wrong:
So update your code:
$id = $employee->id;
$admin = new Admin();
$admin->name = $request->input('emp_email');
$admin->password = $request->input('emp_password');
$admin->employee_id = $id;
$admin->created_at = $created;
$admin->updated_at = $updated;
$admin->save();

Laravel Validation is validating data but then redirecting to the same page with the inputs without executing the following code

Here is my code for validation.
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|email|unique:users',
'phone' => 'required|unique:users',
'user_name' => 'required|unique:users',
'operator_name' => 'required|max:255',
'operator_nid' => 'required|numeric|unique:operators',
'operator_password' => 'required',
'operator_gender' => 'required',
'operator_birthday' => 'required',
]);
if ($validator->fails()) {
return redirect('operator/create')
->withErrors($validator)
->withInput();
}
$user = new User;
$user->name = $request->operator_name;
$user->email = $request->email;
$user->phone = $request->phone;
$user->user_name = $request->user_name;
$user->password = bcrypt($request->password);
$user->type = 3;
$user->save();
$operator = new Operator;
$operator->operator_name = $request->operator_name;
$operator->operator_email = $request->email;
$operator->operator_phone = $request->phone;
$operator->operator_nid = $request->operator_nid;
$operator->operator_user_name = $request->user_name;
$operator->user_id = $user->id;
$operator->type = 3;
$operator->operator_gender = $request->operator_gender;
$operator->operator_birthday = $request->operator_birthday;
$operator->operator_occupation = $request->operator_occupation;
$operator->operator_facebook = $request->operator_facebook;
$operator->operator_twitter = $request->operator_twitter;
$operator->operator_gplus = $request->operator_gplus;
$operator->operator_address = $request->operator_address;
if ($request->hasfile('operator_pro_pic')){
$image = $request->file('operator_pro_pic');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('images/operator/' . $filename);
Image::make($image)->resize(950, 700)->save($location);
$operator->operator_pro_pic = $filename;
}
$operator->save();
return $user;
}
I am trying to create an operator and a user at the same time. email, phone and user_name should be unique in the user's table and other data will be validate from the operators table. Validation is working as it is giving me the errors but after validating it's not going further. So my code after the validation is not executing. What is the possible reason for this?
You can use -
if ($validator->fails()) {
return back()->withInput()
->withErrors($validator);
}
The better way will be to create a request file by using
php artisan make:request requestName
define all the validation in there. In this case if your validation fails the application will return back with error and old-inputs without reaching to the controller.

Categories