Just getting started into laravel and need to run the same db query for 2 different views, I know I could just create 2 controllers and perform the same query in both passing it to each view.
But, is that the proper way? Or is there a way without repeating my code?
Thanks!
Edit:
I have the following function inside a controller:
protected function getLocation($url)
{
$match = ['url' => $url];
$location = DB::table('location')->where($match)->first();
if (!$location) {
abort(404);
}
return $location;
}
the controller is returning that data to a view:
public function showsubcatandlocation($service)
{
$category = $this->getCat($service);
$location = $this->getLocation($category);
$id = $category->id;
$locID = $location->id;
$profiles = $this->getProfileswLoc($id, $locID);
return view('category', ['profile' => $profiles]);
}
What's the proper way to reuse the getLocation function? Or should I just copy it in the new controller? I just need to use it in those 2 views.
maybe scope Query helps?
class Location extends Model
{
public function scopeMatch($query, $url)
{
return $query->where('url', $url);
}
}
And then your two controllel methods will be
$location = Task::match($url)->first();
if (!$location) {
abort(404);
}
return $location;
$category = $this->getCat($service);
$location = Task::match($category['url'])->first();
$id = $category->id;
$locID = $location->id;
$profiles = $this->getProfileswLoc($id, $locID);
return view('category', ['profile' => $profiles]);
Related
I am trying to get the data from a foreach loop in my controller to pass to my view. How do I do it?
Controller
class FormteachersController extends Controller
{
public function form_teachers_view(){
$UniqueStudent = Student::where('Student_ClassID','JSS 1C')->get();
foreach ($UniqueStudent as $keydata) {
$student = $keydata->Stud_id;
$result= Result::where('Term_ID','1st Term')->where('Student_ID',$student)->where('Class_ID','JSS 1C')->where('Session_ID','2225/2222')->get();
foreach ($result as $keyresult) {
echo '<br>'.'<br>'.$student.'-'.$result;
}
return view('teachers.form_teachers_comment_sec');
}
}
}
This is the output.
You can do something like this:
class FormteachersController extends Controller
{
public function form_teachers_view(){
$uniqueStudent = Student::where('Student_ClassID','JSS 1C')->get();
$uniqueStudentsData = [] ;
foreach ($uniqueStudent as $keydata) {
$student = $keydata->Stud_id;
$result = Result::where('Term_ID','1st Term')->where('Student_ID',$student)->where('Class_ID','JSS 1C')->where('Session_ID','2225/2222')->get();
foreach ($result as $keyresult) {
$uniqueStudentsData[] = '<br>'.'<br>'. $student.'-'. $keyresult;
}
}
return view('teachers.form_teachers_comment_sec', compact('uniqueStudentsData'));
// or pass array
return view('teachers.form_teachers_comment_sec',[
'uniqueStudentsData' => $uniqueStudentsData,
]);
}
}
Now, in your form_teachers_comment_sec.blade.php, run your foreach loop and do what do you want to there
// $uniqueStudentsData
#foreach($uniqueStudentsData as $data)
// do what do you want
#endforeach
Hopefully, it will be work. more documentation please visit laravel documentation
When i store a new record, Laravel returns the new record. Everything works fine.
When i update a record, Laravel returns the old record. I like to return the updated record.
Controller
public function store(StoreProjectRequest $request)
{
$data = $this->repo->create( $request->all());
return response()->json(new ProjectResource($data));
}
public function update(UpdateProjectRequest $request, Project $project)
{
$data = $this->repo->update($project, $request->all());
return response()->json(new ProjectResource($data));
}
Repository
public function create( $data)
{
$this->model->name = $data['name'];
$this->model->description = $data['description'];
$this->model->sales_order_id = $data['sales_order_id'] ? $data['sales_order_id'] : NULL;
$this->model->project_leader_id = $data['project_leader_id'];
$this->model->project_type_id = $data['project_type_id'];
$this->model->project_status_id = $data['project_status_id'];
$this->model->creator_id = Auth()->id();
$this->model->save();
return $this->model;
}
public function update($model, $data)
{
$model->name = $data['name'];
$model->description = $data['description'];
$model->sales_order_id = $data['sales_order_id'];
$model->project_leader_id = $data['project_leader_id'];
$model->project_type_id = $data['project_type_id'];
$model->project_status_id = $data['project_status_id'];
$model->save();
return $model;
}
When i add $data = Project::find($project->id)i receive the updated model.
But is this the only way?
The reason the $data is returning as the old data is because it still stores the data from when the variable was created. When you call $data->fresh() it will go fetch the new data and return it. Does that make sense?
My Model code is given below.
public function getattendence($data)
{
$sql="CALL `sp_AttendanceDetails`(?,?,?);";
$query=$this->db->query($sql,$data);
return $query->result_array();
}
But it return one result set.The second result set i not get..
Pass data like this
public function getattendence($data)
{
# example of your $data array
$id = $data['id'];
$name = $data['name'];
$date = $data['date'];
$sql="CALL sp_AttendanceDetails($id,'$name',$date);";
$query=$this->db->query($sql);
return $query->result_array();
}
Use return $this->_execute_multi_query($sql);
refer http://php.net/manual/en/mysqli.multi-query.php
Ok I want to pass two variables from a controller to a model but I get some kind of error. Am I passing variables on right way? My syntax is:
Controller:
public function add_tag(){
if(isset($_POST['id_slike']) && isset($_POST['id_taga'])){
$slika = $_POST['id_slike'];
$tag = $_POST['id_taga'];
$this->load->model("Member_model");
$res = $this->Member_model->add_tags($slike, $tag);
foreach ($res->result() as $r){
echo $r->name;
}
}
else{
echo "";
}
}
Model:
public function add_tags(){
$data = array(
'tags_id' => $tag ,
'photos_id' => $slika
);
$check = $this->db->query("SELECT tags_id,photos_id FROM bridge WHERE bridge.tags_id='{$tag}' AND bridge.photos_id={$slika} ");
if($check->num_rows()==0){
$this->db->insert('bridge',$data);
$res = $this->db->query("SELECT name FROM tags where `tags`.`id`='{$tag}' ");
return $res;
}
}
you are passing variables correctly, but do not get them correctly in the model, which should look like this:
public function add_tags($slike, $tag){
//your other code
}
The following code write on the controller file:-
$data = array();
$this->load->model('dbmodel');
$data['item'] = $this->dbmodel->getData('*','catagory',array('cat_id'=>21));
$this->load->view('listing_view', $data);
The following code write on the dbmodel file:-
public function getData($cols, $table, $where=array()){
$this->db->select($cols);
$this->db->from($table);
$this->db->where($where);
$query = $this->db->get();
$result = $query->result();
return $result;}
In CI, I have a model...
<?php
class User_crud extends CI_Model {
var $base_url;
var $category;
var $brand;
var $filter;
var $limit;
var $page_number;
public function __construct($category, $brand, $filter, $limit, $page_number) {
$this->base_url = base_url();
$this->category = $category;
$this->brand = $brand;
$this->filter = $filter;
$this->limit = $limit;
$this->page_number = $page_number;
}
public function get_categories() {
// output
$output = "";
// query
$this->db->select("name");
$this->db->from("categories");
$query = $this->db->get();
// zero
if ($query->num_rows() < 1) {
$output .= "No results found";
return $output;
}
// result
$output .= "<li><a class=\"name\">Categories</a></li>\n";
foreach ($query->result_array as $row) {
$output = "<li>{$row['name']}</li>\n";
}
return $output;
}
while I am calling this in my controller...
<?php
class Pages extends CI_Controller {
// home page
public function home() {
}
// products page
public function products($category = "cell phones", $brand = "all", $filter = "latest") {
// loading
$this->load->model("user_crud");
//
}
Now, How can I pass the $category, $brand and $filter variables to the user_crud model while loading/instantiation?
You shouldn't be using your model like this, just pass the items you need for the functions you require:
$this->load->model("user_crud");
$data['categories'] = $this->user_crud->get_categories($id, $category, $etc);
I would suggest (after seeing your code) that you study the fantastic codeigniter userguide as it has really good examples, and you just went a totally different way (treating model like an object). Its more simple sticking to how it was designed vs what you are doing.
You can not. A better idea would be to setup some setters in your model class along with some private vars and set them after loading the model.
if you return $this from the setters you can even chain them together like $this->your_model->set_var1('test')->set_var2('test2');