Laravel 4 500 Internal Server Error when query database - laravel

I am using code below
$users = DB::table('users')->find(1);
And I got 500 Internal Server Error
but when I use
$users = DB::table('users')->get();
It works, what is the issue with first code snippet?

Using find() with query builder, e.g. DB::table(...)->find() only works if you have primary key (or a column) named "id". Do you have an "id" column?
If not you'll need to use:
$users = DB::table(...)->where('your_primary_key', '=', 1)->first();
Reference: framework/src/Illuminate/Database/Query/Builder.php:
public function find($id, $columns = array('*'))
{
return $this->where('id', '=', $id)->first($columns);
}

Related

How to add custom if..else statements to the selected columns at a query for exporting data from database into excel file

I'm using Laravel 5.8 and laravel-excel for exporting some data into an Excel file.
So I added this method to the Model:
public static function getAccounts($id)
{
$records = DB::table('members')
->where('mys_creator_id',$id)
->where('mys_olp_id',4)
->join('my_students', 'members.mbr_usr_id', '=', 'my_students.mys_mbr_id')
->join('students', 'members.mbr_usr_id', '=', 'students.std_mbr_id')
->select('members.mbr_name', 'members.mbr_family', 'members.mbr_father_name','members.mbr_national_code','members.mbr_birthday','members.mbr_phone','members.mbr_mobile','members.mbr_post_code','members.mbr_prv_id','members.mbr_cit_id','members.mbr_gender_id','members.mbr_address','students.std_degree_id','students.std_grade_id','students.std_filed_id','students.std_major_id','students.std_school','students.std_education_type_id','my_students.mys_paid_price')
->get()->toArray();
return $records;
}
And this works fine but some of data holds and id instead of text value:
And all these ids are stored in baseinfos table. For example std_degree_id of 8 goes like this:
And now instead of returning number 8, I need to get bas_value and return it in the exported Excel file.
So it would looked like this:
if(students.std_degree_id == 9){
// print Elementry
}elseif(students.std_degree_id == 10){
// print Academy
}else{
...
}
So how can I do that?
UPDATE #1:
$records = DB::table('members')
->where('mys_creator_id',$id)
->where('mys_olp_id',4)
->join('my_students', 'members.mbr_usr_id', '=', 'my_students.mys_mbr_id')
->join('students', 'members.mbr_usr_id', '=', 'students.std_mbr_id')
->join('baseinfos', 'students.std_degree_id', '=', 'baseinfos.bas_id')
->join('baseinfos', 'members.mbr_gender_id', '=', 'baseinfos.bas_id')
->select(...,'baseinfos.bas_value','members.mbr_address','baseinfos.bas_value',...)->get()->toArray();
return $records;
If I add two more joins with baseinfos table, I get this error:
SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique
And this mainly because I get baseinfos.bas_value twice in the select.
You'd need to join one more table and show the corresponding field from that table:
public static function getAccounts($id)
{
$records = DB::table('members')
->where('mys_creator_id',$id)
->where('mys_olp_id',4)
->join('my_students', 'members.mbr_usr_id', '=', 'my_students.mys_mbr_id')
->join('students', 'members.mbr_usr_id', '=', 'students.std_mbr_id')
->join('baseinfos', 'students.std_degree_id', '=', 'baseinfos.bas_id')
->select('members.mbr_name', 'members.mbr_family', 'members.mbr_father_name','members.mbr_national_code','members.mbr_birthday','members.mbr_phone','members.mbr_mobile','members.mbr_post_code','members.mbr_prv_id','members.mbr_cit_id','members.mbr_gender_id','members.mbr_address','baseinfo.bas_value','students.std_grade_id','students.std_filed_id','students.std_major_id','students.std_school','students.std_education_type_id','my_students.mys_paid_price')
->get()->toArray();
return $records;
}
I am not sure if you are using getAccounts anywhere else, If you are create a new method to format this data.
public static function getAccounts($id)
{
$degrees = [
9 => 'Elementry',
10 => 'Academy',
];
$records = DB::table('members')
->where('mys_creator_id',$id)
->where('mys_olp_id',4)
->join('my_students', 'members.mbr_usr_id', '=', 'my_students.mys_mbr_id')
->join('students', 'members.mbr_usr_id', '=', 'students.std_mbr_id')
->select('members.mbr_name', 'members.mbr_family', 'members.mbr_father_name','members.mbr_national_code','members.mbr_birthday','members.mbr_phone','members.mbr_mobile','members.mbr_post_code','members.mbr_prv_id','members.mbr_cit_id','members.mbr_gender_id','members.mbr_address','students.std_degree_id','students.std_grade_id','students.std_filed_id','students.std_major_id','students.std_school','students.std_education_type_id','my_students.mys_paid_price')
->get();
// if map is not working add it in collect($records)->map.
$records->map(function($record) use($degrees) {
$record->std_degree_id = $degrees[$record->std_degree_id];
return $record;
});
return $records->toArray();
}
But I am guessing $record->std_degree_id is a relation, so just use the relation title instead of the array map i created.

