Code Igniter Models & libraries - codeigniter

in CI i created a model called "User" which has a method called "entries" and another one called "books"
I would like to pass a $user_id parameter to the model so it creates an instance of the class in my controller.
the way I currently call the model in the controller is :
$data1 = $this->user->entries($user_id);
$data2 = $this->user->books($user_id);
I would like to pass that user_id parameter directly to the constructor so that i dont have to use the $user_id parameter each time
perhaps something like this ( i know the syntax is wrong in this case):
$this->load->model('user',$user_id);
$data['row1'] = $this->user->entries();
$data['row2'] = $this->user->books();
Please forgive my lack of understand of OOP ..i just made the switch.
thanks for your help

You cannot pass variables to the constructor, but you could make a method to set the userID, and then use it.
Example:
class user extends CI_Model{
var $user_id;
function __construct(){
parent::__construct();
}
function set_user_id($user_id){
$this->$user_id = $user_id;
}
}
And then inside your entries and books books method, you can use $this->$user_id, without needing to pass it again.
Like so:
function entries(){
$user_id = $this->user_id;
}

Related

Why we need to create a function in model page for relation

public function single($category, $slug)
{
$category = Category::where('slug', $category)->first();
$article = Article::where('slug', $slug)->where('category_id', $category->id)->first();
$data['comments'] = Comment::where('article_id', $article->id)->get();
}
These codes are on my controller page. When I take the comments on my article page it is working fine.
But on the laravel webpage, they say we have to create function in Model. Why we need to create a function in Model page? My structure is working fine without extra function.
I will be glad if you explain, thank you.
the difference is you can do something like this with a single db query and alter the results:
public function single($category, $slug)
{
$category->where('slug', $category)->articles()->where('slug', $slug)->with('comments');
}

Laravel 6, passing multiple arrays from a controller to a view

