pass variable between functions in same controller - php

class AppointmentsController extends AppController {
public function view($id = null) {
if (!$this->Appointment->exists($id)) {
throw new NotFoundException(__('Invalid appointment'));
}
$options = array('conditions' => array('Appointment.' . $this->Appointment->primaryKey => $id));
$this->set('appointment', $this->Appointment->find('first', $options));
$kk = $this->Appointment->find('first', array('fields' => 'status', 'conditions' => array('Appointment.id' => $id)));
$ss = reset($kk);
$stats = reset($ss);
}
}
I have set $stats via getting value from DB and i want to use in in another function in same controller
then I want to use like this
class AppointmentsController extends AppController {
function confirm(){
$stats = 'New';
}
}

Seeing that it's the same class, have you tried using $this->stats instead of a local variable?

You can call another function in your first function like
$this->confirm($status); // calling confirm function
function confirm($status)
{
//use status as you want
}
Or you can set status as global variable then this can you accessible in any function.

I think, you've to create function in the model that will return the value of the field by id.
<?php
// model/AppModel.php
public function getFieldById($field='id', $id){
return $this->field($field, array('id' => $id));
}
// in controller function you can access this like.
$status = $this->Appointment->getFieldById('status', $id); // $id will be appointment id.
?>

Related

reuse mysql query code among few methods in same controller - Laravel 5.4

I have few queries which I would like to use it to few methods in the same controller.for example below code:
$lastlogin = User::select('lastlogin')->where('id',Auth::user()->id)->get()->pluck('lastlogin');
$bio = User::where('id',Auth::user()->id)->value('bio');
$photo = User::where('id',Auth::user()->id)->value('photo');
$notifications = Notification::where('created_at','>',$lastlogin)->get();
$status = User::where('id',Auth::user()->id)->value('search_status');
I need to call above query in 4 methods in UserController.
I thought of doing something like:
public function john_doe()
{
$lastlogin = User::select('lastlogin')->where('id',Auth::user()->id)->get()->pluck('lastlogin');
$bio = User::where('id',Auth::user()->id)->value('bio');
$photo = User::where('id',Auth::user()->id)->value('photo');
$notifications = Notification::where('created_at','>',$lastlogin)->get();
$status = User::where('id',Auth::user()->id)->value('search_status');
}
Then
UserController
public abc (){john_doe();}
public def (){john_doe();}
public ghi (){john_doe();}
public jkl (){john_doe();}
But I get an error. How do I do this so when I change the code in one place it reflects everywhere?
Updated question
public function notify()
{
$bio = User::where('id',Auth::user()->id)->value('bio');
$photo = User::where('id',Auth::user()->id)->value('photo');
$friends = Friend::where('user_id',Auth::user()->id)->where('reqs_status',2)->get();
$notifications = Notification::where('created_at','>',Auth::user()->lastlogin)->get();
$status = User::where('id',Auth::user()->id)->value('search_status');
}
public function index()
{
$this->notify();
return view('/users/index',compact('send_requests','accept_rejects','sent_requests','users','bio','photo','friends','status','seeks','filters','notifications'));
}
That is a poorly written code. You get everything except notifications from the logged in user model.
public function fetchData()
{
$user = auth()->user();
$notifications = Notification::where('created_at', '>' , $user->lastlogin)->get();
$data = [
'lastlogin' => $user->lastlogin,
'bio' => $user->bio,
'photo' => $user->photo,
'search_status' => $user->search_status,
'notifications' => $notifications,
];
return (Object)$data;
}
public function test()
{
$data = $this->fetchData();
// $data->lastlogin;
// $data->bio;
// $data->photo;
// $data->search_status;
// $data->notifications;
}
Your UserController could looks like this
class UserController extends BaseController {
public function notify()
{
$array['bio'] = User::where('id',Auth::user()->id)->value('bio');
$array['photo'] = User::where('id',Auth::user()->id)->value('photo');
$array['friends'] = Friend::where('user_id',Auth::user()->id)->where('reqs_status',2)->get();
$array['notifications'] = Notification::where('created_at','>',Auth::user()->lastlogin)->get();
$array['status'] = User::where('id',Auth::user()->id)->value('search_status');
return $array;
}
public function index()
{
return view('/users/index', $this->notify());
}
}

How to pass and retrieve data between two controllers in Laravel

I'm trying to get to grips with Laravel and not finding the documentation any help at all. It seems to assume you know so much instead of actually walking new users through each section step by step.
I've got to the point where I need to make an internal call to another class, and sticking with MVC I can't seem to do what should be a simple thing.
My code:
class UsersController extends BaseController {
protected $layout = 'layouts.templates.page';
protected $messages;
public function getIndex()
{
$input = array('where', array('field' => 'email', 'operator' => '=', 'value' => 'tony#fluidstudiosltd.com'));
$request = Request::create('user/read', 'GET');
$users = json_decode(Route::dispatch($request)->getContent());
var_dump($users); exit;
$this->pageTitle = 'Fluid Customer Status :: Admin Users';
$this->content = View::make('layouts.admin.users');
}
}
Class UserController extends Base Controller
public function getRead()
{
$userId = (int) Request::segment(3);
if ($userId)
{
$user = User::findOrFail($userId);
return $user;
}
else
{
$users = new User;
var_dump(Input::all()); exit;
if (Input::has('where'))
{
var_dump(Input::get('where')); exit;
}
return $users->get();
}
}
Why isn't the input data from UsersController#getIndex available in UserController#getRead