Join Laravel tables

I have got three tables Kudos, Kudoscategories, and specialpost. I need to get the data from those tables and check the post id using a where condition.
I have attached the database table screenshot here
I already tried this, but it's not getting any result.
$results = DB::table('kudos')
->select('kudos.description','kudoscategory.catname','kudoscategory.image','kudos.spid')
->join('kudoscategory', 'kudoscategory.id', '=', 'kudos.categoryid')
->where('kudos.spid', '=', $post_id)
->first();
return $results;
What I need to do is get the results using below where condition newsfeed_special_posts.main_post_id = kudos.spid
You must add another join with newsfeed_special_posts.
The query will be like,
$results = DB::table('kudos')
->select('kudos.description','kudoscategory.catname','kudoscategory.image','kudos.spid')
->join('kudoscategory', 'kudoscategory.id', '=', 'kudos.categoryid')
->join('newsfeed_special_posts', 'newsfeed_special_posts.main_post_id', '=', 'kudos.spid')
->where('kudos.spid', '=', $post_id)
->first();
return $results;
Though this is not a good practice for laravel. using laravel eloquent relationships will be more efficient for these results.
https://laravel.com/docs/5.8/eloquent-relationships
you can still do it this way. still efficient to avoid sql injection since you are getting all the record from the 3 tables. seeing your table above, its not properly normalised. anywaye try this.
$results = DB::table('kudos')
->leftjoin('kudoscategory', 'kudoscategory.id', '=', 'kudos.categoryid')
->leftjoin('newsfeed_special_posts', 'newsfeed_special_posts.id', '=', 'kudos.spid')
->where('kudos.spid', '=', $post_id)
->first();
return $results;
you can try this code
at first, create model Kudos,KudosCategory,NewsfeedSpecialPosts
Kudos Model
public function kudoscategory_dta()
{
return $this->belongsTo('App\Model\KudosCategory','categoryid');
}
public function newsfeed_special_posts_dta()
{
return $this->belongsTo('App\Model\NewsfeedSpecialPosts','spid','main_post_id ');
}
controller
Kudos::with('kudoscategory_dta','newsfeed_special_posts_dta')->first();

Joining 2 scopes laravel

I've been trying to solve this for quite a while now. I want to join these two scopes from my Match Model:
public function scopeMainMatches($query)
{
return $query->where('type', 'main');
}
public function scopeDotaMatches($query)
{
return $query->join('leagues', function ($join) {
$join->on('matches.league_id', '=', 'leagues.id')
->select('matches.*')
->where('leagues.type', '=', 'dota2')
->where('matches.type', '=', 'main');
});
}
so basically, when I put in into join eloquent relationship it will be the same like this:
$query = DB::table('matches')
->join('leagues', 'leagues.id', '=', 'matches.league_id')
->select('matches.*')
->where('leagues.type', '=', 'dota2')
->get();
it works fine during the terminal check. but I need to connect 2 scopes for the Controller which looks like this:
$_matches = \App\Match::mainMatches()
->get()
->load('teamA', 'teamB')
->sortByDesc('schedule');
so when I try to connect mainMatches and dotaMatches, it doesn't show up on the matches. although when i run php artisan tinker, it returns the correct output, but it won't show up on the matches table.
$_matches = \App\Match::mainMatches()
->dotaMatches()
->get()
->load('teamA', 'teamB')
->sortByDesc('schedule');
any Ideas how to work on this? TYIA!
I've managed to join two tables in just one scope here is the code:
public function scopeMainMatches($query) {
return $query->join('leagues','leagues.id','=','matches.league_id')->select('matches.*')->where('matches.type', 'main');
}

