LARAVEL: How to fetch id dynamically in a query builder? - php

I want to join multiple tables in laravel with query builder. My problem is that my code only works if I specify the id myself that I want like this:
$datauser = DB::table('users')
->join('activitates','users.id','=','activitates.user_id')
->join('taga_cars','taga_cars.id','=','activitates.tagacar_id')
->join('clients','users.id','=','clients.user_id')
->where('users.id','=','1')
->select('users.*','activitates.*','taga_cars.model','taga_cars.id','clients.name')
->get();
return response()->json($datauser);
But I would want something like this(which I just can't seem to figure out)
public function showuser($id)
{
$userid = User::findOrFail($id);
$datauser = DB::table('users')
->join('activitates','users.id','=','activitates.user_id')
->join('taga_cars','taga_cars.id','=','activitates.tagacar_id')
->join('clients','users.id','=','clients.user_id')
->where('users.id','=',$userid)
->select('users.*','activitates.*','taga_cars.model','taga_cars.id','clients.name')
->get();
return response()->json($datauser);
}
Am I making a syntax mistake? When I check the page for my json response in second page it just returns empty brackets, but when I specify the id it fetches me the right data

The findOrFail method will return the entire user model, with all its properties, since you already have the user id. You dont need to get the entire user model for that, you could just use the $id you receveid as a parameter like this:
$datauser = DB::table('users')
->join('activitates','users.id','=','activitates.user_id')
->join('taga_cars','taga_cars.id','=','activitates.tagacar_id')
->join('clients','users.id','=','clients.user_id')
->where('users.id','=',$id)
->select('users.*','activitates.*','taga_cars.model','taga_cars.id','clients.name')
->get();
return response()->json($datauser);

public function showuser($id)
{
$getUserByID = User::findOrFail($id); //not used
$userData = DB::table('users')
->join('activitates','users.id','=','activitates.user_id')
->join('taga_cars','taga_cars.id','=','activitates.tagacar_id')
->join('clients','users.id','=','clients.user_id')
->where('users.id','=',$id)
->select('users.*','activitates.*','taga_cars.model','taga_cars.id','clients.name')
->get();
return response()->json($userData);
}
But the best way is to have relations set on models
public function showuser($id)
{
$userData = User::where('id', $id)->with(['activitates','taga_cars','clients'])->first();
return response()->json($userData);
}

Related

Laravel 5.2 : Fetch records against logged in user id

I am fetching records in controller :
$tasks = Task::where('user_id', '=', Auth::user()->id);
return view('todo',compact('tasks'));
But it returns null.
And Auth::user()->id returns 2 Which is Okay.
Am i missing something ?
You need to actually retrieve the record. What you have is an instance of \Illuminate\Database\Eloquent\Builder, but not the actual record(s) associated with the query.
To tell Eloquent to fetch the data, you need to use either get().
Like:
$tasks = Task::where('user_id', '=', Auth::user()->id)->get();
As a side note, you can simplify your query to be:
$tasks = Task::where('user_id', Auth::user()->id)->get();
Furthermore, on your User model, you could do this:
public function tasks()
{
return $this->hasMany(Task::class) // make sure you use the full namespace here or use at the top of User.php
}
And then you can simply do:
$tasks = auth()->user()->tasks;
This is a Relationship in Eloquent as explained in the docs.

Laravel Model get all where $id = Auth::user()->id

How to List all rows from a DB where $id matches the logged user id.
I'm using default Auth from Laravel.
At the moment i can list them all with this method in my controller:
public function index(){
$invoices = Invoice::all();
return view('index', compact('invoices'));
}
But i just want the ones that are from this user which is logged in:
Something like
$invoices = Invoice::where('id', '=', Auth::user()->id);
Your code Seems almost right. I would do:
$invoice = Invoice::where('id', Auth::user()->id)->get();
So basically use the get in order to fetch a collection. And maybe I would separate the user id in a varaible in case that you change the authentication in the future ;)
When using any condition then of course you must need to add the get() method. Otherwise, you can't show your data.
$invoices = Invoice::where('id', '=', Auth::user()->id)->get();
This means that you want to see data on which user is logged in now

orderBy on whereHas query in Laravel 4.2

