Insert fields after success payment - laravel

Hope you all have a good day..
At first i have a form that user should fill before redirect to PayTabs page for payment
But i don't need the form to be inserted in database before success payment
public function index(Request $request): RedirectResponse
{
$response = $this->request(
url: 'https://secure-global.paytabs.com/payment/request',
payload: $this->transactionPayload(
amount: 0
)
);
Transaction::create([
'paytabs_transaction_reference' => $response->json()['tran_ref'] ?? null
]);
Cart::where('opened', '=', 0)->where('user_id', Auth::id())->update(['paytabs_transaction_reference' => $response->json()['tran_ref'] ?? null]);
$cart_id = Cart::latest()->first()->id;
$payment = new Payment;
$payment->cart_id = $cart_id;
$payment->country_id = $request->input('country_id');
$payment->delivery_id = $request->input('delivery_id');
$payment->address = $request->input('address');
$payment->street = $request->input('street');
$payment->home = $request->input('home');
$payment->email = $request->input('email');
$payment->save();
return redirect()->away($response['redirect_url']);
}
public function return(Request $request): string
{
$category = Category::all();
$products = Product::all();
$validSignature = $this->validateSignature($request->all());
if ($validSignature) {
if ($request->respStatus == 'A') {
$transaction = Transaction::where('paytabs_transaction_reference', $request->tranRef)->first();
$transaction->paid = true;
$transaction->save();
DB::table('carts')->where('user_id', Auth::id())->where('opened', 0 )->update(['opened' => 1]);
return view('index', compact('category', 'products'))->with('success', 'Payment has been done successfully. Thank you!') . $request->respMessage;
}
return view('index', compact('category', 'products')) . $request->respMessage;
} else {
return 'Invalid Transaction Signature';
}
}
Here the form will be inserted even if he back from the next page
<form role="form" action="{{ route('index') }}" method="post">
#csrf
.......
</form>
That's my form should be to INDEX function to redirect to payment page

You Need To Make A Validation To Your Form

Related

Laravel: how can i get files from database in edit form. so i dont have to reupload if i dont want to change the files

blade edit
<form action="/files" method="POST" enctype="multipart/form-data">
{{csrf_field()}}
<label for="dokumen">Dokumen Awal : ({{$aktivitas_list->dokumen}}) <br><i>Upload Ulang Dokumen</i></label>
<input type="file" id="dokumen" name="dokumen" accept=".pdf" class="form-control" value="{{$aktivitas_list->dokumen}}">
#if ($errors->has('dokumen'))
<span class="text-danger">{{ $errors->first('dokumen') }}</span>
#endif
controller store
$aktivitas_list = new Aktivitas;
$aktivitas_list->pt_id = $request->get('pt_id');
$aktivitas_list->nama_aktivitas = $request->get('nama_aktivitas');
$aktivitas_list->tgl_aktivitas = $request->get('tgl_aktivitas');
$aktivitas_list->tempat = $request->get('tempat');
$aktivitas_list->jenis_aktivitas = $request->get('jenis_aktivitas');
$aktivitas_list->dokumen = $request->file('dokumen');
$aktivitas_list->tenggat_waktu = $request->get('tenggat_waktu');
$aktivitas_list->deskripsi = $request->get('deskripsi');
$aktivitas_list->status = $request->get('status');
$aktivitas_list->user = $request->get('user');
$rules = array(
'nama_aktivitas' => 'required',
'dokumen' => 'required|mimes:pdf'
);
$dokumen = $request->file('dokumen');
$tujuan_upload = 'document-upload';
$dokumen->move($tujuan_upload, $dokumen->getClientOriginalName());
$aktivitas_list->dokumen = $dokumen->getClientOriginalName();
if ($aktivitas_list->save()) {
return redirect('pt')->with('success', 'Data Berhasil Ditambahkan');
} else {
return redirect('pt')->with('error', 'error message');
}
}
controller update
$rules = array(
'nama_aktivitas' => 'required',
'dokumen' => 'required|mimes:pdf'
);
$dokumen = $request->file('dokumen');
$tujuan_upload = 'document-upload';
$dokumen->move($tujuan_upload, $dokumen->getClientOriginalName());
$aktivitas_list->dokumen = $dokumen->getClientOriginalName();
$aktivitas_list->status = $status=1;
$aktivitas_list->user = Auth::user()->name;
$user = Auth::user()->name;
if ($aktivitas_list->save()) {
return redirect('pt')->with('success', 'Data Berhasil Ditambahkan');
} else {
return redirect('pt')->with('error', 'error message');
}
The problem is, if I don't select again the file when I update the data so the data is null. for example i just want to edit field nama aktivitas and not change the files. and another example i want to update all field. how can i get the files beside the browse button? how can i solve them? please guys help me
In Controller on update method
Make file as optional.
Check if request has file then make process of upload.
in view you can't set file input value for security reason.
$rules = array(
'nama_aktivitas' => 'required',
'dokumen' => 'nullable|mimes:pdf'//make file as optional
);
if($request->file('dokumen')){//check if file are exists on request
$dokumen = $request->file('dokumen');
$tujuan_upload = 'document-upload';
$dokumen->move($tujuan_upload, $dokumen->getClientOriginalName());
$aktivitas_list->dokumen = $dokumen->getClientOriginalName();
}
$aktivitas_list->status = $status=1;
$aktivitas_list->user = Auth::user()->name;
$user = Auth::user()->name;
if ($aktivitas_list->save()) {
return redirect('pt')->with('success', 'Data Berhasil Ditambahkan');
} else {
return redirect('pt')->with('error', 'error message');
}
you can check if file existed then upload it and save file's new name in database and if file didn't exist just escape this field so old value remain in database.
if($request->hasFile()) {
}
See docs here
public function update(Request $request)
{
$rules = array(
'nama_aktivitas' => 'required',
'dokumen' => 'sometimes|mimes:pdf'
);
//Validation of request data
if($request->hasFile('dokumen') && $request->file('dokumen')->isValid()){
$dokumen = $request->file('dokumen');
$tujuan_upload = 'document-upload';
$dokumen->move($tujuan_upload, $dokumen->getClientOriginalName());
//Since your provided code snippet for update is truncated
// don't know how $aktivitas_list is instantiated
$aktivitas_list->dokumen = $dokumen->getClientOriginalName();
}
$aktivitas_list->status = $status=1;
$aktivitas_list->user = Auth::user()->name;
$user = Auth::user()->name;
if ($aktivitas_list->save()) {
return redirect('pt')->with('success', 'Data Berhasil Ditambahkan');
} else {
return redirect('pt')->with('error', 'error message');
}
}

Display name instead of id in url laravel

I would just like to ask how do I display the name of the business instead of it's id.
It's currently displayed like this, localhost:8000/1/Belen'sChoice and desired output is
localhost:8000/Belen'sChoice. I can get the name however it says 'trying to find id'.
Controller
public function show($id)
{
$categories = Category::all();
$businesses = Business::find($id);
if (Auth::check()) {
$userId = Auth::user()->id;
$users = User::where('id', $userId)->get();
$posts = Post::where('business_id', $businesses->id)->get()->sortByDesc('created_at');
$supporters = Supporter::where('user_id', $userId)->get();
$photos = Image::where('business_id', $businesses->id)->get();
$albums = Album::where('business_id', $businesses->id)->get();
$count = 0;
if ($businesses->user_id != Auth::user()->id) {
$businesses->views = $businesses->views + 1;
$businesses->save();
} else {
$businesses->views = $businesses->views;
}
return view('businesses.index', [
'categories' => $categories,
'businesses' => $businesses,
'users' => $users,
'posts' => $posts,
'supporters' => $supporters,
'count' => $count,
'images' => $photos,
'albums' => $albums,
]);
} else {
return view('businesses.index', [
'categories' => $categories,
'businesses' => $businesses,
]);
}
}
Blade
<a class="text-center" href='{{ url("/businessprofile/".$business->id."/".str_replace(" ", "" ,$business->name)) }}'><img class="bprof-img" src='{{ asset("storage/$business->logo") }}'>{{ $business->name }}</a>
Web.php
Route::get('/businessprofile/{id?}/{name}', 'BusinessController#show');
TIA
take one Column in your business migration
$table->string('slug')->unique();
and save it like this way in your controller
//use this at the bottom of your controller
use Illuminate\Support\Str;
$business = new Business;
$business->slug = Str::slug($request->name) // whatever you request dring //creating a business row
//and after that save it
$business->save();
then in your controller find the row using slug
public function show($slug)
{
$business = Business::where('slug',$slug)->first();
//and rest of your operation
}
href='{{ url("/".str_replace(" ", "" ,$business->slug))}}'
then in your web
Route::get('/{slug}', 'BusinessController#show');

