Upload multiple forms no save in mysql database laravel 9 - mysql

could someone help me to find the error? only the post_image input is saved the others are not saved in the database what am I doing wrong?
I've checked it several times but only the filename of the post_image field is saved in the database, the other files are not persisting in the database, could someone help me where I'm going wrong?
Every help is welcome.
Thank you very much in advance.
create.blade.php
div class="form-group row">
<label for="post_image" class="col-md-4 col-form-label text-md-right">{{ __('Image') }}</label>
<div class="col-md-6">
<input type="file" name="post_image"/>
#error('post_image')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<br>
<hr>
<label for="post_video" class="col-md-4 col-form-label text-md-right">{{ __('Video') }}</label>
<div class="col-md-6">
<input type="file" name="post_video"/>
#error('post_video')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<br>
<hr>
<label for="post_gif" class="col-md-4 col-form-label text-md-right">{{ __('GIF') }}</label>
<div class="col-md-6">
<input type="file" name="post_gif"/>
#error('post_gif')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<br>
<hr>
</div>
function store in controller -->
public function store(Request $request, Community $community)
{
$user = Auth::user();
$creds = $request->validate([
'post_image' => '|image|mimes:jpeg,jpg,png,svg|max:18048',
'post_video' => 'mimes:mp4,ogx,oga,ogv,ogg,webm|max:180048',
'post_gif' => '|image|mimes:gif|max:18048',
'title' => ['required'],
'post_text' => ['required'],
'post_url' => ['required']
]);
//IMAGE JPG,PNG,SVG
if ($image = $request->file('post_image')) {
$destinationPath = 'media/uploads';
$profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $profileImage);
$input['post_image'] = "$profileImage";
}
//END IMAGE JPG,PNG,SVG
//VIDEO MP4
if ($image = $request->file('post_video')) {
$destinationPath = 'media/uploads';
$profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $profileImage);
$inputmp4 ['post_video'] = "$profileImage";
}
//END VIDEOS
// GIF IMAGES
if ($image = $request->file('post_gif')) {
$destinationPath = 'media/uploads';
$profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $profileImage);
$inputgif ['post_gif'] = "$profileImage";
}
//END GIF IMAGES
$post = $community->posts()->create
(['user_id' => auth()->id(),
'title' => $creds['title'],
'post_text' => $creds['post_text'],
'post_url' => $creds['post_url'],
'post_image' => $input['post_image'] ?? '',
'post_video' => $inputmp4['post_video'] ?? '',
'post_gif' => $inputgif['post_gif'] ?? '',
]);
return redirect()->route('communities.show', $community);
}

Is it possible post_video and post_gif are empty? Php has a max_upload and max post size limit that is defined on the ini file. It is possible that that size is being exceeded. Hence your files are not actually uploading.
Also, your if statements are kinda confusing. Check this out :
//This if statement will always return true. Since you're assigning $image variable to $request->file('post_video').
if ($image = $request->file('post_video')) {
//Code For saving file
//Don't use this
}
// Instead you should use hasFile to check if the file is uploaded. here's how
if ($request->hasFile('post_video')) {
$video = $request->file('post_video');
//Code For saving file
//Use This instead
}
Also, at the last line, where you call create() method, do this:
$post = $community->posts()->create
(['user_id' => auth()->id(),
'title' => $creds['title'],
'post_text' => $creds['post_text'],
'post_url' => $creds['post_url'],
'post_image' => $input['post_image'], // skip the "?? ''" part
'post_video' => $inputmp4['post_video'],
'post_gif' => $inputgif['post_gif'],
]);
Now, if either post_image, post_video or post_gif is empty, you'll get a error and can see if the data is wrong.
Also, on a kinda related note, did you know laravel has a good helper to save files in storage? Check it out

Related

How to just use json and ajx for Realtime notification in laravel 9

I have a function here which is needed to generate ticket. What is working rights is when Generating a ticket, it also creates a notification, but it was not real-time showing in the notification bell.
After a search, I found that using post-json and ajax is feasible. But I just started learning programming so I have zero knowledge about these two technologies. I hope someone can provide me with some help on how to use them.
PS. I also found that web socket and pusher are also viable solutions, but since my system only has few functions that need to send notifications. So I don't take websocket and pusher into consideration.
Translated with www.DeepL.com/Translator (free version)
I would like to attach my code below and hope somebody could help me. Any suggestion is highly appreciated. Thankyou in advance
In my controller
public function GenerateTicket($code)
{
# Retrieve the records using $code
$GiftGiving = GiftGiving::where('code', $code)->firstOrFail();
$tickets = GiftGivingBeneficiary::where('gift_giving_id', $GiftGiving->id)->get();
# Users can only access their own charity's records
if ($GiftGiving->charitable_organization_id == Auth::user()->charitable_organization_id) {
# Must have at least one beneficiary before generating tickets
if ($tickets->count() < 1) {
$notification = array(
'message' => 'Gift Giving must have at least one (1) beneficiary first before generating tickets',
'alert-type' => 'error'
);
return redirect()->back()->with($notification);
}
# Retrieve the last batch no. from the gift giving.
$batch_no = $GiftGiving->batch_no;
# Increment Batch no. by +1
$GiftGiving->update([
'last_downloaded_by' => Auth::id(),
'batch_no' => $batch_no + 1,
]);
$pdf = PDF::loadView('charity.gifts.generate_ticket', compact('tickets'));
# Audit Logs Creation
$log = new AuditLog;
$log->user_id = Auth::user()->id;
$log->action_type = 'GENERATE PDF';
$log->charitable_organization_id = Auth::user()->charitable_organization_id;
$log->table_name = 'Gift Giving';
$log->record_id = $GiftGiving->code;
$log->action = 'Charity Admin generated tickets for the Gift Giving [' . $GiftGiving->name . '] with batch no. ' . $GiftGiving->batch_no . '.';
$log->performed_at = Carbon::now();
$log->save();
# Send Notification to each user in their Charitable Organizations
$users = User::where('charitable_organization_id', Auth::user()->charitable_organization_id)->where('status', 'Active')->get();
foreach ($users as $user) {
Notification::insert([
'code' => Str::uuid()->toString(),
'user_id' => $user->id,
'category' => 'Gift Giving',
'Subject' => 'Generated Tickets',
'message' => Auth::user()->role . ' ' . Auth::user()->info->first_name . ' ' . Auth::user()->info->last_name . ' has generated tickets for ['.$GiftGiving->name.'] with batch no. ' . $GiftGiving->batch_no . '.',
'icon' => 'mdi mdi-ticket',
'color' => 'info',
'created_at' => Carbon::now(),
]);
}
return $pdf->download($GiftGiving->name . ' - No. ' . $batch_no . '.pdf');
} else {
$notification = array(
'message' => 'Users can only access their own charity records.',
'alert-type' => 'error'
);
return redirect()->back()->with($notification);
}
}
The view for the header
<div class="dropdown-menu dropdown-menu-lg dropdown-menu-end p-0"
aria-labelledby="page-header-notifications-dropdown">
<div class="p-3">
<div class="row align-items-center">
<div class="col">
<h6 class="m-0"> Notifications </h6>
</div>
<div class="col-auto">
View All
</div>
</div>
</div>
#include('charity.body.notifications')
<div class="p-2 border-top">
<div class="d-grid">
<a class="btn btn-sm btn-link font-size-14 text-center" href="{{ route('notifications.all') }}">
<i class="mdi mdi-arrow-right-circle me-1"></i> View all..
</a>
</div>
</div>
</div>
</div>
THe view for notification
#php
$notifications = App\Models\Notification::latest()->limit(3)->get();
#endphp
<div data-simplebar style="max-height: 230px;">
#if(Auth::user()->notifications->count() == 0)
<p class="text-muted font-size-12 text-center">You have no new notifications.</p>
#endif
#foreach (Auth::user()->notifications as $notif)
<a href="{{ route('notifications.view' , $notif->code) }}" class="text-reset notification-item">
<div class="d-flex">
<div class="avatar-xs me-3">
<span class="avatar-title bg-{{$notif->color}} rounded-circle font-size-16">
<i class="{{$notif->icon}}"></i>
</span>
</div>
<div class="flex-1">
<h6 class="mb-1">{{ $notif->subject}} #if($notif->read_status == 'unread')<span class="badge bg-danger">NEW</span>#endif</h6>
<div class="font-size-12 text-muted">
<p class="mb-1">{{Str::limit($notif->message, 75)}}</p>
<p class="mb-0"><i class="mdi mdi-clock-outline"></i> {{Carbon\Carbon::parse($notif->created_at)->diffForHumans()}}</p>
</div>
</div>
</div>
</a>
#endforeach
</div>

