Best way to make selects in laravel? - laravel

In order to use the Form::select, you need to add a name and two arrays.
In a normal case, we have one with the id and another one with the name. Both needs to be loaded from a query.
So in the model I have something like this:
public static function get_ids()
{
//return DB::query('select id FROM __roles');
return DB::table('roles')->get(array('id'));
}
//Returns an array with all the names
public static function get_names()
{
//return DB::query('select name FROM __roles');
return DB::table('roles')->get(array('name'));
}
However, this gives me this:
Array ( [0] => stdClass Object ( [id] => 1 ) [1] => stdClass Object ( [id] => 2 ) [2] => stdClass Object ( [id] => 3 ) )
I would like to get something like this:
Array ( [0] => '1' [id] => '2' [id] => '3' )
For the form
Form::select('role', array(Role::get_ids(), Role::get_names()));

Does this work?
public static function get_ids()
{
//return DB::query('select id FROM __roles');
return DB::table('roles')->get(array('id'))->to_array();
}
//Returns an array with all the names
public static function get_names()
{
//return DB::query('select name FROM __roles');
return DB::table('roles')->get(array('name'))->to_array();
}

I tried this option:
$projects = Project::where('user_id', Auth::user()->id)->lists('name', 'id');
In template:
{{ Form::select('project', $projects) }}

Related

I need To All Data In $qryy It Return Only Last Record

How I Return all data of $qryy it's return me only last record. How I need return all off data.
public function get_subcategory(){
$qry = $this->db->get("shopping_category");
foreach($qry->result() as $row){
$this->db->where("c_id",$row->id);
$qryy = $this->db->get("shopping_subcategory");
}
return $qryy;
}
You can try this
public function get_subcategory() {
$result = [];
$qry = $this->db->get("shopping_category");
foreach ($qry->result() as $row) {
$this->db->where("c_id", $row->id);
$qryy = $this->db->get("shopping_subcategory");
$result[] = $qryy;
}
return $result;
}
The reason you get the last record is, every time you loop data through foreach it keeps replacing $qryy = $this->db->get("shopping_subcategory");
to fix this you can simply change $qryy into an array $qryy[] like this.
To improve your query. you can simply try
$qryy = [];
$this->db->select("shopping_subcategory.*");
$this->db->from("shopping_category");
$this->db->join('shopping_subcategory', 'shopping_category.id = shopping_subcategory.c_id');
$sql= $this->db->get();
$qryy = $sql->result_array();
$data['category'] = $qryy;
$this->load->view('view_name', $data);
In view
$category will show your data
I think it solve your problem. would you mind if you give it a try?
since you want from table shopping_category is only id i try to fetch it so it's not a heavy duty on your server.
$result = [];
$qry = $this->db->select("id")->get('shopping_category');
foreach ($qry->result() as $row) {
$this->db->where("c_id", $row->id);
$qryy = $this->db->get("shopping_subcategory")->result();
$result[] = $qryy;
}
return $result;
Hope that helps :)
you should use another approach to resolve your problem: use joins to query the database only once:
$this->db->join("shopping_subcategory t2","t2.c_id=t1.id");
$qry = $this->db->get("shopping_category t1");
return $qry->result();
if you output above with print_r($qry->result()), you get similar to below:
Array
(
[0] => stdClass Object
(
[ID] => 1
[company_ID] => 1
[name] => aaa
)
[1] => stdClass Object
(
[ID] => 2
[company_ID] => 1
[name] => bbb
)
[2] => stdClass Object
(
[ID] => 4
[company_ID] => 2
[name] => ccc
)
)
to resolve your approach: you need to make $qryy an array, to store each subquery data, right now you are overwriting the variable $qryy with each loop and therefore only get the last result:
$qry = $this->db->get("shopping_category");
$qryy=array();
foreach($qry->result() as $i=>$row){
$this->db->where("c_id",$row->id);
$qryy[$i] = $this->db->get("shopping_subcategory")->result();
}
return $qryy;
if you output above with print_r($qryy), you get similar to below:
Array
(
[0] => Array
(
[0] => stdClass Object
(
[ID] => 1
[company_ID] => 1
[name] => aaa
)
[1] => stdClass Object
(
[ID] => 2
[company_ID] => 1
[name] => bbb
)
)
[1] => Array
(
[0] => stdClass Object
(
[ID] => 4
[company_ID] => 2
[name] => ccc
)
)
)
therefore, depending which approach you use, you'll need to take care of your data output differently.
helpful info on joins here

whereBetween passing array

