Display subject based on status of user in laravel - php

Hi everyone i have a question how can i display the subject based on the user status. if the user is active which means the the full subject will be displayed but if he is not active i only want to display specific subject.
public function inquirySubject()
{
if(auth()->user()->status === 'approved' || auth()->user()->status === 'active')
{
$subject = [
'Inquiry',
'Follow Up',
'Technical Problem',
'Other Application Concern',
'Payment Concern' ,
'Proof of Payment'
];
}else{
$subject = [
'Inquiry',
'Follow Up',
'Technical Problem',
'Other Application Concern',
// 'Payment Concern' , // if user is not active or approved this subject line should not display
'Proof of Payment'
];
}
return response()->json($subject);
}

You could do something like this to save a bit of code duplication:
public function inquirySubject()
{
$isApprovedOrActiveUser = auth()->user()->status === 'approved' || auth()->user()->status === 'active';
$subject = [
'Inquiry',
'Follow Up',
'Technical Problem',
'Other Application Concern',
'Proof of Payment'
];
if ($isApprovedOrActiveUser) {
$subject[] = 'Proof of Payment';
}
return response()->json($subject);
}
You could also implement this logic in a Resource - see: https://laravel.com/docs/9.x/eloquent-resources

Add to model
public const SUBJECT_ACTIVE_OR_APPROVED = [
'Inquiry',
'Follow Up',
'Technical Problem',
'Other Application Concern',
'Payment Concern',
'Proof of Payment',
];
And
public const SUBJECT_NOTACTIVE = [
'Inquiry',
'Follow Up',
'Technical Problem',
'Other Application Concern',
'Proof of Payment',
];
Your function
public function inquirySubject()
{
return (auth()->user()->status === 'approved' || auth()->user()->status === 'active')
? response()->json(Model::SUBJECT_ACTIVE_OR_APPROVED)
: response()->json(Model::SUBJECT_NOTACTIVE);
}

Related

CI3 / Validation always returns false upon initial load

I do not understand why upon load the validation always returns false. Here is part of my controller:
// load up the validation rules for blog Info form
$this->config->load('mh_blog_validate');
$this->form_validation->set_rules($this->config->item('validate_blog_update'));
if ($this->form_validation->run('validate_blog_update') === FALSE) {
$errors = array('message' => $this->upload->display_errors());
$message = array('message' => 'Warning - '.$errors['message'],
'class' => 'danger',
);
$this->data['alert'] = bootstrap_alert($message);
}
Here is my validation config from mh_blog_validate:
$config['validate_blog_update'] = array(
'title' => array(
'field' => 'title',
'label' => '',
'rules' => 'required|trim|xss_clean|min_length[5]|callback_is_slug_unique_on_update[]',
'errors' => array(
'required' => 'The title cannot be blank.',
'min_length' => 'The title must be 5 charaters or more.',
'is_unique' => 'The title must be unique.',
'is_slug_unique_on_update' => 'The new title needs to be unique'
),
),
'body' => array(
'field' => 'body',
'label' => '',
'rules' => 'required|trim|xss_clean|min_length[5]',
'errors' => array(
'required' => 'The body cannot be blank',
'min_length' => 'The body must be 5 charaters or more.',
)
),
); // end validate_blog_create
This is the callback function I use in the validate:
function is_slug_unique_on_update() {
$new_slug = url_title($this->input->post('title'));
if ( $new_slug == $this->input->post('slug')) {
// no change in slug so update
// echo "no change in title";
return TRUE;
} elseif ( $new_slug !== $this->input->post('slug')) {
// new slug
$result = $this->Blog_model->is_slug_unique_on_update($new_slug);
return $result; // returns FALSE if the title is not unique
}
}
The output I receive in the view is "Warning - " and this is placed in the view:
if (isset($this->data['alert']){
echo $this->data['alert'];
}
I was expecting the validation not to produce an error because I have not submitted the form. It runs the validation maybe(?) even when I have not submitted the form I think.
+++ new edit +++
Added code below that works and wish to know why mine code doesn't. I thought my code follows the same pattern, no?
class Form extends CI_Controller {
public function index()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required',
array('required' => 'You must provide a %s.')
);
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
$this->form_validation->set_rules('email', 'Email', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('myform');
}
else
{
$this->load->view('formsuccess');
}
}
}
The problem is you are setting $this->data['alert'] values, whether the form is submitting data or not. Of course you could prevent this variable assignment by adding conditional so it will set only when there are any $_POST data is submitted :
// load up the validation rules for blog Info form
$this->config->load('mh_blog_validate');
$this->form_validation->set_rules($this->config->item('validate_blog_update'));
if ($this->form_validation->run('validate_blog_update') === FALSE) {
if ($_POST)
{
$errors = array('message' => $this->upload->display_errors());
$message = array('message' => 'Warning - '.$errors['message'],
'class' => 'danger',
);
$this->data['alert'] = bootstrap_alert($message);
}
}