Insert data excel into 2 tables with id codeigniter

I have a problem with how to upload files excel with phpsreadsheet to the database. I want to put the data into two tables namely:
Beasiswa contain table: beasiswa_nama, beasiswa_id, beasiswa_file (link file), beasiswa_tahun, DATE_CREATED, DATE_UPDATED.
data_mahasiswa table cotain table: id_mhs, nama_mhs, nim_mhs, (FK) id_beasiswa
How to insert a file and read it to the Beasiswa table, and student data to data_mahasiswa?
Relation table:
Error create data:
Beasiswa Controller
public function create()
{
$this->form_validation->set_rules('nama_beasiswa', 'Nama Beasiswa', 'trim|required');
$this->form_validation->set_rules('tahun_beasiswa', 'Tahun Mahasiswa', 'trim|required');
if (empty($_FILES['nama_mahasiswa_beasiswa']['name'])) {
$this->form_validation->set_rules('nama_mahasiswa_beasiswa', 'File Nama Mahasiswa', 'required');
}
if ($this->form_validation->run() == TRUE) {
// true case
$upload_nama_mahasiswa = $this->_upload_nama_mahasiswa();
$data = array(
'beasiswa_nama' => htmlspecialchars($this->input->post('nama_beasiswa', true)),
'beasiswa_tahun' => htmlspecialchars($this->input->post('tahun_beasiswa', true)),
'beasiswa_file' => $upload_nama_mahasiswa,
'date_created' => date("Y-m-d H:i:s")
);
$create = $this->m_beasiswa->create($data);
if ($create == true) {
$this->session->set_flashdata('success', 'Berhasil Upload Data Beasiswa');
redirect('beasiswa/', 'refresh');
} else {
$this->session->set_flashdata('errors', 'Terjadi Galat. Silahkan Periksa Kembali!!');
redirect('beasiswa/create', 'refresh');
}
} else {
$this->render_template('beasiswa/create', $this->data);
}
}
private function _upload_nama_mahasiswa()
{
$filename = 'import-data';
$config['upload_path'] = 'assets/file/beasiswa/';
$config['file_name'] = $filename;
$config['overwrite'] = TRUE;
$config['allowed_types'] = 'xlsx|xls';
$config['max_size'] = '1024';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('nama_mahasiswa_beasiswa')) {
// $error = array('errors' => $this->upload->display_errors('File yang anda masukkan tidak sesuai permintaan, atau file terlalu besar.'));
$this->session->set_flashdata('errors', 'File yang anda masukkan tidak sesuai permintaan, atau file terlalu besar.');
redirect('beasiswa/create', 'refresh');
} else {
$data = array('upload_data' => $this->upload->data());
$img = $data['upload_data']['file_name'];
$excelReader = new PhpOffice\PhpSpreadsheet\Reader\Xlsx();
$loadExcel = $excelReader->load($config['upload_path'] . $img);
$sheet = $loadExcel->getActiveSheet()->toArray(null, true, true, true);
$dataExcel = array();
// $this->data['sheet'] = $sheet;
$numRow = 3;
foreach ($sheet as $row) {
if ($numRow > 3) {
array_push(
$dataExcel,
[
'nama_mhs' => $row['A'],
'nim_mhs' => $row['B']
]
);
}
$numRow++;
}
$this->db->insert_batch('data_beasiswa', $dataExcel);
unlink($config['upload_path'] . $img);
}
}
Beasiswa Model
public function create($data)
{
if ($data) {
$insert = $this->db->insert('beasiswa', $data);
return ($insert == true) ? true : false;
}
}
Beasiswa View
<?php
defined('BASEPATH') or exit('No direct script access allowed');
?>
<!-- Main Content -->
<div class="main-content">
<section class="section">
<div class="section-header">
<div class="section-header-back">
<i class="fas fa-arrow-left"></i>
</div>
<h1>Tambah Beasiswa</h1>
</div>
<div class="section-body">
<div class="row">
<div class="col-md-12 col-xs-12 col-xl-12 col-12">
<div id="messages"></div>
<?php if ($this->session->flashdata('success')) : ?>
<div class="alert alert-success alert-dismissible">
<div class="alert-body">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<?php echo $this->session->flashdata('success'); ?>
</div>
</div>
<?php elseif ($this->session->flashdata('errors')) : ?>
<div class="alert alert-danger alert-dismissible show fade">
<div class="alert-body">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<?php echo $this->session->flashdata('errors'); ?>
</div>
</div>
<?php endif; ?>
<div class="card">
<div class="card-body">
<b style="font-size: 17px">Unduh format excel data mahasiswa</b><br>
Download template
<form action="<?php base_url('beasiswa/create') ?>" method="POST" enctype="multipart/form-data">
<div class="form-group">
<div class="section-title">Nama Program Beasiswa</div>
<input type="text" class="form-control" name="nama_beasiswa" id="nama_beasiswa" placeholder="Nama Program Beasiswa" value="<?= set_value('nama_beasiswa'); ?>">
<?= form_error('nama_beasiswa', '<small class="text-danger">', '</small>'); ?>
</div>
<div class="form-group">
<div class="section-title">Tahun Beasiswa</div>
<input type="text" class="form-control" name="tahun_beasiswa" id="tahun_beasiswa" placeholder="Tahun Beasiswa (contoh: 2020)" value="<?= set_value('tahun_beasiswa'); ?>">
<?= form_error('tahun_beasiswa', '<small class="text-danger">', '</small>'); ?>
</div>
<div class="form-group">
<div class="section-title">Upload File Nama Mahasiswa</div>
<input type="file" name="nama_mahasiswa_beasiswa" id="nama_mahasiswa_beasiswa" class="form-control col-sm-6 col-md-6">
<p class="text-danger" style="font-style:italic"><b>* Upload file sesuai dengan format yang sudah disesuaikan</b></p>
</div>
<button type="submit" class="btn btn-primary">Simpan</button>
Kembali
</form>
</div>
</div>
</div>
</div>
</div>
</section>
</div>
It is because foreign key error probably happening because you insert a null data in data_mahasiswa table.
There was empty space in your excel (that probably have been edited?) that are used in foreach ($sheet as $row). You can fix this with:
foreach ($sheet as $row) {
if ($numRow > 3) {
if($row['A'] != null && $row['B'] != null)
{
$dataExcel[] = array(
'nama_mhs' => $row['A'],
'nim_mhs' => $row['B']
);
}
/*you can also break the function, if no empty row between data in your excel*/
/*else
{
break;
}*/
}
}
you need to get rid of the null value when you input the data to the database. above this line of your code at Beasiswa Controller
$this->db->insert_batch('data_beasiswa', $dataExcel);
add this line of code to delete cell that have null data
foreach ($dataExcel as $data => $val) {
if(empty($val['nama_mhs'])){
unset($dataExcel[$data]['nama_mhs']);
unset($dataExcel[$data]['nim_mhs']);
}
}
$dataExcel = array_filter($dataExcel);
$data = array('data_excel' => $dataExcel);

