I have an API with Laravel and I have decided to use relations between tables to make it work better, so I have related them using these functions in all migrations:
// 2020_05_26_185555_create_customers_table.php:27
$table->foreign('user_id')->references('id')->on('users');
And then I've implemented functions like the following (which get the records it's related to):
// app\User.php:80
public function customers()
{
return $this->hasMany(Customer::class);
}
The problem is that from the Customers controller, I do not know how to use the function shown above to list all the clients of that user , that is, replace the following code:
// app\Http\Controllers\Customer\CustomerController.php:17
public function index()
{
$user_id = Auth::id();
$customers = Customer::where('user_id', $user_id)->get();
return $this->showAll($customers, 200, $filters);
}
For something like the following (Just an example, it doesn't work, but it's the idea of what I mean):
// app\Http\Controllers\Customer\CustomerController.php:17
public function index()
{
$customers = User::customers(); // Ejemplo
return $this->showAll($customers, 200, $filters);
}
Basically my problem is that I don't know how to use relations to get, for example, a user's clients , without using the conditions (which I currently do), because then relations don't make sense.
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire