Laravel ORM select query function load() on null - php

Here's my function to load submissions created by a user.
public function viewSubs()
{
$user = User::find(Input::get('id'));
$submissions = Submission::find($user)->sortByDesc('created_at');
$submissions->load('user')->load('votes')->load('suggestions.votes');
return view('submissions.index' , compact('submissions'));
}
This returns with an error
Call to a member function load() on null
when there are no records on the submission.
How to handle if there are no submission on the DB?

Just check if its null first using an if statement:
public function viewSubs()
{
$user = User::find(Input::get('id'));
if ($submissions = Submission::find($user)->sortByDesc('created_at')) {
$submissions->load('user')->load('votes')->load('suggestions.votes');
}
return view('submissions.index' , compact('submissions'));
}
Also, depending on your DB structure I'm pretty sure you can cut out a lot of the code by utilising your models' relationships by doing something like this:
$user = User::find(Input::get('id'))
->with(['submissions' => function($query) {
$query->orderBy('created_at', 'asc');
}, 'submissions.votes', 'submissions.suggestions.votes']);
Then pass the $user variable to the view, or:
$submissions = Submission::with('user', 'votes', 'suggestions.votes')
->where('user_id', Input::get('id'))
->sortByDesc('created_at')
->first();
Not entirely sure the code will work perfectly, but I'm sure you can tweak it. The point is your code can be a lot shorter and still/or more readable by using relationships you've already set up.

Related

Laravel, when using Eloquent to retrieve data paginate and get methods are returning diferent output

I am having a hard time with Laravel. I have a query that returns all the table columns. The problem is that a field "foto" returns as an empty string in the JSON when I use the "get" or "find" methods. Paginate it works as expected.
This query:
$resultado = $query
->where('id_admin', '=', $id_admin)
->with('telasPermissao.itemPermissao')
->paginate(50);
foto comes as:
"foto": "data/image:93483940349"
Now, with this:
$resultado = $query
->where('id_admin', '=', $id_admin)
->with('telasPermissao.itemPermissao')
->find(1);
$resultado = $query
->where('id_admin', '=', $id_admin)
->with('telasPermissao.itemPermissao')
->get(50);
foto comes as:
"foto" : ""
I am returning the data from the controller like this:
return response()->json($resultado, 200);
In my operador model I have the following mutator:
public function getFotoAttribute($value)
{
if ($value != null)
{
return pg_escape_string(fgets($value));
}
return null;
}
Try updating your mutator like this:
public function getFotoAttribute()
{
if ($this->attributes['foto'] != null)
{
return pg_escape_string(fgets($this->attributes['foto']));
}
return null;
}
After fighting 2 hours, I give up. As a workoaround I used this to replace the find method.
$resultado = $query->where('id_admin', '=', $id_admin)->with('telasPermissao.itemPermissao')->where('id', 517 )->paginate(1)
If someone knows what happened please post an answer.

Laravel SQL with where not in example and gettype with dynamic value

There is one function for getting all the data from table with one where clause and one with not wherein clause. I am stuck when I am passing data dynamically but when I am hardcoding the data, it is showing me correct data.
Hard-coded Example :
public function getAllTickets($drawId, $existing)
{
$login = [200263129,200263162,200263735,200263752];
$data = $this->select('ticket')
->where('wlf_draws_id', $wlfDrawId)
->whereNotIn('login', $login)
->get();
return $data;
}
Dynamic Example :
public function getAllTickets($drawId, $existing)
{
$login = [$existing];
$data = $this->select('ticket')
->where('wlf_draws_id', $wlfDrawId)
->whereNotIn('login', $login)
->get();
return $data;
}
In variable $existing I am same data as 200263129,200263162,200263735,200263752
But result is varying for both data and hard-coded example is showing me correct result.
Please use this it may help you:
public function getAllTickets($drawId, $existing)
{
$login = explode(',',$existing);
$data = $this->select('ticket')
->where('wlf_draws_id', $wlfDrawId)
->whereNotIn('login', $login)
->get();
return $data;
}

Laravel detect if there is a new item in an array

