PHP code example of cuytamvan / base-pattern-laravel
1. Go to this page and download the library: Download cuytamvan/base-pattern-laravel library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
cuytamvan / base-pattern-laravel example snippets
$app->configure('cuypattern');
$app->alias('cache', \Illuminate\Cache\CacheManager::class); // if you don't have this already
$app->provider(Cuytamvan\BasePattern\BasePatternServiceProvider::class);
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Repositories\ModuleNameRepository;
use Exception;
class ModuleNameController extends Controller {
protected $repository;
public function __construct(ModuleNameRepository $repository) {
$this->repository = $repository;
}
}
public function index(Request $request) {
$params = $request->query();
$this->repository->setPayload($params);
/**
* automaticly detect request _limit, default for request _limit is 10
* if _limit >= 1, it will be paginate
* if _limit less than 1, it will show all data
*/
$query = $this->repository->query();
$data = $query->getData();
return view('user.index', compact('data'));
}
/**
* if you use $data for api, i suggest to use collection and resource
* you can read documentation https://laravel.com/docs/9.x/eloquent-resources
*/
public function index(Request $request)
{
try {
$params = $request->query();
$payload = $this->repository->setPayload($params);
$data = $this->repository->query()->getData();
$res = $payload['withPagination'] ?
new UserCollection($data) :
UserResource::collection($data);
return response()->json([
'message' => 'success',
'data' => $res,
]);
} catch (Exception $e) {
return response()->json([
'message' => $e->getMessage(),
'data' => null,
], 500);
}
}
// get from fillable
public function columns() {
$arr = $this->fillable;
// additional columns
$arr[] = 'created_at';
$arr[] = 'updated_at';
return $arr;
}
// or manualy
public function columns() {
return [
'name',
'email',
'created_at',
'updated_at',
];
}
public function relations()
{
return [
'user' => (new User())->columns(),
// or
'user' => [
'name',
'email',
],
];
}
// relation
public function user()
{
return $this->belongsTo(User::class);
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.