php - Tidy up controller in Laravel 5.1 -
i'm setting laravel 5.1 project , i've been making progress have run in i'm struggling figure out.
basically, have been creating objects insert in database in controller methods. hasn't been bad because they're one-liners.
however, i've run in more complex db entry , controller has become little muddied. let me show you:
/** * store new ticket specified project. * * @param int $id * @param ticketsrequest $request * @return response */ public function store_ticket($id, ticketsrequest $request) { $user_id = auth::user()->id; $project_id = $id; $project_tickets = ticket::whereprojectid($id); $project_ticket_id = $project_tickets->count() + 1; $ticket = new ticket; $ticket->user_id = $user_id; $ticket->project_id = $project_id; $ticket->project_ticket_id = $project_ticket_id; $ticket->title = $request->title; $ticket->save(); $ticket_update = new ticketupdate; $ticket_update->user_id = $user_id; $ticket_update->ticket_id = $ticket->id; $ticket_update->status_id = $request->status_id; $ticket_update->priority_id = $request->priority_id; $ticket_update->assigned_to = $request->assigned_to; $ticket_update->description = $request->description; $ticket_update->save(); return redirect('/projects'); }
so can see, i'm creating ticket gets saved database, creating ticket update saved database.
what i'd extract code in 'something' clean controller.
on travels, i've found maybe creating repositories might way forward. otherwise thinking kind of service i'm not convinced that way forward.
i have subscription laracasts , found following video it's little outdated , sure if still 'right' way in laravel 5.1 (i've found things seem have natural home in 5.1 compared older versions).
https://laracasts.com/lessons/repositories-simplified
any suggestions/links etc great. thanks!
if instantiate objects often/always using same set of attributes, extract code models constructors, e.g:
//in model public function __construct($user_id, $ticket_id, $request) { $this->user_id = $user_id; $this->ticket_id = $ticket_id; $this->status_id = $request->status_id; $this->priority_id = $request->priority_id; $this->assigned_to = $request->assigned_to; $this->description = $request->description; } // in controller $ticket_update = new ticketupdate($user_id, $ticket->id, $request); $ticket_update->save();
Comments
Post a Comment