I want to implement a system in my project that "alerts" users when there is a new comment on one of their posts.
I currently query all comments on the posts from the logged in user and put everything in an array and send it to my view.
Now my goal is to make an alert icon or something when there is a new item in this array. It doesn't have to be live with ajax just on page load is already good :)
So I've made a function in my UsersController where I get the comments here's my code
public function getProfileNotifications()
{
$uid = Auth::user()->id;
$projects = User::find($uid)->projects;
//comments
if (!empty($projects)) {
foreach ($projects as $project) {
$comments_collection[] = $project->comments;
}
}
if (!empty($comments_collection)) {
$comments = array_collapse($comments_collection);
foreach($comments as $com)
{
if ($com->from_user != Auth::user()->id) {
$ofdate = $com->created_at;
$commentdate = date("d M", strtotime($ofdate));
$comarr[] = array(
'date' => $ofdate,
$commentdate,User::find($com->from_user)->name,
User::find($com->from_user)->email,
Project::find($com->on_projects)->title,
$com->on_projects,
$com->body,
Project::find($com->on_projects)->file_name,
User::find($com->from_user)->file_name
);
}
}
} else {
$comarr = "";
}
}
Is there a way I can check on page load if there are new items in the array? Like keep a count and then do a new count and subtract the previous count from the new one?
Is this even a good way to apprach this?
Many thanks in advance! Any help is appreciated.
EDIT
so I added a field unread to my table and I try to count the number of unreads in my comments array like this:
$uid = Auth::user()->id;
$projects = User::find($uid)->projects;
//comments
if (!empty($projects)) {
foreach ($projects as $project) {
$comments_collection[] = $project->comments;
}
}
$unreads = $comments_collection->where('unread', 1);
dd($unreads->count());
But i get this error:
Call to a member function where() on array
Anyone any idea how I can fix this?
The "standard" way of doing this is to track whether the comment owner has "read" the comment. You can do that fairly easily by adding a "unread" (or something equivalent) flag.
When you build your models, you should define all their relationships so that stuff like this becomes relatively easy.
If you do not have relationships, you need to define something like the following:
In User
public function projects()
{
return $this->hasMany('App\Models\Project');
}
In Project
public function comments()
{
return $this->hasMany('App\Models\Comment');
}
Once you hav ethose relationshipt, you can do the following. Add filtering as you see fit.
$count = $user->projects()
->comments()
->where('unread', true)
->count();
This is then the number you display to the user. When they perform an action you think means they've acknowledged the comment, you dispatch an asynchronous request to mark the comment as read. A REST-ish way to do this might look something like the following:
Javascript, using JQuery:
jQuery.ajax( '/users/{userId}/projects/{projectId}/comments/{commentId}', {
method: 'patch'
dataType: 'json',
data: {
'unread': false
}
})
PHP, in patch method:
$comment = Comment::find($commentId);
$comment->update($patchData);
Keep in mind you can use Laravel's RESTful Resource Controllers to provide this behavior.
try this
$unreads = $project->comments()->where('unread', 1);
dd($unreads->count());
EDIT
My be Has Many Through relation will fit your needs
User.php
public function comments()
{
return $this->hasManyTrough('App\Project', 'App\Comment');
}
Project.php
public function comments()
{
return $this->hasMany('App\Comment');
}
then you can access comments from user directly
$user->comments()->where('unread', 1)->count();
or I recommend you define hasUnreadComments method in User
public function hasUnreadComments()
{
$return (bool) $this->comments()->where('unread', 1)->count();
}
P.S.
$uid = Auth::user()->id;
$projects = User::find($uid)->projects;
this code is horrible, this way much better
$projects = Auth::user()->projects;

Create like/unlike functionality with Laravel

I have a list of properties for a real estate application and im trying to implement a like/unlike functionality based on each property detail. The idea is to add a like or remove it matching the current property and user. This is my code so far, but it only remove likes so it doesnt work as expected. If anyone can suggest for a better approach ill be appreciated.
//Controller
public function storeLike($id)
{
$like = Like::firstOrNew(array('property_id' => $id));
$user = Auth::id();
try{
$liked = Like::get_like_user($id);
}catch(Exception $ex){
$liked = null;
}
if($liked){
$liked->total_likes -= 1;
$liked->status = false;
$liked->save();
}else{
$like->user_id = $user;
$like->total_likes += 1;
$like->status = true;
$like->save();
}
return Redirect::to('/detalle/propiedad/' . $id);
}
// Model
public static function get_like_user($id)
{
return static::with('property', 'user')->where('property_id', $id)
->where('user_id', Auth::id())->first();
}
// Route
Route::get('store/like/{id}', array('as' => 'store.like', 'uses' => 'LikeController#storeLike'));
#Andrés Da Viá Looks like you are returning object from model. In case there is no data in database, it will still return an object - so far my guessing. Can you do something like below in the if($liked){ code?
Try this instead:
if(isset($liked -> user_id)){
Also try to print $liked variable after try and catch blocks. Use var_dump.
If this still does not work for you then let me know. I will try to create code based on your question.
Fix it by adding a where clause in my model to make the status equal to True ->where('status', 1)->first();

Getting the value of a row in CodeIgniter

I am trying to get the value of a row in the database but not working out that well. I not sure if can work like this.
I am just trying to get the value but also make sure it from the group config and the key.
Model
function getTitle() {
return $this->db->get('setting', array(
->where('group' => 'config'),
->where('key' => 'config_meta_title'),
->where('value'=> ) // Want to be able to return any thing in the value
))->row();
}
In the controller I would do this:
function index() {
$data['title'] = $this->document->getTitle();
$this->load->view('sample', $data);
}
First, you have this line set to this:
$data['title'] $this->document->getTitle();
That should be an = assignment for $this->document->getTitle(); like this:
$data['title'] = $this->document->getTitle();
But then in your function you should actually return the setting value from your query with row()->setting:
function getTitle() {
return $this->db->get('setting', array(
->where('group' => 'config'),
->where('key' => 'config_meta_title'),
->where('value'=> ) // Should return this row information but can not.
))->row()->setting;
}
But that said, I am unclear about this:
->where('value'=> ) // Should return this row information but can not.
A WHERE condition is not a SELECT. It is a condition connected to a SELECT that allows you to SELECT certain values WHERE a criteria is met. So that should be set to something, but not really sure what since your code doesn’t provide much details.
Found Solution Working Now. For Getting Single Item From Database In Codeigniter
Loading In Library
function getTitle($value) {
$this->CI->db->select($value);
$this->CI->db->where("group","config");
$this->CI->db->where("key","config_meta_title");
$query = $this->CI->db->get('setting');
return $query->row()->$value;
}
Or Loading In Model
function getTitle($value) {
$this->db->select($value);
$this->db->where("group","config");
$this->db->where("key","config_meta_title");
$query = $this->db->get('setting');
return $query->row()->$value;
}

Categories