How to update 2 table data using query builder

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.

Codeigniter User's Data

Hi guys I have a User controller and User_model model. I want to be able to retrieve and display a logged in users email and phone number from the database to a view after the user is logged in. any idea how I could go about this would be appreciated and if codes could be written to demonstrate I would be very happy.
MODEL
public function login($username, $password){
//validation
$this->db->select('id, email, username');
$this->db->where('username', $username);
$this->db->where('password', $password);
$this->db->where('status', 1);
$result = $this->db->get('users');
if($result->num_rows() == 1){
return $result->row(0)->id;
} else {
return FALSE;
}
}
public function get_user($username){
$this->db->where('username', $username);
$query = $this->db->get('users');
return $query->result();
}
CONTROLLER:
public function login(){
$data['title'] = 'Login';
$this->form_validation-> set_rules('username', 'Username', 'required');
$this->form_validation-> set_rules('password', 'Password', 'required');
if($this->form_validation->run() === FALSE){
$this->load->view('templates/header');
$this->load->view('users/login', $data);
$this->load->view('templates/footer');
} else {
// fetching user
$username = $this->input->post('username');
//Encrypted password
$password = md5($this->input->post('password'));
//login user
$user_id = $this->user_model->login($username, $password);
if($user_id){
//creating session
$user_data = array(
'user_id' => $user_id,
'username' => $username,
'logged_in' => TRUE,
);
$this->session->set_userdata('user_data',$user_data);
// Set message to be sent
$this->session->set_flashdata('user_login', 'Welcome');
redirect('posts');
} else {
// Set message to be sent
$this->session->set_flashdata('login_fail', 'Login Failed');
redirect('users/login');
}
}
}
public function get_user()
{
if($this->session->userdata('logged_in')){
$username = $this->session->userdata('username');
$data['results'] = $this->user_model->get_user($username);
$this->load->view('templates/header');
$this->load->view('users/login', $data);
$this->load->view('templates/footer');
}
}
There is basic problem in your Controller
Session Data Problem: In your Controller you storing all array data in CodeIgniter Session:
the 'user_data' would work like array key, and all other array will be assign as keys data;
$this->session->set_userdata('user_data', $user_data);
and you retrieving/checking the session data by using $this->session->userdata('logged_in') and $this->session->userdata('username'), It's wrong my friend. You can get user data session by $this->session->userdata('user_data')['username'] or $this->session->userdata['user_data']['username'] ...
Because the session would be like;
Array
(
[__ci_last_regenerate] => 1499791562
// This is the array key 'user_data' where your array data stores
[user_data] => Array
(
[user_id] => 1
[username] => scott
[email] => scott.dimon#example.com
[phone_number] => 1234567890
[first_name] => Scott
[logged_in] => 1
)
)
So, you have to have use 'user_data' with session to get your data
One thing I would like to share with everyone, Always Read The Docs and manual Carefully. Believe me if you read before the start, your code would be more nicer and cleaner... Ha ha ha ha ha.. ;) :|
When you login if you set the users_id in session you can get the information like
Read manual also
https://www.codeigniter.com/user_guide/database/results.html#result-rows
https://www.codeigniter.com/user_guide/general/views.html#adding-dynamic-data-to-the-view
Make sure you autoload session, and database.
Examples ONLY below.
Filename: User_model.php
class User_model extends CI_Model {
public function get_user($id)
{
$this->db->where('user_id', $id);
$user_query = $this->db->get('yourtable');
return $user_query->row_array();
}
}
Filename: Dashboard.php
Controller
<?php
class Dashboard extends CI_Controller {
public function __construct()
{
parent::__construct();
if (!$this->session->userdata('user_id'))
{
redirect('logoutcontroller');
}
$this->load->model('user_model');
}
public function index()
{
$userdata = $this->user_model->get_user($this->session->userdata('user_id'));
/** You can use what you want example
$data['email'] = $userdata['email'];
**/
$data['username'] = $userdata['username'];
$this->load->view('some_view', $data);
}
}
View
<?php echo $username;?>
You can use session to carry the logged in user detail.
This is your model code:
//In your model
$query = $this->db
->select('id,email,phone')
->where(['username' => $username, 'password' => $password])
->where('status','1')
->get('users');
$user_data = $query->row_array();
if (!empty($user_data)) {
return $user_data;
} else {
return FALSE;
}
In side the controller where you get the user data if username & password is correct. Here you can put the user data on session:
//In Side Controller
$user_data = $this->user_model->login($username, $password);
if(isset($user_data) && !empty($user_data)){
// you can directly add the `$user_data` to the session as given billow.
// set user data in session
$this->session->set_userdata('user_data', $user_data);
Now after putting a data on session you can retrive it any where, on any view or in side morel, controller.
//retrive the user data in any view
//To echo in view Inside your view code.
<?php
$session_data = $this->session->userdata('user_data');
$user_email = $session_data['email'];
$user_phone = $session_data['phone'];
$user_id = $session_data['id'];
?>
<?= $user_phone ?> OR <?php echo $user_phone; ?>
<?= $user_email ?> OR <?php echo $user_email; ?>
On Your $this->load->view('users/login', $data); this view. Where the HTML & PHP code placed.
Example:
<html>
// Your View Page
</body>
<?php
$session_data = $this->session->userdata('user_data');
$user_email = $session_data['email'];
$user_phone = $session_data['phone'];
$user_id = $session_data['id'];
?>
<h1> Logged In User Email: <?= $user_email ?> </h1>
<h1> Logged In User Phone: <?= $user_phone ?> </h1>
<body>
</html>
Note: Once You save the user data inside the session then you don't need to pass that data to the view form controller. You just need to echo it where you need that.
You need to load session library first. like
$this->load->library('session');
Then after you can save your data into session like,
$newdata = array(
'username' => 'johndoe',
'email' => 'johndoe#some-site.com',
'logged_in' => TRUE
);
$this->session->set_userdata($newdata);
Then where ever you require at controller you can retrive session data like,
$data['session_data'] = $this->session->all_userdata();
and then pass to your view,
$this->load->view('data', $data);
and then access that data into your view with the key,
<?= $session_data['username']; ?>
I hope it helps,
Does this answer your question?
public function login($username, $password){
$db = $this->db;
//validation
$db->select('id, email, username');
$db->where('username', $username);
$db->where('password', $password);
$db->where('status', 1);
$result = $db->get('users')->row_array();
return empty($result['id']) ? false : $result['id'];
}
With a unique index on username you won't need to check the number of rows as it will be limited to 1.
if($user_id){
//creating session
$user_data = array(
'user_id' => $user_id,
'username' => $username,
'logged_in' => TRUE,
);
$this->session->set_userdata($user_data);
// Set message to be sent
$data['session_data'] = $this->session->all_userdata();
$this->session->set_flashdata('user_login', 'Welcome');
$this->load->view('posts', $data);
//redirect('posts');
}
else {
// Set message to be sent
$this->session->set_flashdata('login_fail', 'Login Failed');
redirect('users/login');
}
}
at the view,
<?php print_r($session_data); ?>
if you get your session data into print,
you can display it like,
<?= $session_data['user_id']; ?>
****Modal**
//user login**
function userlogin($data)
{
$condition = "username =" . "'" . $data['username'] . "' AND " . "password =" . "'" . $data['password'] . "' AND " . "status = '1'";
$this->db->select("*");
$this->db->from("user");
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1)
{
return $query->result();
}
else {
return false;
}
}
And in your Controller check
if($this->modal_name->login()==false)
{
//redirect user to login page
}
else
{
$data['details'] = $this->modal_name->login();
$this->load->view("post",$data);
}
View
foreach($details as $detail)
{
echo $detail->id;
echo $detail->username;
}

Laravel - update one to one field

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);
}
}

Resources