public function get_user_documents()
{
$userId = Auth::id();
$user_documents = UserDocument::where('user_id', $userId)
->orWhereHas('share_documents', function ($query) use ($userId) {
$query->where('users.id', $userId);
})
->with(['share_documents' => function ($query) use ($userId) {
$query->where('users.id', $userId);
}])
->latest()
->get();
// $user_documents = $user_documents->map(function ($document) use ($userId) {
// $status = $document->user_id == $userId ? 'owned' : 'shared';
// $document->status = $status;
// return $document;
// });
return response()->json($user_documents);
}
Can we ordering on both Base table and Piviot table
i want to get latest record on top it is owned document or shared document
2
Answers
Yes, you can order the results from both the base table and the pivot table (in this case, "share_documents") in your query. You can achieve this by using the orderBy method to specify the ordering for both tables. Here’s an updated version of your get_user_documents function:
In the updated code, we use orderByRaw to order the results based on whether the document is owned by the user (1 if true, 0 if false). This effectively places owned documents before shared documents. Then, we use orderBy(‘updated_at’, ‘desc’) to order the documents by their updated_at timestamp in descending order, so you get the latest documents at the top of the results.