Laravel Model Not Saving but It Says It Is (Inside of Observer class)

I have a task model and I am trying to do a simple create to test something in one of my observer classes. Here's my create code.
private function generateTasks(Event $event)
{
$tasks = [];
$tasks[] = [
'event_id' => $event->id,
'title' => 'This is a test',
'description' => 'this is a description',
'due_on' => Carbon::now()->addDays(14)
];
dump(Task::all());
// foreach ($tasks as $task) {
$task = Task::create([
'event_id' => $event->id,
'title' => 'This is a test',
'description' => 'this is a description',
'due_on' => Carbon::now()->addDays(14)
]);
if ($task->save()) {
echo "Saved";
}
else {
echo "NO SAVE";
}
dump($task);
// }
dd($tasks, "DONE");
}
And the output is below:
When I look at the database the table remains at 120 rows. This is really odd because it says it's saving. When I grab all the tasks you can see in the output it has 120 rows. If you look at my latest output id you'll see that I am up to 133.
Any ideas what is going on here?
UPDATE:
My fillables:
protected $fillable = [
'title', 'description', 'due_on', 'event_id', 'completed'
];
Completed has a default of false.
My table looks like this to give you guys an idea:
the create does the save method you do not need to do it again you can do it as the following:
private function generateTasks(Event $event)
{
$tasks = [];
$tasks[] = [
'event_id' => $event->id,
'title' => 'This is a test',
'description' => 'this is a description',
'due_on' => Carbon::now()->addDays(14)
];
$task = Task::create([
'event_id' => $event->id,
'title' => 'This is a test',
'description' => 'this is a description',
'due_on' => Carbon::now()->addDays(14)
]);
if ($task) {
echo "Saved";
}
else {
echo "NO SAVE";
}
dd($tasks, "DONE");
}
I ended up getting help from the laravel chat. Big shout-out to them. The problem was that I was using a dump die inside of a transaction. This was causing what appeared to be a save but then, because the die was called before the transaction commit, it was rolling everything back. It was a silly mistake. Thanks for all the help!

How to check column record present or not if not display error message else insert into database using codeigniter?

I want to check if record is exist then fire error message else insert into database using codeigniter
model.php
public function insert_profile($data){
$this->db->insert('profile', $data);
}
controller.php
public function empprofile(){
$this->form_validation->set_rules('txtname', 'Name', 'trim|required|min_length[6]',
array(
'required' => 'enter your name'));
$this->form_validation->set_rules('txtemail', 'Email', 'trim|required|valid_email',
array(
'required' => 'enter email'));
$this->form_validation->set_rules('txtvpno', 'Vastipatrak No', 'trim|required|min_length[11]',
array(
'required' => 'select Vastipatrak No'));
$this->form_validation->set_rules('txtfield', 'Field', 'trim|required',
array(
'required' => 'enter Field'));
$this->form_validation->set_rules('txtcontact', 'Phone No', 'trim|required|min_length[10]|max_length[10]',
array(
'required' => 'select Phone No'));
$this->form_validation->set_rules('txtexp', 'Experience', 'trim|required',
array(
'required' => 'enter Experience'));
$this->form_validation->set_rules('txtage', 'Age', 'trim|required',
array(
'required' => 'enter age'));
if($this->form_validation->run() ==FALSE){
$this->load->view('submitprofile');
}
else{
$data = array(
'Name' => $this->input->post('txtname'),
'Email' => $this->input->post('txtemail'),
'VPNo' => $this->input->post('txtvpno'),
'Field' => $this->input->post('txtfield'),
'Phone' => $this->input->post('txtcontact'),
'Exp' => $this->input->post('txtexp'),
'Age' => $this->input->post('txtage')
);
$result= $this->mymodel->insert_profile($data);
if ($result == FALSE) {
echo "Vastipatrak No already exist";
}
elseif ($result == 0) {
echo "Something Went Wrong";
}
else{
echo "You have successfully registred with KDOJobs";
}
redirect(site_url('talents'));
}
}
What i can do to check if record is exists or not if yes then display error
In Model
public function insert_profile($data)
{
$VPNo = $data['VPNo'];
$query = $this-db->query("SELECT * FROM profile WHERE vpno = '$VPNo' ");
$result = $query->result_array();
if (count($result) > 0)
{
# data exist
return FALSE;
}
else
{
$this->db->insert('profile', $data);
if ($this->db->affected_rows() > 0)
{
return TRUE;
}
else
{
return 0;
}
}
}
In Controller
$result = $this->mymodel->insert_profile($data);
if ($result == FALSE) {
$this->session->set_flashdata('error', 'Data exist');
}
elseif ($result == 0) {
$this->session->set_flashdata('error', 'Something Went Wrong');
}
else{
$this->session->set_flashdata('success', 'Successfullly Inserted');
}
/*
In your code you using redirect(). So its better to add session like Flash Data.
So once you redirect as soon as function success you can access it in redirected page.
Setting Flash Data
If error
$this->session->set_flashdata('error', 'Data exist');
$this->session->set_flashdata('error', 'Something Went Wrong');
If Success
$this->session->set_flashdata('success', 'Successfullly Inserted');
Accessing Flash data
if(!empty($this->session->flashdata('error'))
{
echo $this->session->flashdata('error');
}
*/
redirect(site_url('talents'));
Links
Flashdata in Codeigniter
There's a better way to use is_unique[table.coloum_name] , I think, still using CodeIgniters' validation library... Use is_unique where you pass an extra parameter which is the id of the row you're editing.. See below.. I use it and works pretty fine for me.. is_unique[table.coloum_name] hope it helps
$this->form_validation->set_rules('txtname', 'Name', 'trim|required|min_length[6]|is_unique[table.coloum_name]', array( 'required' => 'enter your name'));
https://www.codeigniter.com/userguide3/libraries/form_validation.html

