Support the ongoing development of Laravel.io →
posted 9 years ago
Forms
Last updated 2 years ago.
0

Hello @ethan-mattieu,

If I were to work on this code, I will first start by moving all the database manipulation logic to a Model class. I will start by creating the following classes:

  • Employee
  • JobTitle
  • DataLogic - This will have methods for manipulating most of my entities (Employee and JobTitle).

I will create a relationship between the Employee and JobTitle class as a One to One relationship (Assuming your domain knowledge acknowledges that). This way when I fetch an Employee by ID, I get properties of the employee including Job Title (Thanks to Eloquent).

My DataLogic class will have methods like :

class DataLogic 
{
   public function fetchEmployees($id = null)
   {
        if (isset($id)) {
           return Employee::find($id);
        } else {
           return Employee::all();
        }
   }


  public function fetchAllJobTitles()
  {
     return JobTitle::all();
   }
}

My index and edit functions will likely look like this:


public function index()
{
  $employees = DataLogic::fetchEmployees(); //So many alternatives to instantiating DataLogic class. Its up to you. 
  return View::make("user.index", array("userlist", $employees));
}

public function edit($id)
{
    $employee = DataLogic::fetchEmployees($id);
    //Do check for invalid/null employee
    $jobTitles   = DataLogic::fetchAllJobTitles();

    return View::make("user.edit", array("jobTitles" => $jobTitles, "user" => $employee));
}

In your view, you can now do something like $user->jobTitle, $user->id, $jobTitles->id, $jobTitles->title etc.

Here is the link to the Eloquent Documentation http://laravel.com/docs/eloquent

Hope that helped.

Cheers.

Last updated 2 years ago.
0

Thanks @ndy40 for the suggestion... though I want to know more how I can join tables with your suggestion? As you can see I'm joining multiple tables & display it on the view.

Regards

Last updated 2 years ago.
0

@ethan-mattieu,

if you defined the relationships between your classes properly, Eloquent will perform the Joins for you. E.g if I defined my Employees to have a one to one relationship with Job titles and I want to fetch all employees with their Job titles, then my Eloquent query will look like this.

return Employees::with("jobTitle")->get();

Eloquent will take care of generating the joins for you. Have a look at the Eloquent documentation. Without the Eloquent approach you will have to add your joins manually or dynamically generate your query.

Other useful resources are:

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.