Skip to content

Instantly share code, notes, and snippets.

@jsdecena
Created March 14, 2018 01:57
Show Gist options
  • Save jsdecena/2330f17e95aec2ff410f49678c6ee95d to your computer and use it in GitHub Desktop.
Save jsdecena/2330f17e95aec2ff410f49678c6ee95d to your computer and use it in GitHub Desktop.
<?php
// your code
public function index()
{
try {
$cards = Card::where('user_id',Auth::user()->id)->orderBy('created_at','desc')->get();
return $cards;
} catch(Exception $e){
return response()->json(['error' => $e->getMessage()], 500);
}
}
// Create a repository class in app folder (better if you have another folder),
// and call it: CreditCardRepository.php
class CreditCardRepository {
protected $model;
// inject here your Card Model
public __construct(Card $card) {
$this->model = $model;
}
/**
* Find if the user has a credit card
*/
public function findCreditCardIfExists(User $user) : bool
{
//your User Model should have one to many relationship with Card Model
return $user->card()->count();
}
}
// In your controller
// refactor code
public function index()
{
$creditCardRepository = new CreditCardRepository(new Card);
$creditCard = $creditCardRepository->findCreditCardIfExists(auth()->user());
if(!$creditCard) {
return redirect()->url('/');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment