I have the following routes in web.php, the first five routes are working perfectly but from contacts to aboutroutes` fail with the following exception:
Illuminate\Contracts\Encryption\DecryptException The payload is invalid.
Route::get('services', 'PageController#services')->name('services');
Route::get('/service/{id}', 'PageController#showService')->name('service');
Route::get('/blogs', 'PageController#showBlogs')->name('blogs');
Route::get('/{blog}', 'PageController#showPost')->name('post.show');
Route::post('/comment/{blog}/store', 'PageController#storeComment')->name('comment.store');
Route::get('/contacts', 'PageController#contacts')->name('contacts');
Route::post('/contact/store', 'PageController#storeContact')->name('contact.store');
Route::get('/courses', 'PageController#showCourses')->name('courses');
Route::get('/{course}', 'PageController#categoryCourses')->name('course.category');
Route::get('coursesdetail', 'PageController#showCoursesDetail')->name('coursesdetail');
Route::get('resource', 'PageController#showResource')->name('resource');
Route::get('about', 'PageController#showAbout')->name('about');
PageController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
use App\About;
use App\Team;
use App\Service;
use App\Post;
use App\Category;
use App\Tag;
use App\Slider;
use App\Contact;
use App\Client;
use App\Comment;
use App\Course;
use App\Coursecategory;
class PageController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$about = About::all();
$teams = Team::all();
$services = Service::all();
$posts = Post::orderBy('created_at', 'desc')->take(3)->get();
$sliders = Slider::all();
$clients = Client::all();
return view('index')->with('about', $about)
->with('teams', $teams)
->with('services', $services)
->with('posts', $posts)
->with('sliders', $sliders)
->with('clients', $clients);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
public function services()
{
$services = Service::all();
return view('service')->with('services', $services);
}
public function showService($id)
{
$id = Crypt::decrypt($id);
$service = Service::find($id);
$services = Service::all();
return view('service')->with('service', $service)->with('services', $services);
}
public function showBlogs()
{
// $posts = Post::orderBy('created_at', 'desc')->take(5)->get();
// $recents = Post::orderBy('created_at', 'desc')->take(5)->get();
$posts = Post::orderBy('created_at', 'desc')->paginate(4);
$recents = Post::orderBy('created_at', 'desc')->take(4)->get();
// $posts = Post::all();
$tags = Tag::all();
$categories = Category::all();
return view('blogs')->with('tags', $tags)
->with('categories', $categories)
->with('posts', $posts)
->with('recents', $recents);
}
public function showPost(Request $request, $id)
{
$id = Crypt::decrypt($id);
$posts = [Post::find($id)];
$recents = Post::orderBy('created_at', 'desc')->take(4)->get();
$tags = Tag::all();
$categories = Category::all();
// $next_id = Post::where('id', '>', $id)->min('id');
// $prev_id = Post::where('id', '<', $id)->max('id');
// dd($posts);
return view('post')->with('posts', $posts)
->with('recents', $recents)
->with('tags', $tags)
->with('categories', $categories);
// ->with('next', Post::find($next_id))
// ->with('prev', Post::find($prev_id));
}
public function storeComment(Request $request, $post)
{
request()->validate([
'name' => 'required',
'email' => 'required|email',
'phone' => 'required',
]);
$contact = Comment::create([
'post_id' => $post,
'user_id' => Auth::id(),
'name' => $request->name,
'email' => $request->email,
'phone' => $request->phone,
'comment' => $request->comments,
]);
session()->flash('success', 'Comment successfully submitted');
return redirect()->back();
}
public function contacts()
{
return view('contact');
}
public function storeContact(Request $request)
{
request()->validate([
'name' => 'required',
'email' => 'required|email',
'phone' => 'required',
]);
$contact = Contact::create([
'name' => $request->name,
'email' => $request->email,
'phone' => $request->phone,
'comment' => $request->comments,
]);
session()->flash('success', 'Contact information successfully submitted');
return redirect()->route('contact');
}
public function showCourses()
{
$categories = Coursecategory::all();
$courses = Course::orderBy('created_at', 'desc')->paginate(4);
return view('courses')->with('courses', $courses)
->with('categories', $categories);
}
public function categoryCourses($id)
{
$id = Crypt::decrypt($id);
$course = Coursecategory::where('id', $id)->first()->courses;
$categories = Coursecategory::all();
return view('coursewithcategory')->with('course', $course)
->with('categories', $categories);
}
public function showCoursesDetail()
{
return view('coursesdetail');
}
public function showResource()
{
return view('resource');
}
public function showAbout()
{
$about = About::all();
return view('about')->with('about', $about);
}
}
This should be the order your routes when you use uri as slug.
Route::get('/contacts', 'PageController#contacts')->name('contacts');
Route::post('/contact/store', 'PageController#storeContact')->name('contact.store');
Route::get('/courses', 'PageController#showCourses')->name('courses');
Route::get('coursesdetail', 'PageController#showCoursesDetail')->name('coursesdetail');
Route::get('resource', 'PageController#showResource')->name('resource');
Route::get('about', 'PageController#showAbout')->name('about');
Route::get('/{course}', 'PageController#categoryCourses')->name('course.category');
Related
I try to create restful api using Code Igniter 4 on Apache2. If I open http://<my-ip:port>, it shows welcome message. Then I created Account.php controller to get account list from database.
<?php namespace App\Controllers;
use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\API\ResponseTrait;
use App\Models\AccountModel;
class Account extends ResourceController
{
use ResponseTrait;
public function index()
{
$model = new AccountModel();
$data = $model->findAll();
return $this->respond($data, 200);
}
public function show($id = null)
{
$model = new AccountModel();
$data = $model->getWhere(['account_id' => $id])->getResult();
if($data){
return $this->respond($data);
}else{
return $this->failNotFound('No Data Found with id '.$id);
}
}
}
AccountModel.php
<?php namespace App\Models;
use CodeIgniter\Model;
class AccountModel extends Model
{
protected $table = 'account';
protected $primaryKey = 'id';
protected $allowedFields = ['account_id','name'];
}
I set Cors and Filters.
and this is my routes
<?php
namespace Config;
$routes = Services::routes();
if (file_exists(SYSTEMPATH . 'Config/Routes.php')) {
require SYSTEMPATH . 'Config/Routes.php';
}
$routes->setDefaultNamespace('App\Controllers');
$routes->setDefaultController('Home');
$routes->setDefaultMethod('index');
$routes->setTranslateURIDashes(false);
$routes->set404Override();
$routes->setAutoRoute(true);
//$routes->get('/','Home::index');
$routes->resource('account');
if (file_exists(APPPATH . 'Config/' . ENVIRONMENT . '/Routes.php')) {
require APPPATH . 'Config/' . ENVIRONMENT . '/Routes.php';
}
http://my-ip:port shows welcome message. But if I open http://<my-ip:port/account> using postman I got error
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL was not found on this server.</p>
<hr>
<address>Apache/2.4.46 (Ubuntu) Server at <my-ip> Port 80</address>
</body></html>
and I set Account as a default controller $routes->setDefaultController('Account'); I got list of account if I open http://<my-ip:port>. Do I miss some set up? I want to get account list if I open http://<my-ip:port/account> and others.
Is it works if tried http://<my-ip:port/index.php/account? if yes, you have to config your apache to hide index.php from URL.
visit following link for more infos. => more infos
look at my code best way using restful ctl ci4
first routs
<?php
/*
* Core Auth routes file.
*/
$routes->group('api', ['namespace' => 'Modules\Auth\Controllers'], function ($routes) {
$routes->resource('group', ['filter' => 'authJwt']);
$routes->resource('permission', ['filter' => 'authJwt']);
$routes->resource('groupPermission', ['filter' => 'authJwt']);
$routes->resource('userPermission', ['filter' => 'authJwt']);
$routes->group('auth', function ($routes) {
$routes->post('signin-jwt', 'Auth::signInJwt', ['filter' => 'isSignIn']);
$routes->post('signin', 'Auth::signIn', ['filter' => 'isSignIn']);
$routes->get('signout', 'Auth::signOut', ['filter' => 'authJwt']);
$routes->get('is-signin', 'Auth::isSignIn',['filter' => 'authJwt']);
$routes->post('signup', 'Auth::signUp', ['filter' => 'isSignIn']);
$routes->post('forgot', 'Auth::forgot', ['filter' => 'isSignIn']);
$routes->post('reset-password-email', 'Auth::resetPasswordViaEmail', ['filter' => 'isSignIn']);
$routes->post('reset-password-sms', 'Auth::resetPasswordViaSms', ['filter' => 'isSignIn']);
$routes->post('activate-account-email', 'Auth::activateAccountViaEmail', ['filter' => 'isSignIn']);
$routes->post('send-activate-email', 'Auth::sendActivateCodeViaEmail', ['filter' => 'isSignIn']);
$routes->post('activate-account-sms', 'Auth::activateAccountViaSms', ['filter' => 'isSignIn']);
$routes->post('send-activate-sms', 'Auth::sendActivateCodeViaSms', ['filter' => 'isSignIn']);
});
});
sencond api ctl
<?php
namespace Modules\Shared\Controllers;
/**
* Class BaseController
*
* BaseController provides a convenient place for loading components
* and performing functions that are needed by all your controllers.
* Extend this class in any new controllers:
* class Home extends BaseController
*
* For security be sure to declare any new methods as protected or private.
*
* #package CodeIgniter
*/
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\RESTful\ResourceController;
use Modules\Auth\Config\Services;
use Myth\Auth\AuthTrait;
use Psr\Log\LoggerInterface;
use Modules\Shared\Interfaces\UrlAggregationInterface;
use Modules\Shared\Libraries\UrlAggregation;
class ApiController extends ResourceController
{
use AuthTrait;
protected $format = "";
public object $userObject;
public UrlAggregationInterface $urlAggregation;
/**
* An array of helpers to be loaded automatically upon
* class instantiation. These helpers will be available
* to all other controllers that extend BaseController.
*
* #var array
*/
protected $helpers = [
'cookie',
'url',
'from',
'filesystem',
'text',
'shared'
];
/**
* Constructor.
*
* #param RequestInterface $request
* #param ResponseInterface $response
* #param LoggerInterface $logger
*/
/**
* #var string
* Holds the session instance
*/
protected $session;
public function __construct()
{
$this->userObject = (object)[];
}
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
// Do Not Edit This Line
parent::initController($request, $response, $logger);
$this->urlAggregation = new UrlAggregation($request);
$requestWithUser = Services::requestWithUser();
$this->userObject = $requestWithUser->getUser();
}
}
thrid ctl
<?php namespace Modules\Auth\Controllers;
use Modules\Auth\Config\Services;
use Modules\Auth\Entities\GroupEntity;
use CodeIgniter\HTTP\ResponseInterface;
use Modules\Shared\Controllers\ApiController;
class Group extends ApiController
{
/**
* index function
* #method : GET
*/
public function index()
{
$groupEntity = new GroupEntity();
$this->urlAggregation->dataMap($groupEntity->getDataMap());
$groupService = Services::groupService();
$findAllData = $groupService->index($this->urlAggregation);
return $this->respond([
'data' => $findAllData['data'],
'pager' => $findAllData['pager']
], ResponseInterface::HTTP_OK, lang('Shared.api.receive'));
}
/**
* show function
* #method : GET with params ID
*/
public function show($id = null)
{
$groupService = Services::groupService();
$findOneData = $groupService->show($id);
return $this->respond([
'data' => $findOneData['data'],
'pager' => $findOneData['pager']
], ResponseInterface::HTTP_OK, lang('Shared.api.receive'));
}
public function create()
{
$rules = [
'name' => 'required|min_length[3]|max_length[255]|is_unique[auth_groups.name]',
'description' => 'required|min_length[3]|max_length[255]',
];
if (!$this->validate($rules)) {
return $this->respond([
'error' => $this->validator->getErrors(),
], ResponseInterface::HTTP_NOT_ACCEPTABLE, lang('Shared.api.validation'));
}
$groupEntity = new GroupEntity((array)$this->request->getVar());
$groupService = Services::groupService();
$groupService->create($groupEntity);
return $this->respond([
'data' => ''
], ResponseInterface::HTTP_CREATED, lang('Shared.api.save'));
}
/**
* update function
* #method : PUT or PATCH
*/
public function update($id = null)
{
//get request from Vue Js
//get request from Vue Js
$json = $this->request->getJSON();
if (!isset($id)) {
$id = $json->id;
}
$rules = [
'name' => 'if_exist|required|min_length[3]|max_length[255]',
'description' => 'required|min_length[3]|max_length[255]',
];
if (!$this->validate($rules)) {
return $this->respond([
'error' => $this->validator->getErrors(),
], ResponseInterface::HTTP_NOT_ACCEPTABLE, lang('Shared.api.validation'));
}
$groupEntity = new GroupEntity((array)$this->request->getVar());
$groupService = Services::groupService();
$groupService->update($id, $groupEntity);
return $this->respond([
], ResponseInterface::HTTP_OK, lang('Shared.api.update'));
}
/**
* edit function
* #method : DELETE with params ID
*/
public function delete($id = null)
{
$groupService = Services::groupService();
$groupService->delete($id);
return $this->respond([
], ResponseInterface::HTTP_OK, lang('Shared.api.remove'));
}
}
entitiy
forth service
<?php namespace Modules\Auth\Config;
use CodeIgniter\HTTP\UserAgent;
use Config\App;
use Config\Services as AppServices;
use Config\Services as BaseService;
use Modules\Auth\Libraries\RequestWithUser;
use Modules\Auth\Services\AuthService;
use Modules\Auth\Services\GroupsPermissionService;
use Modules\Auth\Services\PermissionService;
use Modules\Auth\Services\RoleRouteService;
use Modules\Auth\Services\GroupService;
use Modules\Auth\Services\UsersPermissionService;
class Services extends BaseService
{
//--------------------------------------------------------------------
/**
* The Request class models an HTTP request.
*
* #param App|null $config
* #param boolean $getShared
*
* #return RequestWithUser
*/
public static function requestWithUser(App $config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('requestWithUser', $config);
}
$config = $config ?? config('App');;
return new RequestWithUser(
$config,
AppServices::uri(),
'php://input',
new UserAgent()
);
}
//--------------------------------------------------------------------
public static function roleRoute($getShared = true)
{
if ($getShared) {
return static::getSharedInstance('roleRoute');
}
return new RoleRouteService();
}
//--------------------------------------------------------------------
public static function authService($getShared = false)
{
if (!$getShared) {
return new AuthService();
}
return static::getSharedInstance('authService');
}
//--------------------------------------------------------------------
public static function groupService($getShared = false)
{
if (!$getShared) {
return new GroupService();
}
return static::getSharedInstance('groupService');
}
//--------------------------------------------------------------------
public static function permissionService($getShared = false)
{
if (!$getShared) {
return new PermissionService();
}
return static::getSharedInstance('permissionService');
}
//--------------------------------------------------------------------
public static function groupsPermissionService($getShared = false)
{
if (!$getShared) {
return new GroupsPermissionService();
}
return static::getSharedInstance('groupsPermissionService');
}
//--------------------------------------------------------------------
public static function userPermissionService($getShared = false)
{
if (!$getShared) {
return new UsersPermissionService();
}
return static::getSharedInstance('usersPermissionService');
}
//--------------------------------------------------------------------
}
<?php namespace Modules\Auth\Entities;
use \CodeIgniter\Entity;
use CodeIgniter\I18n\Time;
class GroupEntity extends Entity
{
protected $id;
protected $name;
protected $description;
//check type of data
// protected $casts = ['
// is_flag' => 'boolean'];
protected $attributes = [
'id' => null,
'name' => null,
'description' => null,
];
protected $datamap = [
];
protected $dates = [];
protected $casts = [];
protected $permissions = [];
protected $roles = [];
}
model
<?php namespace Myth\Auth\Authorization;
use CodeIgniter\Model;
use Modules\Auth\Entities\GroupEntity;
use Modules\Shared\Models\Aggregation;
class GroupModel extends Aggregation
{
protected $table = 'auth_groups';
protected $primaryKey = 'id';
protected $returnType = GroupEntity::class;
protected $allowedFields = [
'name', 'description'
];
protected $useTimestamps = false;
protected $validationRules = [
'name' => 'required|max_length[255]|is_unique[auth_groups.name,name,{name}]',
'description' => 'max_length[255]',
];
protected $validationMessages = [];
protected $skipValidation = false;
//--------------------------------------------------------------------
// Users
//--------------------------------------------------------------------
/**
* Adds a single user to a single group.
*
* #param int $userId
* #param int $groupId
*
* #return bool
*/
public function addUserToGroup(int $userId, int $groupId)
{
cache()->delete("{$groupId}_users");
cache()->delete("{$userId}_groups");
cache()->delete("{$userId}_permissions");
$data = [
'user_id' => (int) $userId,
'group_id' => (int) $groupId
];
return (bool) $this->db->table('auth_groups_users')->insert($data);
}
/**
* Removes a single user from a single group.
*
* #param int $userId
* #param int|string $groupId
*
* #return bool
*/
public function removeUserFromGroup(int $userId, $groupId)
{
cache()->delete("{$groupId}_users");
cache()->delete("{$userId}_groups");
cache()->delete("{$userId}_permissions");
return $this->db->table('auth_groups_users')
->where([
'user_id' => $userId,
'group_id' => (int) $groupId
])->delete();
}
/**
* Removes a single user from all groups.
*
* #param int $userId
*
* #return bool
*/
public function removeUserFromAllGroups(int $userId)
{
cache()->delete("{$userId}_groups");
cache()->delete("{$userId}_permissions");
return $this->db->table('auth_groups_users')
->where('user_id', (int)$userId)
->delete();
}
/**
* Returns an array of all groups that a user is a member of.
*
* #param int $userId
*
* #return array
*/
public function getGroupsForUser(int $userId)
{
if (null === $found = cache("{$userId}_groups"))
{
$found = $this->builder()
->select('auth_groups_users.*, auth_groups.name, auth_groups.description')
->join('auth_groups_users', 'auth_groups_users.group_id = auth_groups.id', 'left')
->where('user_id', $userId)
->get()->getResultArray();
cache()->save("{$userId}_groups", $found, 300);
}
return $found;
}
/**
* Returns an array of all users that are members of a group.
*
* #param int $groupId
*
* #return array
*/
public function getUsersForGroup(int $groupId)
{
if (null === $found = cache("{$groupId}_users"))
{
$found = $this->builder()
->select('auth_groups_users.*, users.*')
->join('auth_groups_users', 'auth_groups_users.group_id = auth_groups.id', 'left')
->join('users', 'auth_groups_users.user_id = users.id', 'left')
->where('auth_groups.id', $groupId)
->get()->getResultArray();
cache()->save("{$groupId}_users", $found, 300);
}
return $found;
}
//--------------------------------------------------------------------
// Permissions
//--------------------------------------------------------------------
/**
* Gets all permissions for a group in a way that can be
* easily used to check against:
*
* [
* id => name,
* id => name
* ]
*
* #param int $groupId
*
* #return array
*/
public function getPermissionsForGroup(int $groupId): array
{
$permissionModel = model(PermissionModel::class);
$fromGroup = $permissionModel
->select('auth_permissions.*')
->join('auth_groups_permissions', 'auth_groups_permissions.permission_id = auth_permissions.id', 'inner')
->where('group_id', $groupId)
->findAll();
$found = [];
foreach ($fromGroup as $permission)
{
$found[$permission['id']] = $permission;
}
return $found;
}
/**
* Add a single permission to a single group, by IDs.
*
* #param int $permissionId
* #param int $groupId
*
* #return mixed
*/
public function addPermissionToGroup(int $permissionId, int $groupId)
{
$data = [
'permission_id' => (int)$permissionId,
'group_id' => (int)$groupId
];
return $this->db->table('auth_groups_permissions')->insert($data);
}
//--------------------------------------------------------------------
/**
* Removes a single permission from a single group.
*
* #param int $permissionId
* #param int $groupId
*
* #return mixed
*/
public function removePermissionFromGroup(int $permissionId, int $groupId)
{
return $this->db->table('auth_groups_permissions')
->where([
'permission_id' => $permissionId,
'group_id' => $groupId
])->delete();
}
//--------------------------------------------------------------------
/**
* Removes a single permission from all groups.
*
* #param int $permissionId
*
* #return mixed
*/
public function removePermissionFromAllGroups(int $permissionId)
{
return $this->db->table('auth_groups_permissions')
->where('permission_id', $permissionId)
->delete();
}
}
I'm trying to make a get request to rest api, route bellow:
Route::group(
['middleware' => 'api'],
function() {
Route::get('users', 'UserApiController#index')->name('api.user.list');
Route::get('users/{user}', 'UserApiController#show')->name('api.user.user');
Route::post('users', 'UserApiController#store')->name('api.user.create');
Route::put('users/{user}', 'UserApiController#update')->name('api.user.update');
Route::delete('users/{user}', 'UserApiController#destroy')->name('api.user.delete');
Route::patch('users/{user}/credentials', 'UserApiController#setCredentials')->name('api.user.set_credentials');
Route::get('users/credentials', 'UserApiController#findByCredentials')->name('api.user.find_by.credentials');
Route::get('users/email/{email}', 'UserApiController#findByEmail')->name('api.user.find_by.email');
Route::get('users/phone/{phone}','UserApiController#findByPhone')->name('api.user.find_by.phone');
});
Controller
<?php
namespace App\Http\Controllers;
use App\Http\Requests\CreateUserRequest;
use App\Http\Requests\SetCredentialsRequest;
use App\Http\Requests\UpdateUserRequest;
use App\Models\User;
use App\Models\UserEmail;
use App\Models\UserPhone;
use Illuminate\Http\JsonResponse;
use App\Http\Resources\User as UserResource;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class UserApiController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(): JsonResponse
{
return response()->json(
['data' => UserResource::collection(User::all())],
200
);
}
/**
* Display the specified resource.
*
* #param \App\Models\User $user
* #return \Illuminate\Http\Response
*/
public function show(User $user): JsonResponse
{
return response()->json(
['data' => new UserResource($user)],
200
);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(CreateUserRequest $request): JsonResponse
{
try {
DB::beginTransaction();
$user = (new User())
->create(
$request->only(['uuid', 'first_name', 'last_name'])
);
$email = $request->get('email');
$user->emails()->save(
new UserEmail(['email' => $email])
);
DB::commit();
} catch (\Throwable $exception) {
DB::rollBack();
return response()
->json(['error' => $exception->getMessage()], 500);
}
return response()->json(
['data' => new UserResource($user)],
201
);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Models\User $user
* #return \Illuminate\Http\Response
*/
public function update(UpdateUserRequest $request, User $user): JsonResponse
{
$user->update($request->only(['username', 'password', 'first_name', 'last_name']));
return response()->json(
['data' => new UserResource($user)],
200
);
}
/**
* Remove the specified resource from storage.
*
* #param \App\Models\User $user
* #return \Illuminate\Http\Response
*/
public function destroy(User $user): JsonResponse
{
$user->delete();
return response()->json(
null,
204
);
}
public function setCredentials(SetCredentialsRequest $request, User $user)
{
$user->update([
'username' => $request->get('username'),
'password' => \password_hash($request->get('password'), \PASSWORD_BCRYPT),
]);
return response()->json(
['data' => new UserResource($user)],
200
);
}
public function findByCredentials(Request $request)
{
}
public function findByEmail(string $email)
{
$user = UserEmail::all()
->where('email', '=', $email)
->first()
->user()
->getResults();
return response()->json(
['data' => new UserResource($user)],
200
);
}
public function findByPhone(string $phone)
{
$user = UserPhone::all()
->where('phone', '=', $phone)
->first()
->user()
->getResults();
return response()->json(
['data' => new UserResource($user)],
200
);
}
}
Got an error:
No query results for model [App\\Models\\User] credentials
As I understand,laravel is attempting to find credentials field in User model to resolve it.
Controller method is never handled.
If I use Route::post - everything is ok.
How to disable "auto-finding", so I could get control in the controller?
Changing the possion of the route solved the problem:
Route::group(
['middleware' => 'api'],
function() {
Route::get('users/credentials', 'UserApiController#findByCredentials')->name('api.user.find_by.credentials');
Route::get('users', 'UserApiController#index')->name('api.user.list');
Route::get('users/{user}', 'UserApiController#show')->name('api.user.user');
Route::post('users', 'UserApiController#store')->name('api.user.create');
Route::put('users/{user}', 'UserApiController#update')->name('api.user.update');
Route::delete('users/{user}', 'UserApiController#destroy')->name('api.user.delete');
Route::patch('users/{user}/credentials', 'UserApiController#setCredentials')->name('api.user.set_credentials');
Route::get('users/email/{email}', 'UserApiController#findByEmail')->name('api.user.find_by.email');
Route::get('users/phone/{phone}','UserApiController#findByPhone')->name('api.user.find_by.phone');
});
I am making a resource controller. Here's my code.
api.php:
Route::group([ 'prefix' => 'admin', 'namespace' => 'Admin'], function () {
Route::resource('penyedia', 'PenyediaController');
});
Following is the contents of the controller PenyediaController.php:
<?php
namespace App\Http\Controllers\Admin;
use App\Exceptions\InvalidRouteException;
use App\Http\Requests\ValidatePenyedia;
use App\Http\Requests\ValidateList;
use App\Models\Penyedia;
use App\Http\Controllers\Controller;
class PenyediaController extends Controller
{
/**
* Penyedia model.
*
* #var Penyedia
*/
private $penyedia;
/**
* PenyediaController constructor.
*
* #param Penyedia $penyedia
*/
public function __construct(Penyedia $penyedia)
{
$this->penyedia = $penyedia;
}
/**
* Display a listing of the Penyedia.
*
* #param ValidateList $request
* #return \Illuminate\Http\Response
*/
public function index(ValidateList $request)
{
$validated = $request->validated();
$filter = array_key_exists('filter', $validated) ? $validated['filter'] : [];
$keyword = array_key_exists('keyword', $validated) ? $validated['keyword'] : null;
$datatable = array_key_exists('per_page', $validated) ?
$this->penyedia->datatable($filter, $keyword)->paginate($validated['per_page'])
:
$this->penyedia->datatable($filter, $keyword)->get();
return response()->json([
'error' => false,
'data' => $datatable
]);
}
/**
* Show the form for creating a new Penyedia.
*
* #return void
* #throws InvalidRouteException
*/
public function create()
{
throw new InvalidRouteException();
}
/**
* Store a newly created Penyedia in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(ValidatePenyedia $request)
{
$validated = $request->validated();
$this->penyedia = $this->penyedia->create($this->penyedia->prepareData($validated));
return response()->json([
'error' => false,
'data' => $this->penyedia->output()
]);
}
/**
* Display the specified Penyedia.
*
* #param int $id
* #return void
* #throws InvalidRouteException
*/
public function show(Penyedia $penyedia)
{
//dd('z');
dd($penyedia->nama);
throw new InvalidRouteException();
}
/**
* Show the form for editing the specified Penyedia.
*
* #param int $id
* #return void
* #throws InvalidRouteException
*/
public function edit($id)
{
throw new InvalidRouteException();
}
/**
* Update the specified Penyedia in storage.
*
* #param ValidatePenyedia $request
* #param Penyedia $penyedia
* #return \Illuminate\Http\Response
*/
public function update(Penyedia $penyedia)
{
dd($penyedia->id);
//dd("z");
$validated = $request->validated();
//dd("hehe");
dd($penyedia);
$penyedia->update($this->penyedia->prepareData($validated));
dd($this->penyedia->prepareData($validated));
return response()->json([
'error' => false,
'data' => $penyedia->output()
]);
}
/**
* Remove the specified Penyedia from storage.
*
* #param Penyedia $penyedia
* #return \Illuminate\Http\Response
* #throws \Exception
*/
public function destroy(Penyedia $penyedia)
{
$penyedia->delete();
return response()->json([
'error' => false,
'data' => $penyedia->output()
]);
}
}
This is the contents of Penyedia.php:
<?php
namespace App\Models;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Penyedia extends Model
{
use SoftDeletes;
protected $table = 'penyedia';
protected $fillable = [
'nama', 'penanggung_jawab', 'deskripsi', 'category', 'user_id', 'kontak'
];
protected $dates = ['deleted_at'];
/**
* Relation to User.
*
* #return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function scopeDatatable($query, $filters = [], $keyword = null){
// dd("sampesini");
foreach ($filters as $filter) {
$query->orderBy($filter['field'], $filter ['order']);
}
if ($keyword) {
$query->where('nama', 'LIKE', '%' . $keyword . '%')
->orWhere('deskripsi', 'LIKE', '%' . $keyword . '%')
->orWhere('penanggung_jawab', 'LIKE', '%' . $keyword . '%')
->orWhere('kontak', 'LIKE', '%' . $keyword . '%');
}
//return $query->select('id', 'nama');
return $query->with(['user:id,name'])->select('id', 'nama', 'penanggung_jawab', 'deskripsi', 'category', 'user_id', 'kontak');
}
public function prepareData($data)
{
return [
'nama' => $data['nama'] ? $data['nama'] : '',
'penanggung_jawab' => isset($data['penanggung_jawab']) ? $data['penanggung_jawab'] : '',
'deskripsi' => isset($data['deskripsi']) ? $data['deskripsi'] : '',
'category' => isset($data['category']) ? $data['category'] : '',
'user_id' => isset($data['user_id']) ? $data['user_id'] : '',
'kontak' => isset($data['kontak']) ? $data['kontak'] : '',
];
}
public function output()
{
return $this->with(['user:id,name'])->select('id', 'nama', 'penanggung_jawab', 'deskripsi', 'category', 'user_id', 'kontak')->first();
}
public function user()
{
return $this->belongsTo(User::class);
}
/**
* Relation to Beasiswa.
*
* #return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function beasiswa()
{
return $this->hasMany(Beasiswa::class);
}
}
Then when I open cmd then I type php artisan route: list
suddenly there was an addition of 'um' to the router's parameters. How can it be like that ? Here's the screenshot:
https://i.imgur.com/kZLUiGm.png
I found solution, I just edit my route like this :
Route::resource('penyedia', 'PenyediaController', [
'parameters' => ['penyedia' => 'penyedia']
]);
And my parameter is back to 'penyedia'
I want to make an instance of my model in my controller and use it every where i need
I use this code:
public $test = new Access();
but the is this error that i cant figure it out why i kept getting this error:
expression is not allowed as field default value
and this is my controller code down here:
<?php
namespace App\Http\Controllers;
use App\Models\Access;
use Illuminate\Http\Request;
classAccessController extends Controller{
private $table = 'accesses';
public $test = new Access();
/**
* #return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function index()
{
$table = $this->table;
$accesses = (new Access())->index($table);
return view('index', compact('accesses'));
}
/**
* #param Request $request
* #return \Illuminate\Http\RedirectResponse
*/
public function store(Request $request)
{
$access = new Access();
$request->validate([
'can_select' => 'required|boolean',
'can_delete' => 'required|boolean',
'can_edit' => 'required|boolean',
'can_insert' => 'required|boolean',
'role_id' => 'required|integer|max:2',
'module_id' => 'required|integer|max:3',
]);
$access->can_select = $request->get('can_select');
$access->can_delete = $request->get('can_delete');
$access->can_edit = $request->get('can_edit');
$access->can_insert = $request->get('can_insert');
$access->role_id = $request->get('role_id');
$access->module_id = $request->get('module_id');
$attributes = array('can_select', 'can_delete', 'can_edit', 'can_insert', 'role_id', 'module_id');
$options = array($access->can_select, $access->can_delete, $access->can_edit, $access->can_insert, $access->role_id, $access->module_id);
$table = $this->table;
(new Access())->store($table, $attributes, $options);
return redirect('accesses')->with('success', 'Information has been inserted');
}
/**
* #param $id
* #return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function edit($id)
{
$access = Access::find($id);
return view('update', compact('access', 'id'));
}
/**
* #param Request $request
* #param $id
* #return \Illuminate\Http\RedirectResponse
*/
public function update(Request $request, $id)
{
$access = Access::find($id);
$request->validate([
'can_select' => 'required|boolean',
'can_delete' => 'required|boolean',
'can_edit' => 'required|boolean',
'can_insert' => 'required|boolean',
'role_id' => 'required|integer|max:2',
'module_id' => 'required|integer|max:3',
]);
$access->can_select = $request->get('can_select');
$access->can_delete = $request->get('can_delete');
$access->can_edit = $request->get('can_edit');
$access->can_insert = $request->get('can_insert');
$access->role_id = $request->get('role_id');
$access->module_id = $request->get('module_id');
$attributes = array('can_select', 'can_delete', 'can_edit', 'can_insert', 'role_id', 'module_id');
$options = array($access->can_select, $access->can_delete, $access->can_edit, $access->can_insert, $access->role_id, $access->module_id);
$object = $access;
$table = $this->table;
(new Access())->updates($table, $object, $attributes, $options);
return redirect('accesses')->with('success', 'Information has been updated successfully!!');
}
/**
* #param $id
* #return \Illuminate\Http\RedirectResponse
*/
public function destroy($id)
{
$access = Access::find($id);
$object = $access;
$table = $this->table;
(new Access())->erase($table, $object);
return redirect('accesses')->with('success', 'Information has been deleted');
}
}
i first thought it is the security problem but in my idea it is irrelevent in my idea
I don't understand your use case but.. you can use the contructor of the class to do so:
class ACoolController extends Controller {
protected $access;
/**
* ACoolController constructor.
*
*/
public function __construct()
{
$this->access = new Access();
}
public function aCoolFunction()
{
// do something with your variable
$this->access->someMethodOfYourModel();
}
}
Of-course you can't in PHP you cannot call a method to instantiate a class member even if it is a static method either initialize it in the constructor
class AccessController extends Controller{
public $test ;
public function __construct()
{
$this->test= new Access();
}
}
Or much better use the dependency injection pattern ( Container ) in Laravel to avoid creating multiple instances of the Access Model see the docs : https://laravel.com/docs/5.7/container
just now I get this issues that is bothering me.
the error in code after validator::make in update function.
BadMethodCallException in Controller.php line 107: Method [all] does
not exist.
This is the full code from BooksController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\book;
class BooksController extends Controller
{
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
$book = BooksController::all();
return view('book.index')->with('book', $book);
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
return view('book.create');
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store()
{
$rules = array(
'judul' => 'required',
'author' => 'required',
'penerbit' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
// process the login
if ($validator->fails()) {
return Redirect::to('book/create')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
// store
$book = new book;
$book ->judul = Input::get('judul');
$book ->author = Input::get('author');
$book ->penerbit = Input::get('penerbit');
$book ->save();
// redirect
Session:flash('message', 'Berhasil membuat buku!');
return Redirect::to('book');
}
}
/**
* Display the specified resource.
*
* #param int $idate
* #return Response
*/
public function show($id)
{
$book = books::find($id);
return view('book.show')
->with('book', $book);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{
$book = books::find($id);
return view('book.edit')
->with('book', $book);
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id)
{
$rules = array(
'judul' => 'required',
'author' => 'required',
'penerbit' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::to('book/' . $id . '/edit')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
// simpan
$book = books::find($id);
$book->judul = Input::get('judul');
$book->author = Input::get('author');
$book->penerbit = Input::get('penerbit');
$book->save();
// redirect
Session::flash('message', 'Berhasil mengganti info buku!');
return Redirect::to('book');
}
}
/**
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
$book = books::find($id);
$book ->delete();
//redirect
Session::flash('message', 'Berhasil menghapus buku!');
return Redirect::to('book');
}
}
try this use Validator; instead of
use Illuminate\Support\Facades\Validator;
convert user Input::all() to input()->all() or request()->all()