Cake php Model Validation Not Working

I want insert record in a table.For this i have model,view and controller.Everything in my code is working perfectly but my model code for validation not showing any validation message.What should i do?I am giving below the code :
My Controller Code :
public function send_money()
{
$this->layout='agent';
$this->Agent->create();
$this->Agent->set($this->data);
if(empty($this->data) == false)
{
//$this->Agent->saveAll($this->data['Agent'], array('validate' => 'only')); //This code Id New
$this->Agent->saveAll($this->data['Agent']);
$this->Session->setFlash('Information Added Successfully.');
$this->redirect('send_money');
}
else
{
$this->set('errors', $this->Agent->invalidFields());
}
}
And My Model Code is :
App::uses('AppModel', 'Model');
/**
* Admin Login Model
*
*/
class Agent extends AppModel
{
public $name='Agent';
public $usetables='agents';
public $validate = array(
'contact' =>array(
'rule' => 'notEmpty', // or: array('ruleName', 'param1', 'param2' ...)
'allowEmpty' => false,
'message' => 'Please Enter Contact No.'
),
'name' =>array(
'rule' => 'notEmpty', // or: array('ruleName', 'param1', 'param2' ...)
'allowEmpty' => false,
'message' => 'Please Enter Name.'
),
'email_add' =>array(
'rule' => 'email', // or: array('ruleName', 'param1', 'param2' ...)
'allowEmpty' => false,
'message' => 'Please Enter Valid Email.'
),
);
}
Use this in your controller:
if($this->Agent->validates($this->data)) {
Instead of:
if(empty($this->data) == false)
change:
$this->Form->create('Agents',
to
$this->Form->create('Agent',
As your model name is Agent not Agents
See here: Model Validation
try this:
public function send_money()
{
$this->layout='agent';
$this->Agent->create();
$this->Agent->set($this->data);
if($this->Agent->saveAll($this->data['Agent'])) {
$this->Session->setFlash('Information Added Successfully.');
$this->redirect('send_money');
}
else {
$this->set('errors', $this->Agent->invalidFields());
}
}
Note : to log the error validation use this debug($this->Agent->validationErrors);.

Ion Auth & Codeigniter: Looping redirect when new user login

I am a frequent user of Codeigniter and it has come to the point where i've had to start looking at a library for login/forgot password so i decided to use Ion Auth.
I set this up - works fine, tried the admin account that is already set up with it and it's fine.
Now when i login as the admin and then create a new user, the data is added to the database and the page redirects from "create-user" to the welcome page. But if i logout and login with these new details, the page goes blank and the reload bar goes crazy! The url bar looks like it goes to the welcome page if that makes sense but nothing loads.
I've also checked my console on firebug and the php log error and nothing at all.
I've checked my database and when the user has been added, the password has been hashed but in the salt column it is classed as NULL whereas the default account already set up has a hash code? - could this be something to do with it?
EDIT: I've now altered the code but this still didn't worked when it wasn't touched so only edits in code are removal of tables and in the auth controller the functions are login, create_user and logout.
And when the admin#admin.com user logs in it loads the page fine just other"new" accounts..
Thanks!
//log the user in
function login() {
$this->data['title'] = "Login";
$this->form_validation->set_rules('identity', 'Identity', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == true) {
//check for "remember me"
$remember = (bool) $this->input->post('remember');
if ($this->ion_auth->login($this->input->post('identity'), $this->input->post('password'), $remember)) {
//if the login is successful
//redirect them back to the home page
$this->session->set_flashdata('message', $this->ion_auth->messages());
redirect('/', 'refresh');
}else{
//if the login was un-successful
//redirect them back to the login page
$this->session->set_flashdata('message', $this->ion_auth->errors());
redirect('auth/login', 'refresh');
}
}else{
//the user is not logging in so display the login page
$this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
$this->data['identity'] = array('name' => 'identity',
'id' => 'identity',
'type' => 'text',
'value' => $this->form_validation->set_value('identity'),
);
$this->data['password'] = array('name' => 'password',
'id' => 'password',
'type' => 'password',
);
$this->_render_page('auth/login', $this->data);
}
}
//log the user out
function logout() {
$this->data['title'] = "Logout";
$logout = $this->ion_auth->logout();
$this->session->set_flashdata('message', $this->ion_auth->messages());
redirect('auth/login', 'refresh');
}
//create a new user
function create_user() {
$this->data['title'] = "Create User";
$this->form_validation->set_rules('first_name', 'First Name', 'required|xss_clean');
$this->form_validation->set_rules('last_name', 'Last Name', 'required|xss_clean');
$this->form_validation->set_rules('email', 'Email Address', 'required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[' . $this->config->item('min_password_length', 'ion_auth') . ']|max_length[' . $this->config->item('max_password_length', 'ion_auth') . ']|matches[password_confirm]');
$this->form_validation->set_rules('password_confirm', 'Password Confirmation', 'required');
if ($this->form_validation->run() == true) {
$username = strtolower($this->input->post('first_name')) . ' ' . strtolower($this->input->post('last_name'));
$email = $this->input->post('email');
$password = $this->input->post('password');
$additional_data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name')
);
}
if ($this->form_validation->run() == true && $this->ion_auth->register($username, $password, $email, $additional_data)) {
//check to see if we are creating the user
//redirect them back to the admin page
$this->session->set_flashdata('message', $this->ion_auth->messages());
redirect("auth/login", 'refresh');
}else{
//display the create user form
//set the flash data error message if there is one
$this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));
$this->data['first_name'] = array(
'name' => 'first_name',
'id' => 'first_name',
'type' => 'text',
'value' => $this->form_validation->set_value('first_name'),
);
$this->data['last_name'] = array(
'name' => 'last_name',
'id' => 'last_name',
'type' => 'text',
'value' => $this->form_validation->set_value('last_name'),
);
$this->data['email'] = array(
'name' => 'email',
'id' => 'email',
'type' => 'text',
'value' => $this->form_validation->set_value('email'),
);
$this->data['password'] = array(
'name' => 'password',
'id' => 'password',
'type' => 'password',
'value' => $this->form_validation->set_value('password'),
);
$this->data['password_confirm'] = array(
'name' => 'password_confirm',
'id' => 'password_confirm',
'type' => 'password',
'value' => $this->form_validation->set_value('password_confirm'),
);
$this->_render_page('auth/create_user', $this->data);
}
}
function _render_page($view, $data=null, $render=false) {
$this->viewdata = (empty($data)) ? $this->data: $data;
$view_html = $this->load->view($view, $this->viewdata, $render);
if (!$render) return $view_html;
}
}
WELCOME PAGE CONTROLLER
class Welcome extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library('ion_auth');
$this->load->library('session');
$this->load->library('form_validation');
$this->load->helper('url');
}
public function index() {
if (!$this->ion_auth->logged_in()) {
redirect('auth/login', 'refresh');
}elseif (!$this->ion_auth->is_admin()) {
redirect('/', 'refresh');
}else{
$this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
$this->_render_page('auth/welcome', $this->data);
}
}
}
RESOLVED: This was a bug with Google Chrome which i've had to update the system and the brwser. Also for storing the SALT i changed some settings in my ion_auth config file
This was a bug with Google Chrome which i've had to update the system and the browser. Also for storing the SALT i changed some settings in my ion_auth config file

Categories