I'm brand new to Laravel, I need to display around 8 different drop down menus on a page all populated from tables in my Db, I am using blades.
In my controller I can create various types of arraysin one function (using eloquent) and I can dd(); them out correctly one at a time, my issue appears to be that you can only pass one array through a controller to a view. I have tried various options I found here but without success, including ->with and compact(). I have tried defining the arrays in the controller one at a time and passing them using compact() all result in errors either the variable not defined or trying to get an non-object. I am obviously going about this all wrong any help would be great.
This is not a code issue (hence no code posted) I think it more of a Laravel issue that I don't yet understand, thanks in advance.
Try like this
class YourController extends Controller{
public function yourMethod(){
$arr1 = [];
$arr2 = [];
return view('view.name', ['arr1' => $arr1, 'arr2' => $arr2]);
}
}
If you have:
$array1 = [...];
$array2 = [...];
Then you can:
return view('path.to.view', compact('array1', 'array2');
This is my route from web.php and my controller from ReservationContoller any help as to my the arrays wont pass would be great, many thanks.
Route::get('/client/{client}/reservation/{reservation}', 'ReservationController#getReservation');
public function getReservation($client, $reservation)
{
$client = Client::findOrFail($client);
$reservation = Reservation::where('client_id', $client->id)->get();
$company = Company::where('type', 'staghen')
->where('status', 'Active')
->orderBy('comp_name')
->pluck('comp_name', 'id');
$cl = array(['client' => $client]);
$res = array(['reservation' => $reservation]);
$comp = array(['company' => $company]);
return view('admin.reservations.reservation', compact('$cl', '$res', '$comp'));
}

Pass specific id to model and take data from database using codeigniter?

My controller method like below
public function index($book_id) {
print_r($book_id);
}
I will get the id from view. View like below
I need to get specific row according id on model how can I do that if I use query in controller its not working
If I use like below in controller it gives something else as result
public function index($book_id) {
print_r($book_id);
$this->db->select('*');
$this->db->from('books')->where('book_id', $book_id);
$query = $this->db->get();
print_r($query);
}
but if I use same query in model with hard coded id for testing it gives the expected out put
Please help me with this
You don't need to include "/index" in anchor tag href as controller default method will be index if found. And "print_r($book_id)" should be "echo $book_id" as $book_id is variable not array.
Please try this code (either in model/controller):
$query = $this->db->get_where('books', array('book_id' => $book_id));
$result = $query->row_array();
print_r($result);

codeigniter pass variable from controller to model

simple issue I presume.
My controller is getting the if to display from the url using $this->uri->segment(3). This will always be a single value. I am putting this in an array to pass to the model with:
$customerid = array(
'id' => $this->uri->segment(3)
);
The controller syntax is below:
function confirm_delete_customer()
{
$data['title']="Confirm Customer Deletion";
$customerid=array(
'id'=>$this->uri->segment(3)
);
//query model to get data results for form
$data=array();
if($query=$this->model_master_data->get_customer_records_to_delete()){
$data['records']=$query;
$this->load->view("master_data/view_master_data_header",$data);
$this->load->view("master_data/view_master_data_nav");
$this->load->view("master_data/view_content_master_data_confirm_customer_deletion",$data);
$this->load->view("master_data/view_master_data_footer");
}
I am then trying to access this array value and pass it to my model to process. If I hard code the array into the model it works as per below syntax:
Model - Manual Syntax is:
function get_customer_records_to_delete()
{
$query = $this->db->get_where('customers', array('id'=>43));
return $query->result();
}
if I try replace this with the array from my controller it fails with error:
Undefined variable: customerid
idea of model that I want to get working:
function get_customer_records_to_delete()
{
$query = $this->db->get_where('customers', $customerid);
return $query->result();
}
I have a feeling it is something small. however is this the best way to get a single record from the database in order to output to a view?
Thanks in advance for the assistance.
The best way to do that is:
function confirm_delete_customer()
{
$data=array();
$data['title']="Confirm Customer Deletion";
$customerId = $this->uri->segment(3);
//Prevent SQL injections
if(!is_numeric($customerId) || empty($customerId)) {
show_error("Bad Request");
}
$query = $this->model_master_data->get_customer_records_to_delete($customerId);
if ($query){
$data['records']=$query;
$this->load->view("master_data/view_master_data_header",$data);
$this->load->view("master_data/view_master_data_nav");
$this->load->view("master_data/view_content_master_data_confirm_customer_deletion",$data);
$this->load->view("master_data/view_master_data_footer");
}
}
and then you can simply call:
function get_customer_records_to_delete($customerId)
{
$query = $this->db->get_where('customers', array('id'=>$customerId));
return $query->result();
}
at your model.
You need to pass the value as an argument to the function so it can access it.
Ex:
get_customer_records_to_delete($customerid)
{
// now $customerid is accessible
$query = ....;
return $……;
}
You should heavily rely on function parameters. Grab the customer id from the controller and send it to the model. Moreover, you can use row() to get a single result from the database.
Controller:
function confirm_delete_customer(){
$data['title']="Confirm Customer Deletion";
$customerid=$this->uri->segment(3);
//query model to get data results for form
$data=array();
if($query=$this->model_master_data->get_customer_records_to_delete( $customerid)) //you are sending customer id as a parameter here
$data['records']=$query;
$this->load->view("master_data/view_master_data_header",$data);
$this->load->view("master_data/view_master_data_nav");
$this->load->view("master_data/view_content_master_data_confirm_customer_deletion",$data);
$this->load->view("master_data/view_master_data_footer");
}}
Model
function get_customer_records_to_delete($customerid)
{
$query = $this->db->get_where('customers', array("id"=>$customerid)); //you are using the customer id sent from the controller here
return $query->row(); //this will return a single row
}
Old thread but the answer is to declare the variable as "public" in the controller (i.e. public $customerid;), in which case it'll be available to your model. In some cases it's probably safer to explicitly pass as an argument. However, when you have several variables, it's useful to have the option to declare them instead.

how to pass a value to model function in code igniter

I want to pass a user id value in variable $userID, to a function in a Model class Clientmodel. The function is get_username(), now in a model do I have to define that function to accept a variable as a parameter? so.. get_username($userID)? Just want to know how is the recommended way in code igniter?
Thanks!
tariq
That really depends on what you use the model for. Most of the time, it will make sense to have a parameter to the method and use that every time:
// Model
function get_username($userID)
{
// do something with $userID
}
// Controller
$this->some_model->get_username($some_id);
On the other hand, sometimes it makes sense for the Model to be "stateful" -- do you have one userID per controller? Will it ever be more than one? Do you need the userID in a large number of methods of that model? Then maybe this will make sense instead:
// Model
function set_userid($userID)
{
$this->userID = $userID;
}
function get_username()
{
// do something with $this->userID
}
// Controller
$this->some_model->set_userid( $some_id );
$this->some_model->get_username();
Other times, you may have one userID which you plan on using over and over, but sometimes you need to use another value, that is when default arguments come into play:
// Model
function set_userid($userID)
{
$this->userID = $userID;
}
function get_username( $userID = NULL )
{
if( $userID === NULL ) $userID = $this->userID;
// do something with $userID (not $this->userID)
}
// Controller
$this->some_model->set_userid( $some_id );
$this->some_model->get_username();
The solution is not Codeigniter specific in any way, it's just basic PHP. Your model is a class, and get_username() is a function that takes arguments.
The most basic way to do it is this:
// Model
function get_username($userID)
{
// do something with $userID
}
// Controller
$this->some_model->get_username($some_id);
Make sure you read about default arguments so you can decide what to do if $userID is not passed (you may not need a default here though), and make sure you check that the value is valid.

Resources