Hi I have query where I want to pass an array to whereBetween query.
for example I have an array which looks like this
Array
(
[product_id] => Array
(
[0] => 31337
[1] => 31366
)
[lands] => Array
(
[0] => 12
[1] => 23
)
)
Now I want search those product_id which are between [0] => 31337 and [1] => 31366 and same goes to land I want to find the lands where Between [0] => 12 and [1] => 23
now say I have a variable $filters which has the this above array in it and I pass it like this to the query like below.
public function scopeDynamicInBetweenFilter($query, $filters)
{
if(!empty($filters)){
return $query->whereBetween($filters);
}
return $query;
}
It gives me an error
Type error: Too few arguments to function Illuminate\Database\Query\Builder::whereBetween(), 1 passed and at least 2 expected
it does like this at
Builder->whereBetween('product_id' => array('31337', '31366'))->whereBetween('lands' => array('12', '23'))
what could be done to achieve this.
You could try to loop through the filters and apply it to the query
public function scopeDynamicInBetweenFilter($query, $filters)
{
if(! empty($filters)) {
if (is_array($filters)) {
foreach ($filters as $key => $value) {
$query->whereBetween($key, $value);
}
}
}
return $query;
}
Try this:
if(!empty($filters)){
return $query->whereBetween('product_id', $filters['product_id'])->whereBetween('lands', $filters['lands']);
}

CONCAT_WS not working on select statement

Im trying to concatenate "firstname" and "lastname" like this "firstname lastname"
while doing a search query.
here's my code:
$query = Contact::find()
->select([
"CONCAT_WS(' ', firstname, lastname) AS name"
])
->where('(firstname like :fname) OR (lastname like :lname) OR (email = :email)', [
':fname' => $searchkey,
':lname' => $searchkey,
':email' => $searchkey,
])->all();
but the result is empty like this:
Array
(
[0] => common\models\contact\Contact Object
(
[_attributes:yii\db\BaseActiveRecord:private] => Array
(
)
[_oldAttributes:yii\db\BaseActiveRecord:private] => Array
(
)
[_related:yii\db\BaseActiveRecord:private] => Array
(
)
[_errors:yii\base\Model:private] =>
[_validators:yii\base\Model:private] =>
[_scenario:yii\base\Model:private] => default
[_events:yii\base\Component:private] => Array
(
)
[_behaviors:yii\base\Component:private] => Array
(
)
)
)
I'm expecting that i'll have something like this
[name] => "firstname lastname"
output but no luck. need help thanks.
You should add a public var $name in your Contcat model and add attribute as safe in rules for recive the calculated value with alias name
class Contact extends \yii\db\ActiveRecord
{
public $name;
....
}

Laravel : 3 tables linked with a central pivot. How to translate this to Laravel Eloquent ORM?

Hello and thanks for reading this,
A student have several courses and an individual project assigned to this course.
Multiple individual projects are available but only one by student by course.
If i want to know which individual project is assigned to student 10 for the course 1.. I could ask it this way.
Select Individual_project.* FROM Individual_project
INNER JOIN Students_has_Course ON Individual_project.id =
Students_has_Course.Individual_project_id
INNER Course ON Students_has_Course.Course_id = Course.id
INNER JOIN Students ON Students_has_Course.Students_id=Students.id
wHere Students.id=10 AND Course.id=1
I'm trying to translate these relations into Laravel models using Eloquent but I think that I'm missing something.
It's easy to make a relationship to find courses related to a students..
class Students extends Eloquent {
public function courses()
{
return $this->belongsToMany('Course','Students_has_Course','Course_id');
}
}
But I don't know how to make a complex join to obtain a collection of students with their courses and the related individual project for each of them.
Thanks again for reading this. I hope that it is understandable. English is not my first language and It's very late. I will provide more details if necessary.
You have a problem with your model. You shouldn't put courses and projects in the same pivot table. What happens when a single student, in a single course, has 3 projects and you query your pivot table? You get something like:
john doe =>
courses =>
course 1 =>
project 1 data
course 1 =>
project 2 data
course 1 =>
project 3 data
You would be better off breaking the different relationships into separate pivot tables. It is a bit more work, but it offers much more flexibility. Note that I changed the table/column names to match Laravel conventions.
class Course extends Eloquent {
protected $table = 'courses';
public function projects() {
return $this->belongsToMany('Project', 'course_project', 'course_id', 'project_id');
}
public function students() {
return $this->belongsToMany('Student', 'course_student', 'course_id', 'student_id');
}
}
class Student extends Eloquent {
protected $table = 'students';
public function courses() {
return $this->belongsToMany('Course', 'course_student', 'course_id', 'student_id');
}
public function projects() {
return $this->belongsToMany('Project', 'project_student', 'project_id', 'student_id');
}
}
class Project extends Eloquent {
protected $table = 'projects';
public function courses() {
return $this->belongsToMany('Course', 'course_student', 'course_id', 'student_id');
}
public function students() {
return $this->belongsToMany('Student', 'course_student', 'course_id', 'student_id');
}
}
$studentsCoursesProjects = Student::with('courses', 'courses.projects')->get()->toArray();
Array
(
[0] => Array
(
[id] => 1
[name] => John Doe
[courses] => Array
(
[0] => Array
(
[id] => 1
[name] => Intro to Laravel
[pivot] => Array
(
[course_id] => 1
[student_id] => 1
)
[projects] => Array
(
[0] => Array
(
[id] => 1
[desc] => Routing
[pivot] => Array
(
[course_id] => 1
[project_id] => 1
)
)
[1] => Array
(
[id] => 2
[desc] => Eloquent
[pivot] => Array
(
[course_id] => 1
[project_id] => 2
)
)
)
)
)
)
)
$studentsProjectsCourses = Student::with('projects', 'projects.courses')->get()->toArray();
Array
(
[0] => Array
(
[id] => 1
[name] => John Doe
[projects] => Array
(
[0] => Array
(
[id] => 1
[desc] => Routing
[pivot] => Array
(
[project_id] => 1
[student_id] => 1
)
[courses] => Array
(
[0] => Array
(
[id] => 1
[name] => Intro to Laravel
[pivot] => Array
(
[course_id] => 1
[student_id] => 1
)
)
)
)
)
)
)
Doing it this way gives you the ability to do all sorts of cool stuff with Eloquent.
$studentsCoursesProjectsFilter = Student::with(array('courses' => function($query) { }, 'courses.projects' => function ($query ) {
$query->where('projects.id', 1);
}))->get()->toArray();
EDIT:
If changing the db model isn't an option then you can do something like this:
class Student extends Eloquent {
protected $table = 'students';
public function courses() {
return $this->belongsToMany('Course', 'course_student', 'course_id', 'student_id');
}
public function projects() {
return $this->belongsToMany('Project', 'course_student', 'project_id', 'course_id');
}
}
$students = Student::with('courses', 'courses.projects')->get()->toArray();

codeignite trying to get property of non-object not resolved

I am attempting to access the result set from a model query in the view. I have the following:
Controller:
$courseId = $this->session->userdata('courseId');
//echo "Course: ".$courseId;
if(isset($courseId) && $courseId != '')
{
$result = $this->Course_model->loadBasicDetailsEdit($courseId);
$data['basicCourseDetails'] = $result;
$this->load->view('course/basicDetails', $data);
}
Model:
function loadBasicDetailsEdit($courseId)
{
$this->db->select('*');
$this->db->where('course_id', $courseId);
$this->db->from('course');
$query = $this->db->get();
if ( $query->num_rows() > 0 )
{
return $query->result();
} else {
return FALSE;
}
}
and in the view I tried to print_r() and got this:
Array ( [0] => stdClass Object ( [course_id] => 8 [title] => Photography [summary] => [description] => [price] => [member_id] => 12 [category] => [audience] => [goals] => [date] => 2013-09-26 [production] => 0 ) )
I tried to access this using $basicCourseDetails->title or $basicCourseDetails['title']
but neither are working. Any hint as to why this is happening?
Regards,
try this:
foreach($basicCourseDetails as $basic){
echo($basic->title);
}
or something like this:
echo($basicCourseDetails[0]->title);
This is an array of objects
Array ( [0] => stdClass Object ( [course_id] => 8 [title] => Photography [summary] => [description] => [price] => [member_id] => 12 [category] => [audience] => [goals] => [date] => 2013-09-26 [production] => 0 ) )
Contains one stdObject in the array, so, first objects is 0, if there were more, then second item could have index 1 and so on. To retrieve data from the first (here is only one) stdobject you may use
echo $basicCourseDetails[0]->title; // title will be printed
You can send data to the view page by this line of code which is mentioned in above question.
$result = $this->Course_model->loadBasicDetailsEdit($courseId);
$data['basicCourseDetails'] = $result;
$this->load->view('course/basicDetails', $data);
But when you will access these data in view then you need to access all data one by one by using foreachloop in the view page.
For example if you have a view page like basic_details.php inside course folder then you need to write code like this to access these data.
foreach ($basicCourseDetails as $key => $value) {
$name = $value->name;
}
The above foreachloop can be written in view page where you want to access data.

Resources