iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 12
1
Software Development

30天完成家庭任務平台系列 第 12

30天完成家庭任務平台:第十二天

  • 分享至 

  • xImage
  •  

家庭任務平台的Model大概介紹過後,就換成Controller的部份,之後分別介紹Controller程式碼與邏輯:
分別有ProjectController/TaskController/ProjectInvitationController/ProfileController。

  • ProjectController
class ProjectController extends Controller
{
    public function index()
    {
        
        $projects = Auth::user()->getProjects();
        return view('projects.index', ['projects' => $projects]);
    }

    public function show(Project $project)
    {
        $this->authorize('view', $project);
        $activities = $this->getActivities($project);
        return view('projects.show', [
            'project' => $project,
            'activities' => $activities
        ]);
    }

    public function create()
    {
        return view('projects.create');
    }

    public function store(Request $request)
    {
        //validate
        $validatedData = $this->validateRequest();

        //persisit
        $project = Auth::user()->projects()->save(new Project($validatedData));
        //redirect
        return redirect(route('project.show', compact('project')));
    }
    public function edit(Project $project)
    {
        return view('projects.edit', compact("project"));
    }
    public function update(Project $project)
    {
        $this->authorize('update', $project);
        $validatedData = $this->validateRequest();
        $project->update($validatedData);
        return redirect(route('project.show', compact('project')));
    }
    public function destory(Project $project)
    {
        $this->authorize('delete', $project);
        $project->delete();
        return redirect(route('project.index'));
    }
    protected function validateRequest()
    {
        return   request()->validate([
            'title' => 'sometimes|required',
            'description' => 'sometimes|required',
            'note' => 'nullable|max:1000'
        ]);
    }

    protected function getActivities(Project $project)
    {
        $taskActivityIds = $project->tasks->pluck('id');
        $totalActivities = DB::table('activities')
            ->where(function ($query) use ($project) {
                $query->where('recordable_type', '=', 'App\Project')
                    ->where('recordable_id', '=', $project->id);
            })
            ->orWhere(function ($query) use ($taskActivityIds) {
                $query->where('recordable_type', '=', 'App\Task')
                    ->whereIn('recordable_id', $taskActivityIds);
            })->get();

        $activities = Activity::whereIn('id', $totalActivities->pluck('id'))->orderBy('created_at', 'desc')->limit(8)->get();
        return $activities;
    }
}

上一篇
30天完成家庭任務平台:第十一天
下一篇
30天完成家庭任務平台:第十三天
系列文
30天完成家庭任務平台30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言