Can't get input value with Twig

Hello I was trying to pass some arguments but I don't know how to get value of input using twig here is my code :
okey first of all im displaying the blog details using this detailsaction which also rendering a form to add comments to the blog ;
public function detailsAction(Request $request,Blog $blog){
$user=$this->getUser();
if($user==null)
return $this->redirectToRoute('fos_user_security_login');
$add_comment = new CommentaireBlog();
$em = $this->getDoctrine()->getManager();
$comments = $em->getRepository(CommentaireBlog::class)->findByBlog($blog);
$add_comment->setBlog($blog);
$add_comment->setUser($user);
$add_comment->setDate( new \DateTime());
$form = $this->createFormBuilder($add_comment)
->add('contenu', TextareaType::class)
->getForm();
if ($request->getMethod() == 'POST') {
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$add_comment = $form->getData();
$em = $this->getDoctrine()->getEntityManager();
$em->persist($add_comment);
$em->flush();
return $this->redirectToRoute('blog_details', array('id' => $blog->getId()));
}
}
return $this->render('blog/details.html.twig', array(
'form' => $form->createView(),
'comment' => $add_comment,
'blog' => $blog,
'comments'=>$comments,
));
}
twig page:
{{ form_start(form) }}
<div class="row form-group">
<div class="col col-md-3"><label class=" form-control-label">Votre Commentaire </label></div>
<div class="col-12 col-md-9"> {{ form_widget(form.contenu, { 'attr': {'class': 'form-control'} }) }}<small class="form-text text-muted"></small></div>
<button type="submit" class="btn btn-default">Envoyer</button>
<div class="col-12 col-md-9">
</div>
</div>
{{ form_end(form) }}
now what i want to do is that after someone add a comment and its(racist/verbual abuse..) an other user can report the comment and a mail will be sent so i used reportAction which take three arguments the reason the message and comment id
public function reportAction($msg,$type,$id)
{
}
i still didnt write inside it cause first of all i need to the value of inputs so i went to the twig page and i made this little form to get inputs but idk how to get the value
here is the form :
<div class="modal-body">
<form id="lala" method="GET">
<label for="cars">Reason:</label>
<select id="reportreason">
<option value="Inappropriate Content">Inappropriate Content</option>
<option value="Spam">Spam</option>
<option value="Racism">Racism</option>
<option value="Nudity">Nudity</option>
<option value="Other">Other</option>
</select>
<div class="form-group">
<label for="message-text" class="col-form-label">Message:</label>
<textarea id="reportmessage" class="form-control" id="message-text"></textarea>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<a id="reportlink" href="{{ path('comment_report', { 'msg': form.vars.data.reportmessage ,'type': form.vars.data.reportreason, 'id': comment.id }) }}" type="button" class="btn btn-primary">Send message</a>
</div>
this is yml file :
blog_details:
path: /{id}/details
defaults: { _controller: "BlogBundle:Blog:details" }
methods: [GET, POST]
comment_report:
path: /{msg}/{type}/{id}/report
defaults: { _controller: "BlogBundle:Blog:report" }
methods: [GET, POST]
but im getting this error now :
Neither the property "reportmessage" nor one of the methods "reportmessage()", "getreportmessage()"/"isreportmessage()" or "__call()" exist and have public access in class "BlogBundle\Entity\CommentaireBlog".
so how can i get get the value of the inputs using twig ?
Twig Object Syntax https://twigfiddle.com/01iobj
Effectively the twig error message is saying that in your path() arguments, you are passing an object without an associated key as {value} The correct syntax would be {key: value} or [value], resembling a JSON syntax.
{
"key1": { "key1a": "value1a" },
"key2": ["value2"],
"key3": "value3"
}
Result
$_GET = array(
'key1' => array('key1a' => 'value1a'),
'key2' => array('value2'),
'key3' => 'value3'
);
A different approach
Looking at what you want to do, you need to refactor your approach.
First change your controller pathing for ONLY the comment.
blog_details:
path: /{id}/details
defaults: { _controller: "BlogBundle:Blog:details" }
methods: [GET, POST]
comment_report:
path: /{comment}/report
defaults: { _controller: "BlogBundle:Blog:report" }
methods: [POST]
Next create a form instance for your modal, this will allow you use the FormInstance for rendering and validating the submitted form elsewhere. Ensuring that all of the validation occurs and you're not having to update different scripts for the same form.
/* /src/Form/CommentReportForm.php */
namespace App\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type as Form;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints as Assert;
class CommentReportForm extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('reason', Form\ChoiceType::class [
'choices' => [
'Inappropriate Content' => 'Inappropriate Content',
'Spam' => 'Spam',
'Racism' => 'Racism',
'Nudity' => 'Nudity',
'Other' => 'Other'
]
])
->add('message', Form\TextType::class, [
'constraints' => [
new Assert\Length(['min' => 10]),
new Assert\NotBlank(),
],
]);
}
public function getBlockPrefix()
{
return 'report_comment_form';
}
}
Next, update your Controller actions accordingly.
public function detailsAction(Request $request, Blog $blog)
{
if (!$user = $this->getUser()) {
//this should be handled in your firewall configuration!!!!
return $this->redirectToRoute('fos_user_security_login');
}
$em = $this->getDoctrine()->getManager();
$add_comment = new CommentaireBlog();
$add_comment->setBlog($blog);
$add_comment->setUser($user);
$add_comment->setDate(new \DateTime());
$form = $this->createFormBuilder($add_comment)
->add('contenu', TextareaType::class)
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
//Symfony form sets values for the model by_reference
$em->persist($add_comment);
$em->flush();
return $this->redirectToRoute('blog_details', array('id' => $blog->getId()));
}
/*
* create the report form
*/
$reportForm = $this->createForm(\App\Form\CommentReportForm::class);
$reportForm->handleRequest($request);
return $this->render('blog/details.html.twig', array(
'form' => $form->createView(),
'comment' => $add_comment,
'blog' => $blog,
'comments'=> $em->getRepository(CommentaireBlog::class)->findByBlog($blog),
/*
* give the report form a different name in twig
*/
'report_form' => $reportForm->createView(),
));
}
public function reportAction(Request $request, CommentaireBlog $comment)
{
$reportForm = $this->createForm(\App\Form\CommentReportForm::class);
$reportForm->handleRequest($request);
/** #var array|string[message, reason] */
$reportData = $reportForm->getData();
/*
array( 'reason' => 'value', 'message' => 'value' )
*/
dump($reportData);
if ($reportForm->isSubmitted() && $reportForm->isValid()) {
//send email
//redirect to success message
}
//display an error message
}
Lastly update your view to support the new form in your modal.
<div class="modal-body">
{{ form_start(report_form, { action: path('comment_report', { comment: comment.id }) })
{{ form_label(report_form.reason) }}
{{ form_widget(report_form.reason) }}
<div class="form-group">
{{ form_label(report_form.message) }}
{{ form_widget(report_form.message) }}
</div>
{{ form_end(report_form) }}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Send message</button>
</div>
As a recommendation, I strongly urge you to record the report submissions in the database, to function as a case log and status of the reports. My approach will get you most of the way there, you would just need to create your App\Entity\CommentReport entity, with an optional association to the CommentaireBlog entity. Which would be passed to the form and adding the data_class to the form options resolver, mimicking what you have done in your other database forms.
I don't know why you wrote your path call like that, but there should not be any round brackets about the variables you want to use in your route. The following code should work:
<a
href="{{ path('comment_report', { 'msg': form.reportmessage.value ,'type': form.reportreason.value, 'id': comment.id }) }}"
type="button"
class="btn btn-primary">
Send message
</a>

how to insert these data into mysql in wampserver

here are is the code.no matter what i did couldnt connect to mysql database in phpadmin in the wampserver all attempts has failed please help to solve
if (isset($_POST['continue'])) {
$j=0;
while ($j < $passengers)
{
$register_data2 = array(
'first_name' => $_POST["fname"][$j],
'last_name' => $_POST["lname"][$j],
'passport' => $_POST["passport"][$j],
'visa' => $_POST["visa"][$j],
'address1' => $_POST["address1"][$j],
'address2' => $_POST["address2"][$j],
'email' => $_POST["email"][$j],
'contact' => $_POST["contact"][$j],
'pin' => $_POST["pin"][$j],
'leaving_from' => $pieces[0],
'going_to' => $pieces[2],
'depart_date' => $pieces[7],
'depart_time' => $pieces[12],
'arrival_time' => $pieces[17],
'grand_fare' => $pieces[22],
'returning_from' => $pieces1[0],
'returning_to' => $pieces1[2],
'returning_date' => $pieces1[7],
'returning_time' => $pieces1[11],
'reaching_time' => $pieces1[16],
'fare' => $pieces1[21]
);
session_start();
$_SESSION['ticket'][] = $_POST["fname"][$j];
$_SESSION['ticket'][] = $_POST["lname"][$j];
$_SESSION['ticket'][] = $_POST["passport"][$j];
$_SESSION['ticket'][] = $_POST["visa"][$j];
$_SESSION['ticket'][] = $_POST["pin"][$j];
register_passenger($register_data2);
$j = $j+1;
}
$_SESSION['ticket1'] = $pieces[0];
$_SESSION['ticket2'] = $pieces[2];
$_SESSION['ticket3'] = $pieces[7];
$_SESSION['ticket4'] = $pieces[12];
$_SESSION['ticket5'] = $pieces[17];
$_SESSION['ticket6'] = $pieces[22];
$_SESSION['ticket11'] = $pieces1[0];
$_SESSION['ticket22'] = $pieces1[2];
$_SESSION['ticket33'] = $pieces1[7];
$_SESSION['ticket44'] = $pieces1[11];
$_SESSION['ticket55'] = $pieces1[16];
$_SESSION['ticket66'] = $pieces1[21];
}
?>
<?php
if (isset($_POST['pay'])){
if ($_POST['cash'] != $grand_total) {
echo "*Pay the given amount!"."<br>";
}
else{
header ('Location: ticket.php');
}
}
?>
<h2> Select payment method </h2>
<form action="payment.php" method="post">
<input type="radio" name="payment" id="cash" checked="checked" value="cash">
<label for="cash">Cash</label>
<input type="number" id="cash" name="cash" size="8"><br><br>
<input type="radio" name="payment" id="card" value="card">
<label for="card">Card</label>
<select>
<option>Debit card</option>
<option>Credit card</option>
</select>
<br>
<img src="Credit.jpg">
<br>
<input type="submit" name="pay" value="Make payment">
</form>
<?php
if(isset($_POST["Continue"])){
$firstname = $_POST['fname'];
$lastname = $_POST['lname'];
$passport = $_POST['passport'];
$visa = $_POST['visa'];
$address1 = $_POST['address1'];
$address2 = $_POST['address2'];
$email = $_POST['email'];
$contact = $_POST['contact'];
$pin = $_POST['pin'];
mysql_query( "INSERT INTO passengers (first_name,last_name,passport,visa,address1,address2,email,contact,pin) VALUES('$lastname','$passport','passport','$visa','$address1','$address2','$email','$contact','$pin')");
}
?>
i couldnt connect the data to mysql database in the phpadmin in the wampserver. it shows up nothing. as you can see below one of my many attempt to correct to make it work it up as fail. non of the method that i tried didnt work. please help to sove this problem
It seems you messed up the values list:
mysql_query( "INSERT INTO passengers
(first_name,last_name,passport,visa,address1,address2,email,contact,pin)
VALUES
('$lastname','$passport','passport','$visa','$address1','$address2','$email','$contact','$pin')");
First name is missing, 'passport' should not be there, etc. It should be:
('$firstname','$lastname','$passport','$visa','$address1','$address2','$email','$contact','$pin')");

cant login with Auth::attempt

RegisterController :
public function register(Request $request)
{
$user=$request->file('cover');
$destination ='img/user';
$filename=$user->getClientOriginalName();
storage::put('img/user/'.$filename,file_get_contents($request->file('cover')->getRealPath()));
$user = new User();
$user->username = $request->username;
$user->email = $request->email;
$user->name = $request->name;
$user->password = bcrypt($request->password);
$user->cover = $filename;
$roles_id = DB::table('roles')->select('id')->where('rolename','admin')->first()->id;
$user->roles_id = $roles_id;
$user->save();
}
Login.blade.php :
<form action="/login" method="POST">
<input type="hidden" name="_token" value="{{{ csrf_token() }}}">
<div class="row">
<div class="input-field col s6">
<input type="text" class="validate" name="username" placeholder="username">
</div>
</div>
<div class="row">
<div class="input-field col s6">
<input type="password" class="validate" name="password" placeholder="Password">
</div>
</div>
<div class="row">
<div class="input-field col s5">
<input type="submit" class="btn">
</div>
</div>
</form>
LoginController :
public function postlogin(Request $request)
{
if(Auth::attempt([
'username' => $request->username,
'password' => $request->password
])){
return 'Cool';
}else{
return 'Not Cool';
}
}
just in case if you wanna see the route :
Route::get('/register','Auth\RegisterController#showRegistrationForm');
Route::post('/register', 'Auth\RegisterController#register');
Route::get('/login', 'Auth\LoginController#showLoginForm');
Route::post('/login', 'Auth\LoginController#postlogin');
i do read this post Laravel Auth::attempt() always false? but still dont know how to fix it
i try put
'password' => Hash::make($request->password)
and still got 'Not Cool'
:(
Laravel's Hash::make() uses bcrypt internally to hash the passwords.
But Hash::make() will generate different hash each time. So you can't use Hash::make() again on the same password and compare the two values. It will always return false as the hash generated each time would be different. However Laravel provides a Hash::check() to check the passwords hashed using Hash::make() or bcrypt() helper function.
If you want to verify the password hashed by using Hash::make() or bcrypt() helper function then you can do so by
/* Say you are using word secret as password while registering */
$password = 'secret';
$hashedPassword = Hash::make('secret');
/* Or */
$hashedPassword = bcrypt('sectet');
/* To verify the $hashedPassword - probably stored in a database */
function verify_password($password)
{
if(Hash::check($password, $hashedPassword)
{
echo "Passwords Match!";
}
else
{
echo "Passwords do not match :(";
}
}
/* While logging back (after registering)
in the first attempt you have a typo in your password secrets instead of secret
*/
$attempt1 = 'secrets';
verify_password($attempt1); /* will echo Passwords do not match :( */
/* in the second attempt you use the correct password secret */
$attempt2 = 'secret';
verify_password($attempt2); /* will echo Passwords Match! */
Hope this helps to understand.