phplaraveleloquentlaravel-10soft-delete

Laravel History page and Soft Delete


i want to make the project data saved in history page after a project finished and also for the soft delete function in the same page. but it's only shows the data with status done

class HistoryController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $projects = Project::where('status', 'Done') //select data with done status only
                    ->orWhereNotNull('deleted_at') // shows soft deleted data
                    ->orderBy('id', 'desc')
                    ->paginate(5);

        // Pass the merged projects to your view
        return view('history', compact('projects'));
    }
}

i tried to have 2 variable then merges it. it does work but it makes the pagination doesn't work. i also try this but it result the same

public function index()
    {
        $projects = Project::withTrashed()
                            ->where('status', 'Done')
                            ->orderBy('id', 'desc')
                            ->paginate(5);

        // Pass the merged projects to your view
        return view('history', compact('projects'));
    }

is it possible to do this?


Solution

  • Your code doesn't work because it tries to find projects where status = "Done". If there are any projects without this status but with a non-null "deleted_at" value, they won't be caught because of the first "WHERE" clause.

    Try conditional query grouping, it will select both projects where "status" is "Done" and where "deleted_at" is null.

    $projects = Project::withTrashed()
                       ->where(function ($query) {
                           $query->where('status', 'Done');
                           $query->orWhereNotNull('deleted_at');
                       })
                       ->orderBy('id', 'desc')
                       ->paginate(5);