how can I sort the return data from a query using whereHas? In my query i have to get the users data which id exist on interest table but i need to sort it using the datetime column from interest. But, the return query do not sort the data at all.
Here's my code snippets in case it would help you understand my problem.
Model (name: User)
//***relationship***//
public function interest(){
return $this->belongsTo('Interest','id','interest_by');
}
Controller
$userInterested = User::whereHas('interest',function($q) use ($id) {
return $q->where('interest_on', $id)
->orderBy('datetime');
});
$userQuery = $userInterested->get();
return $userQuery;
remove return from where has and try this.like
$userInterested = User::whereHas('interest',function($q) use ($id) {
$q->where('interest_on', $id)
->orderBy('datetime');
})->get();
return $userInterested;
$userInterested = User::whereHas('interest',function($q) use ($id) {
return $q->where('interest_on', $id);
})->orderBy('datetime');
$userQuery = $userInterested->get();
return $userQuery;

Laravel Join Returning odd values

Just come across a bug on my Join query.
I am echoing out data in a foreach, and showing the username. On other pages it works fine and each username matches the username from the ID in the row. However, in the example below the username return is ALWAYS the name of the logged in user.
Hope the below makes some more sense. Thanks.
The query is:
$query = DB::table('blogs')
->join('followers', 'blogs.id', '=', 'followers.blogid')
->where('followers.userid', Auth::user()->id)
->where('frontpage', '1')
->latest('lastupdated');
This is called via:
Route::get('following', array('before' => 'auth', function()
{
$slug = Route::getCurrentRoute()->uri();
$builds = Blog::findBuilds($slug);
return View::make('pages/home', compact('builds'), array('pageTitle' => 'Builds You Are Following'));
}));
And then on the pages/home I am showing the data like so:
foreach ($builds as $build)
{
$usernameOfOwner = User::usernameFromID($build->userid);
}
And then... the function for getting the username from ID is:
public static function usernameFromID($id) {
$user = DB::table('users')->where('id', $id)->first();
return $user->username;
}
Everywhere else on my website when I run a query similiar to the top one but not a join so e.g.:
$query = static::where('frontpage', '1')->latest('lastupdated');
It works fine, so my only guess is that its down to the Join as thats the only different part of the code.
The problem is that you have multiple columns named userid. followers.userid and blogs.userid. Now in this case, unfortunately followers.userid gets returned when you use $build->userid
You can change that by only selecting the columns you want in your result.
$userid = Auth::user()->id;
$query = DB::table('blogs')
->join('followers', function($q) use ($userid){
$q->on('blogs.id', '=', 'followers.blogid');
$q->where('followers.userid', '=', $userid);
})
->select('blogs.userid', 'other-column')
->where('frontpage', '1')
->latest('lastupdated');
By the way: * works too, so you can do select('blogs.*') if you want

How to update a column of a field in Laravel 4?

I'm trying to call an AJAX request on a route that calls this function updateImpression() in UserController, and this function tries to increment the counter column named "impressions_cpunt" in my 'users' table stored in MySQL. I tried using Eloquent to update the column of one particular user only.
public function updateImpression()
{
$username = Input::get('username');
$user = User::where('username', '=', $username)->first();
$impressions_count = $user->impressions_count + 1;
// save() method failed to update my database.
// $user->impressions_count = $impressions_count;
// $user->save();
//update() method does not return anything. Any syntax error here?
//$user->update(array('impressions_count' => $impressions_count));
DB::table('users')
->where('username', $username)
->update(array('impressions_count' => $impressions_count));
$user = User::where('username', '=', $username)->first();
return $user->impressions_count;
}
I think save() function should be work at the first place but my database doesn't get updated and return the original count, and the update() function doesn't even returning any value from the function. This only works when I use DB but I think Eloquent should be better to use since this is Laravel. Is there anything I missed or something wrong with the syntax? I know increments() data type should be used but please allow me to solve this before I change anything.
Update:
This is my database queries shown in Debugbar when I use save() method:
select * from 'users' where 'username'= <test> limit 1
select count(*) as aggregate from 'users' where 'username'= <test>
select count(*) as aggregate from 'users' where 'email'= <test#example.org>
User object (which supposed to be Eloquent child) like any other entity will store its state after changes if your save() call was successful. Therefore, there is no need to update the record explicitly. In your case I would go with something like this:
public function updateImpression()
{
$username = Input::get('username');
$user = User::where('username', '=', $username)->first();
$user->impressions_count += 1;
$user->save();
return $user->impressions_count;
}
In Laravel 5.2 you can update specific column by using the following Eloquent builder:
public function update(Request $request, $id) {
$user = User::where('id', $id)->update(['name', $request->name]);
return redirect()->back()->with('status', trans('User has been updated successfully.'))
}

Categories