all code is in one controller
My code goes like this.
public function login()
{
$session = $this->request->session();
$session_event_id = $session->read('Events.event_id');
$session_division_id = $session->read('Events.division_id');
if(!$session_event_id || !$session_division_id) {
$event_table = TableRegistry::get('Events');
$event = $event_table->find('all', ['fields' => ['id'], 'order' => 'id desc'])->first();
$session->write('Events.event_id', $event->id);
$session_event_id = $session->read('Events.event_id');
$division_table = TableRegistry::get('Divisions');
$division = $division_table->find('all',['fields' => ['id'], 'conditions' => ['event_id' => $event->id]])->first();
$session->write('Events.division_id', $division->id);
$session_division_id = $session->read('Events.division_id');
}
}
By above code i am able to write and read session values but while logout i want to delete those session data
public function logout()
{
$session = $this->request->session();
$this->$session->delete();
return $this->redirect($this->Auth->logout());
}
Warning (4096): Object of class Cake\Network\Session could not be
converted to string [APP/Controller/UsersController.php, line 56]
Notice (8): Object of class Cake\Network\Session to string conversion
[APP/Controller/UsersController.php, line 56]
Error: Call to a member function delete() on a non-object File
/var/www/html/MEX/src/Controller/UsersController.php
You're looking for $this->request->session()->destroy();
http://book.cakephp.org/3.0/en/development/sessions.html#destroying-the-session
Just a tip - there's not much of a point for storing a variable $session for a function that small, where the reuse of $session isn't necessary. The only case I'd store $this->request->session(); in a variable is when I'm accessing the session for multiple read and writes all in the same function.
(As far as the error is concerned, #Eagle is correct in that you're referencing '$this' twice by the use of that stored variable.)
Thank You for your supports and help finally i found solution of my problem by myself
$session = $this->request->session();
$session->delete('Events.event_id');
$session->delete('Events.division_id');
by doing so, i am able to clear session data. Thank you
Related
I have a variable which holds the model name like so
$fooTableName = 'foo_defs';
$fooModel = 'FooDefs';
Now I would like to insert in the DB using that model like so
$fooModel::insert([..foo..array...]);
Throws an error
"message": "Parse error: syntax error, unexpected '$fooModel' (T_VARIABLE), expecting identifier (T_STRING)",
Is it possible to do something like that? or will I be forced to use
DB::table('fooTableName')->insert([...foo...array...]);
If I do it in the latter way, the timestamps in the table are wrong. The created_at column is null and the updated_at has the value
EDIT 1
$model = CustomHelper::getNameSpace($this->tableNames[$i]);
// $model => /var/www/html/erp/app/Models/sales/InvoiceDefs
$model::insert($this->tableCollections[$this->tableNames[$i]]);
Most of them said that, it was namespace issue, so I have corrected it, but still it is throw error like
"message": "Class '/var/www/html/erp/app/Models/sales/InvoiceDefs' not
found",
What you are doing wrong is using model name as string, you need to refactor your code as like below :
$fooModel = 'App\Models\FooDefs';
I have a same situation before and i have created the function to do this
function convertVariableToModelName($modelName='',$nameSpace='')
{
//if the given name space iin array the implode to string with \\
if (is_array($nameSpace))
{
$nameSpace = implode('\\', $nameSpace);
}
//by default laravel ships with name space App so while is $nameSpace is not passed considering the
// model namespace as App
if (empty($nameSpace) || is_null($nameSpace) || $nameSpace === "")
{
$modelNameWithNameSpace = "App".'\\'.$modelName;
}
//if you are using custom name space such as App\Models\Base\Country.php
//$namespce must be ['App','Models','Base']
if (is_array($nameSpace))
{
$modelNameWithNameSpace = $nameSpace.'\\'.$modelName;
}
//if you are passing Such as App in name space
elseif (!is_array($nameSpace) && !empty($nameSpace) && !is_null($nameSpace) && $nameSpace !== "")
{
$modelNameWithNameSpace = $nameSpace.'\\'.$modelName;
}
//if the class exist with current namespace convert to container instance.
if (class_exists($modelNameWithNameSpace))
{
// $currentModelWithNameSpace = Container::getInstance()->make($modelNameWithNameSpace);
// use Illuminate\Container\Container;
$currentModelWithNameSpace = app($modelNameWithNameSpace);
}
//else throw the class not found exception
else
{
throw new \Exception("Unable to find Model : $modelName With NameSpace $nameSpace", E_USER_ERROR);
}
return $currentModelWithNameSpace;
}
How To user it:
Arguments
First Argument => Name of the Model
Second Argument => Namespcce of the Model
For Example we have the model name as Post
$postModel = convertVariableToModelName('Post');
dd($postModel::all());
Will returns all the values in the posts table
But in Some Situation You Model Will in the
Custom Namespace such as App\Models\Admin\User
So this function is created to overcome that
$userModel = convertVariableToModelName('User',['App','Models','Admin']);
dd($userModel::all());
You are feel free to customize the function
Hope it helps
Try the below one,
$fooModel = new FooDefs();
and then you can do the following also,
$fooModel->column1 = $value1;
$fooModel->column2 = $value2;
$fooModel->column2 = $value2;
$fooModel->save();
or
$fooModel->save([
'column1' => $value1,
'column2' => $value2,
'column3' => $value3,
])
Edited answer
$path = 'my\project\path\to\Models';
$fooModel = app($path.'\FooDefs');
$fooModel::save([
'column1' => $value1,
'column2' => $value2,
'column3' => $value3,
])
dd($fooModel ::all());
Try my edited answer.
When you have the name of class stored as string you can call method on that class by using the php method call_user_func_array like this
$class_name = "FooDefs";
call_user_func_array(array($class_name, "insert"), $data);
$data is an Array of data which will be past to the called function as arguments.
Just for simple advice It's will be Good if you save in the $class_name variable the FQN Fully Qualified Name of the class which is the __NAMESPACE__ follow by the name of the class. For sample purpose FQN look like Illuminate\Support\Facades\DB which you can get when you save you use User::class I presume you have some User model. That will return the Fully Qualified Name of the User model will will be App\User in case of Laravel.
$requests = $post['request'] // posting the data from view page
$models = "app\models".'\\'.$requests //geting the model
$model = $models::findOne($referenceId) //fetching value from database
i post value through ajax in codeigniter controller function , and trying to store value in session like this
function abc{
$studio = $_POST['studio'];
$trnr_type = $_POST['trnrtyp'];
$this->session->set_userdata('studio',$studio),$this->session->set_userdata('trnr_type',$trnr_type)
}
and use this value
$st = $this->session->userdata('studio');
$tr = $this->session->userdata('trnr_type');
but not getting value in session variable.
Load the session library in your controller by the following
$this->load->library('session');
then you have to post the data to the codeigniter controller
then at the controller you have to do the following
$sess_array = array(
'studio' => $this->input->post('studio'),
'trnr_type' => $this->input->post('trnrtyp'),
);
$this->session->set_userdata('studio',$sess_array);
//set user data
$this->session->set_userdata('username',$username);
//get user data
if($this->session->has_userdata('username'))
{
$userid = $this->session->userdata('username');
}
Hope this is what u are looking for
Before call abc function load sesion library
function abc() {
$session = array('studio'=>$_POST['studio'],'trnr_type'=>$_POST['trnrtyp']);
$this->session->set_userdata($session);
}
1. Load session library into your controller:
$this->load->library('session');
2. Get your data:
$studio = $this->input->post('studio');
$trnrtyp = $this->input->post('trnrtyp');
3. Set session data:
$this->session->set_userdata('studio', $studio);
$this->session->set_userdata('trnrtyp ', $trnrtyp );
4. Get session data:
$st = $this->session->userdata('studio');
$tr = $this->session->userdata('trnr_type');
This is what the user guide says to do
http://www.codeigniter.com/user_guide/libraries/sessions.html#adding-session-data
public function abc() {
$sessiondata = array(
'studio' => $this->input->post('studio'),
'trnrtyp' => $this->input->post('trnrtyp')
);
$this->session->set_userdata($sessiondata);
}
Make sure you have set your session save path on config.php don't leave it null
I need to change value of my request parameter like this:
$request->name = "My Value!";
I use this code but does not work:
$request->offsetSet('img', $img);
Try to:
$requestData = $request->all();
$requestData['img'] = $img;
Another way to do it:
$request->merge(['img' => $img]);
Thanks to #JoelHinz for this.
If you want to add or overwrite nested data:
$data['some']['thing'] = 'value';
$request->merge($data);
If you do not inject Request $request object, you can use the global request() helper or \Request:: facade instead of $request
Use merge():
$request->merge([
'user_id' => $modified_user_id_here,
]);
Simple! No need to transfer the entire $request->all() to another variable.
Read more about Laravel's merge() here:
https://laravel.com/docs/collections#method-merge
If you need to customize the request
$data = $request->all();
you can pass the name of the field and the value
$data['product_ref_code'] = 1650;
and finally pass the new request
$last = Product::create($data);
If you need to update a property in the request, I recommend you to use the replace method from Request class used by Laravel
$request->replace(['property to update' => $newValue]);
Use add
$request->request->add(['img' => $img]);
If you use custom requests for validation, for replace data for validation, or to set default data (for checkboxes or other) use override method prepareForValidation().
namespace App\Http\Requests\Admin\Category;
class CategoryRequest extends AbstractRequest
{
protected function prepareForValidation()
{
if ( ! $this->get('url')) {
$this->merge([
'url' => $this->get('name'),
]);
}
$this->merge([
'url' => \Str::slug($this->get('url')),
'active' => (int)$this->get('active'),
]);
}
}
I hope this information will be useful to somebody.
It work for me
$request = new Request();
$request->headers->set('content-type', 'application/json');
$request->initialize(['yourParam' => 2]);
check output
$queryParams = $request->query();
dd($queryParams['yourParam']); // 2
Great answers here but I needed to replace a value in a JSON request. After a little digging into the code, I came up with the following code. Let me know if I'm doing something dumb.
$json = $request->json()->all();
$json['field'] = 'new value';
$request->json()->replace($json);
Try that :
$request["name"] = "My New Value";
$request["img"] = $img;
It's worked in Laravel 8.
Also, make sure to update the model class.
Item
{
fillable=[
'img',
... // other attributes
];
}
in case of updating an item of object you can write the lines bellow
$Obj = $request->data;
$Obj['item'] = value;
please look at this.
The code below is from my model class (using datamapper orm)
function login()
{
$u = new User();
$u->where('username', $this->username)->get();
$this->salt = $u->salt;
$this->validate()->get();
if (empty($this->id))
{
// Login failed, so set a custom error message
$this->error_message('login', 'Username or password invalid');
return FALSE;
}
else
{
// Login succeeded
$data = array
(
'username' => $u->username,
'usergroup' => $u->usergroup->get(),
'is_logged_in' => true
);
$this->session->set_userdata($data);
return TRUE;
}
}
when i do this i get
**Fatal error: Call to a member function set_userdata() on a non-object**
but when i do this instead
$data = array
(
'username' => $u->username,
'usergroup' => $u->usergroup->get(),
'is_logged_in' => true
);
$obj=& get_instance();
$obj->session->set_userdata($data);
It works.
Please what is the right way to get this working ?
Thanks in advance.
your model did not extends CI_Model
after that you have to add constructor to your model
add this code to yours
function __construct()
{
parent::__construct();
$this->load->library('session');
}
Well, you didn't provide enough information.
The first code looks fine, provided that:
You actually load the session class before calling it (you also need to create an encryption key in your configs).
$this->load->library('session');
$this->session->set_userdata($data);
The above code, or your code, is inside a controller, a model or a view.
$this relates to the CI's superclass, in particular to an instance of the Session class, so if you're calling that inside a helper (collection of functions), or inside a library (where you need to create a CI instance first), it won't work.
After posting a form having two fields named 'id' and 'url' I have the following code:
$this->load->library('form_validation');
$this->form_validation->set_rules('id', 'id', 'trim|xss_clean');
$this->form_validation->set_rules('url', 'url|id', 'trim|xss_clean|callback_url_check');
A db query needs both fields.
The function url_check($str, $id) is called but in this case 'id' always has the value 0.
If I just do :
$this->form_validation->set_rules('url', 'url', 'trim|xss_clean|callback_url_check');
And call url_check($str) everything's working as it's is supposed to do.
The question is how do I pass two values to the url_check($str, $id)?
You can use $this->input->post directly:
function check_url() {
$url = $this->input->post('url');
$id = $this->input->post('id');
// do some database things you need to do e.g.
if ($url_check = $this->user_model->check_url($url, $id) {
return TRUE;
}
$this->form_validation->set_message('Url check is invalid');
return FALSE;
}
Just do it the right way (at least for CI 2.1+) as described in the docs:
$this->form_validation->set_rules('uri', 'URI', 'callback_check_uri['.$this->input->post('id').']');
// Later:
function check_uri($field, $id){
// your callback code here
}
This seems to work also.
$id = 1;
$this->form_validation->set_rules('username', 'Human Username', 'callback_username_check['.$id.']');
function username_check($str, $id) {
echo $id;
if ($str == 'test') {
$this->form_validation->set_message('username_check', 'The %s field can not be the word "test"');
return FALSE;
}
else {
return TRUE;
}
}
If I understand form_validation correctly, each rule (set_rules) is for one field of the form and your callback will only check the one field. In your case it would seem that 'id' is out of scope. Instead, one can pass an array to the set_rules function and do the callback. I have not tried this yet. http://codeigniter.com/user_guide/libraries/form_validation.html#validationrulesasarray
Just a note on using the callback parameters as suggested in the other answers. If you are using app/config/form_validation.php to create your validation rules, the $this->input->post('parameter') syntax will not work since that object is not available in the CI Loader at the point in the execution where it reads the contents of that file. You would have to do the call in your callback routine e.g. :
public function _validate_user_signup($username, $password) {
$var = $this->input->post('password');
In this case the second parameter passed to the method would not contain the password, but $var would after the call.
I hope that's clear.
Matt
It's better to use Form Validation library to get the data that is being validated.
Not always your data will be in $_GET or $_POST (see https://www.codeigniter.com/userguide3/libraries/form_validation.html#validating-an-array-other-than-post).
The best way you can access your data inside a validation callback is this:
$this->form_validation->validation_data
"validation_data" is a public property in the CI_Form_validation class.