Eloquent / Laravel - Putting a WHERE Clause on a Reference Table With Chained Relationships

I have the following relationship functions in my Job model:
public function resourceTypes(){
return $this->belongsToMany('ResourceType', 'job_requests');
}
public function resources(){
return $this->belongsToMany('Resource', 'jobs_resources')->withPivot('flow_type', 'resource_type_id');
}
I am able to get an object with data from both of the above relationships using:
$job = Job::findorfail($projectId);
$result = $job->with('resources.resourceTypes')->get();
I would like to put a where clause on the jobs_resources pivot table - specifically on the column flow_type.
How would I do this?
Try something like this:
$job = Job::with('resources' => function($q) {
$q->with('resourceTypes')->where('flow_type',2);
})->findorfail($projectId);
In above you will get only those resources with flow_type = 2
I ended up using the following statement:
Job::with(['resources' => function ($query){
$query->wherePivot('flow_type', '=', '1' );
}, 'resources.resourceTypes'])->where('id', $projectId)->firstOrFail();
$result = DB::table('job')
->join('job_resources', 'job.id', '=', 'job_resources.job_id')
->join('job_requests', 'job_resources.request_id', '=', 'job_requests.id')
->where('job_resources.flow_type', '=', CONDITION)
->get();
Your table data is not clear from your input, but this method (query builder) should work

Laravel eloquent and relationship

I have a code:
$response = $this->posts
->where('author_id', '=', 1)
->with(array('postComments' => function($query) {
$query->where('comment_type', '=', 1);
}))
->orderBy('created_at', 'DESC')
->limit($itemno)
->get();
And when I logged this query with:
$queries = \DB::getQueryLog();
$last_query = end($queries);
\Log::info($last_query);
In log file I see follow:
"select * from `post_comments` where `post_comments`.`post_id` in (?, ?, ?, ?) and `comment_type` <> ?"
Why is the question mark for comment_type in the query?
Update #1:
I replaced current code with following and I get what I want. But I'm not sure it is OK. Maybe exists many better, nicer solution.
$response = $this->posts
->where('author_id', '=', 1)
->join('post_comments', 'post_comments.post_id', '=', 'posts.id')
->where('comment_type', '=', 1)
->orderBy('created_at', 'DESC')
->limit($itemno)
->get();
Behind the scene the PDO is being used and it's the way that PDO does as a prepared query, for example check this:
$title = 'Laravel%';
$author = 'John%';
$sql = "SELECT * FROM books WHERE title like ? AND author like ? ";
$q = $conn->prepare($sql);
$q->execute(array($title,$author));
In the run time during the execution of the query by execute() the ? marks will be replaced with value passed execute(array(...)). Laravel/Eloquent uses PDO and it's normal behavior in PDO (PHP Data Objects). There is another way that used in PDO, which is named parameter/placeholder like :totle is used instead of ?. Read more about it in the given link, it's another topic. Also check this answer.
Update: On the run time the ? marks will be replaced with value you supplied, so ? will be replaced with 1. Also this query is the relational query, the second part after the first query has done loading the ids from the posts table. To see all the query logs, try this instead:
$queries = \DB::getQueryLog();
dd($queries);
You may check the last two queries to debug the queries for the following call:
$response = $this->posts
->where('author_id', '=', 1)
->with(array('postComments' => function($query) {
$query->where('comment_type', '=', 1);
}))
->orderBy('created_at', 'DESC')
->limit($itemno)
->get();
Update after clarification:
You may use something like this if you have setup relation in your Posts model:
// $this->posts->with(...) is similar to Posts::with(...)
// if you are calling it directly without repository class
$this->posts->with(array('comments' =. function($q) {
$q->where('comment_type', 1);
}))
->orderBy('created_at', 'DESC')->limit($itemno)->get();
To make it working you need to declare the relationship in your Posts (Try to use singular name Post if possible) model:
public function comments()
{
return $this->hasmany('Comment');
}
Your Comment model should be like this:
class Comment extends Eloquent {
protected $table = 'post_comments';
}

Resources