How to get access to the model in the view - Symfony 2

I have the following model:
class Person
{
public $name;
function __Construct( $name )
{
$this->name = $name;
}
}
I have the following controller:
class NavigationController extends Controller
{
public function indexAction()
{
$people = array(
new Person("James"),
new Person("Bob")
);
return $this->render('FrameworkBundle:Navigation:index.html.php', $people);
}
}
How do I get access to the model array in the view. Is there a way to access the model directly or do I have to assign a property like so:?
class NavigationController extends Controller
{
public function indexAction()
{
$people = array(
new Person("James"),
new Person("Bob")
);
return $this->render('FrameworkBundle:Navigation:index.html.php', array( "model" => $people ) );
}
}
View:
<?php
foreach( $model as $person )
{
echo $person->title;
}
?>
The problem with the above will be that it can be changed by a user to
return $this->render( 'FrameworkBundle:Navigation:index.html.php', array( "marybloomingpoppin" => $people ) );
With the example view you used, you already had the correct implementation:
class NavigationController extends Controller
{
public function indexAction()
{
$people = array(
new Person("James"),
new Person("Bob")
);
return $this->render('FrameworkBundle:Navigation:index.html.php', array( "model" => $people ) );
}
}
You mentioned the concern that somebody could change the assignment in the controller, but this is something you always have if somebody changes the name of a variable only in one place and not in all. So I don't think this is an issue.

Database switch with BindModel in cakePHP

I'm working on application in cake PHP which uses multiple database. I need to fetch data from multiple tables and i'm using bindModel for their association. But bindModel does not allow database switch functionality, I need to access data from multiple databases.If anyone has done this type of assignment then plz help me out.
In your AppModel
class AppModel extends Model
{
/**
* Connects to specified database
*/
public function setDatabase($database, $datasource = 'default')
{
$nds = $datasource . '_' . $database;
$db = &ConnectionManager::getDataSource($datasource);
$db->setConfig(array(
'name' => $nds,
'database' => $database,
'persistent' => false
));
if ( $ds = ConnectionManager::create($nds, $db->config) ) {
$this->useDbConfig = $nds;
$this->cacheQueries = false;
return true;
}
return false;
}
}
and in your controller you can use
class CarsController extends AppController
{
public function user()
{
$this->User->setDatabase('testdb1');
$cars = $this->User->find('all');
$this->set('User', $User);
}
public function client()
{
$this->Client->setDatabase('testdb2');
$cars = $this->User->find('all');
$this->set('Client', $Client);
}
}

How can I retrieve data using a model and pass it to be used in a controller using CodeIgniter?

From a user login form i need to use their username ($this->input->post('username')) to query against the membership table in my database so that I can retrieve the users firstname and lastname, which I believe should be done via a model called from my controller. I then need to pass that data back to my controller to use the firstname and lastname to add in to my session userdata which is set in my controller, as shown below.
$data = array(
'username' => $this->input->post('username'),
'firstname' => //need to retrieve value from database,
'lastname' => //need to retrieve value from database,
'is_logged_in' => true
);
$this->session->set_userdata($data);
Thanks,
Kristan.
In your model, make a function to retrieve the first and last name of a user:
public function get_user_details($username){
// retrieve contents from db:
// the first username here is the name of the column in your table
$query = $this->db->select('firstname, lastname')
->where('username', $username)
->get('membership');
return $query->result_array();
}
In your controller, like you were doijng, grab the POST contents in your controller:
$username = $this->input->post('username');
Then, from your controller, call your model function but save the output of that model function in a variable:
$data = $this->user_model->get_user_details($username);
After that, you can do what you were trying to do:
$this->session->set_userdata($data);
Hope that helps. I wrote this from the top of my head but it should work. I also suggest you read the CI documentation through because it really is some of the best documentation I have ever seen for a framework. Good luck.
Please check CodeIgniter user guide for model. The example of Blog controller and Blog model will answer you.
class Blogmodel extends CI_Model {
var $title = '';
var $content = '';
var $date = '';
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function get_last_ten_entries()
{
$query = $this->db->get('entries', 10);
return $query->result();
}
function insert_entry()
{
$this->title = $_POST['title']; // please read the below note
$this->content = $_POST['content'];
$this->date = time();
$this->db->insert('entries', $this);
}
function update_entry()
{
$this->title = $_POST['title'];
$this->content = $_POST['content'];
$this->date = time();
$this->db->update('entries', $this, array('id' => $_POST['id']));
}
}
class Blog_controller extends CI_Controller {
function blog()
{
$this->load->model('Blog');
$data['query'] = $this->Blog->get_last_ten_entries();
$this->load->view('blog', $data);
}
}
You first need to create a model.
class Membership_model extends CI_Model {
function __construct() {
parent::__construct();
}
function getUser($username) {
$query = $this->db->get_where('membership', array('username' => $username));
return $query->result_array();
}
}
then in your controller, use the membership model to retrieve data. Calling this function: $this->membership_model->getUser($this->input->post('username'));

Categories