The route I made suddenly added the "um" - php

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'

Related

Code Igniter 4 Restful API only default controller, routes not work

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();
}
}

Laravel image save as .tmp in the db even though the file uploaded in the correct folder

I'm trying to add a user to the database in Laravel.
following is my User Model.
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable implements MustVerifyEmail {
use HasFactory, Notifiable, HasRoles;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'first_name',
'last_name',
'image_id',
'country_id',
'email',
'password',
'gender',
'date_of_birth',
'region_id',
'role_id',
'is_email_verified'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
And this is my User Controller.
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\User;
use Spatie\Permission\Models\Role;
use DB;
use Hash;
class UserController extends Controller {
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(Request $request) {
$data = User::orderBy('id','DESC')->paginate(5);
return view('admins.users.index',compact('data'))
->with('i', ($request->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create() {
$roles = Role::pluck('name','name')->all();
return view('admins.users.create',compact('roles'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request) {
$data = $request->input('roles');
foreach($data as $key => $value) {
$key = 'data' . $key;
$$key = $value;
}
$roleid=$data0;
if($roleid=='Admin') {
$roleid='1';
} else if($roleid=='Regional Admin') {
$roleid='2';
} else {
$roleid='3';
}
$request->merge(['role_id' => ''.$roleid.'']);
$request->merge(['gender' => 'M']);
$request->merge(['date_of_birth' => '1992-01-11']);
$this->validate($request, [
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required|same:confirm-password',
'roles' => 'required',
'image_id' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'role_id'=>'required',
'gender'=>'required',
'date_of_birth'=>'required'
]);
if ($image = $request->file('image_id')) {
$destinationPath = 'propics/';
$profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $profileImage);
$input['image_id'] = $profileImage;
$request->merge(['image_id' => $profileImage]);
}
//$input['role_id']=$request->input('roles');
dd($request->all());
$input = $request->all();
$input['password'] = Hash::make($input['password']);
$user = User::create($input);
$user->assignRole($request->input('roles'));
return redirect()->route('users.index')
->with('success','User created successfully');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id) {
$user = User::find($id);
return view('admins.users.show',compact('user'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id) {
$user = User::find($id);
$roles = Role::pluck('name','name')->all();
$userRole = $user->roles->pluck('name','name')->all();
return view('admins.users.edit',compact('user','roles','userRole'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id) {
$this->validate($request, [
'name' => 'required',
'email' => 'required|email|unique:users,email,'.$id,
'password' => 'same:confirm-password',
'roles' => 'required'
]);
$input = $request->all();
if(!empty($input['password'])) {
$input['password'] = Hash::make($input['password']);
} else {
$input = array_except($input,array('password'));
}
$user = User::find($id);
$user->update($input);
DB::table('model_has_roles')->where('model_id',$id)->delete();
$user->assignRole($request->input('roles'));
return redirect()->route('admins.users.index')
->with('success','User updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id) {
User::find($id)->delete();
return redirect()->route('admins.users.index')
->with('success','User deleted successfully');
}
}
Now my question is that this stores my users in the DB perfectly but the user image stores as .tmp.
The file also get uploaded into the correct folder, but when it stores in the DB it stores as,
C:\xampp\tmp\phpA031.tmp
instead of .png or .jpg
Where should I correct my code?
public function store(Request $request){
$post = new Post([
'title'=>$request->get('title'),
'description'=>$request->get('description')
]);
$imageName = $request->title.'.png';
$request->image->move(public_path('images/posts'),$imageName);
$post->save();
return redirect()->back();
}
now you create view and create 3 input fields: name title (text), description (textarea) and image (file)

Laravel CRUD Generator FatalThrowableError in ProiodaController.php line 32: Call to undefined method App\DataTables\ProiodaDataTable::render()

I'm working on a Laravel 5.4 project and I've downloaded the crud generator package, but when I use the --datatables=true tag and I go to the view I'm getting the error:
FatalThrowableError in ProiodaController.php line 32:
Call to undefined method App\DataTables\ProiodaDataTable::render()
I am using the yajra/laravel-datatables such the generator to works need it.
The Generator has generate all the view files controller request model repositories and in a folder called DataTables has generate a file named ProiodaDataTable.php.
Below is The ProiodaController.php
<?php
namespace App\Http\Controllers;
use App\DataTables\ProiodaDataTable;
use App\Http\Requests;
use App\Http\Requests\CreateProiodaRequest;
use App\Http\Requests\UpdateProiodaRequest;
use App\Repositories\ProiodaRepository;
use Flash;
use App\Http\Controllers\AppBaseController;
use Response;
class ProiodaController extends AppBaseController
{
/** #var ProiodaRepository */
private $proiodaRepository;
public function __construct(ProiodaRepository $proiodaRepo)
{
$this->proiodaRepository = $proiodaRepo;
}
/**
* Display a listing of the Proioda.
*
* #param ProiodaDataTable $proiodaDataTable
* #return Response
*/
public function index(ProiodaDataTable $proiodaDataTable)
{
return $proiodaDataTable->render('proiodas.index');
}
/**
* Show the form for creating a new Proioda.
*
* #return Response
*/
public function create()
{
return view('proiodas.create');
}
/**
* Store a newly created Proioda in storage.
*
* #param CreateProiodaRequest $request
*
* #return Response
*/
public function store(CreateProiodaRequest $request)
{
$input = $request->all();
$proioda = $this->proiodaRepository->create($input);
Flash::success('Proioda saved successfully.');
return redirect(route('proiodas.index'));
}
/**
* Display the specified Proioda.
*
* #param int $id
*
* #return Response
*/
public function show($id)
{
$proioda = $this->proiodaRepository->findWithoutFail($id);
if (empty($proioda)) {
Flash::error('Proioda not found');
return redirect(route('proiodas.index'));
}
return view('proiodas.show')->with('proioda', $proioda);
}
/**
* Show the form for editing the specified Proioda.
*
* #param int $id
*
* #return Response
*/
public function edit($id)
{
$proioda = $this->proiodaRepository->findWithoutFail($id);
if (empty($proioda)) {
Flash::error('Proioda not found');
return redirect(route('proiodas.index'));
}
return view('proiodas.edit')->with('proioda', $proioda);
}
/**
* Update the specified Proioda in storage.
*
* #param int $id
* #param UpdateProiodaRequest $request
*
* #return Response
*/
public function update($id, UpdateProiodaRequest $request)
{
$proioda = $this->proiodaRepository->findWithoutFail($id);
if (empty($proioda)) {
Flash::error('Proioda not found');
return redirect(route('proiodas.index'));
}
$proioda = $this->proiodaRepository->update($request->all(), $id);
Flash::success('Proioda updated successfully.');
return redirect(route('proiodas.index'));
}
/**
* Remove the specified Proioda from storage.
*
* #param int $id
*
* #return Response
*/
public function destroy($id)
{
$proioda = $this->proiodaRepository->findWithoutFail($id);
if (empty($proioda)) {
Flash::error('Proioda not found');
return redirect(route('proiodas.index'));
}
$this->proiodaRepository->delete($id);
Flash::success('Proioda deleted successfully.');
return redirect(route('proiodas.index'));
}
}
Here is The ProiodaDataTable.php
<?php
namespace App\DataTables;
use App\Models\Proioda;
use Form;
use Yajra\Datatables\Facades\Datatables;
use Illuminate\Support\Facades\View;
class ProiodaDataTable extends Datatables
{
/*
* #return \Illuminate\Http\JsonResponse
*/
public function ajax()
{
return $this->datatables
->eloquent($this->query())
->addColumn('action', 'proiodas.datatables_actions')
->make(true);
}
/**
* Get the query object to be processed by datatables.
*
* #return \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder
*/
public function query()
{
$proiodas = Proioda::query();
return $this->applyScopes($proiodas);
}
/**
* Optional method if you want to use html builder.
*
* #return \Yajra\Datatables\Html\Builder
*/
public function html()
{
return $this->builder()
->columns($this->getColumns())
->addAction(['width' => '10%'])
->ajax('')
->parameters([
'dom' => 'Bfrtip',
'scrollX' => false,
'buttons' => [
'print',
'reset',
'reload',
[
'extend' => 'collection',
'text' => '<i class="fa fa-download"></i> Export',
'buttons' => [
'csv',
'excel',
'pdf',
],
],
'colvis'
]
]);
}
/**
* Get columns.
*
* #return array
*/
private function getColumns()
{
return [
'onoma' => ['name' => 'onoma', 'data' => 'onoma'],
'perigrafi' => ['name' => 'perigrafi', 'data' => 'perigrafi'],
'timi' => ['name' => 'timi', 'data' => 'timi']
];
}
/**
* Get filename for export.
*
* #return string
*/
protected function filename()
{
return 'proiodas';
}
}

FatalThrowableError in ProiodaController.php line 32: Call to undefined method App\DataTables\ProiodaDataTable::render()

Hi i am getting an error with laravel 5.4 i am using infyom/laravel-generator package and when i use the php artisan infyom:scaffold ModelName --datatables=true when i go to the view im getting the error.
FatalThrowableError in ProiodaController.php line 32: Call to undefined method App\DataTables\ProiodaDataTable::render()
This is my controller ProiodaController.php
<?php
namespace App\Http\Controllers;
use App\DataTables\ProiodaDataTable;
use App\Http\Requests;
use App\Http\Requests\CreateProiodaRequest;
use App\Http\Requests\UpdateProiodaRequest;
use App\Repositories\ProiodaRepository;
use Flash;
use App\Http\Controllers\AppBaseController;
use Response;
class ProiodaController extends AppBaseController
{
/** #var ProiodaRepository */
private $proiodaRepository;
public function __construct(ProiodaRepository $proiodaRepo)
{
$this->proiodaRepository = $proiodaRepo;
}
/**
* Display a listing of the Proioda.
*
* #param ProiodaDataTable $proiodaDataTable
* #return Response
*/
public function index(ProiodaDataTable $proiodaDataTable)
{
return $proiodaDataTable->render('proiodas.index');
}
/**
* Show the form for creating a new Proioda.
*
* #return Response
*/
public function create()
{
return view('proiodas.create');
}
/**
* Store a newly created Proioda in storage.
*
* #param CreateProiodaRequest $request
*
* #return Response
*/
public function store(CreateProiodaRequest $request)
{
$input = $request->all();
$proioda = $this->proiodaRepository->create($input);
Flash::success('Proioda saved successfully.');
return redirect(route('proiodas.index'));
}
/**
* Display the specified Proioda.
*
* #param int $id
*
* #return Response
*/
public function show($id)
{
$proioda = $this->proiodaRepository->findWithoutFail($id);
if (empty($proioda)) {
Flash::error('Proioda not found');
return redirect(route('proiodas.index'));
}
return view('proiodas.show')->with('proioda', $proioda);
}
/**
* Show the form for editing the specified Proioda.
*
* #param int $id
*
* #return Response
*/
public function edit($id)
{
$proioda = $this->proiodaRepository->findWithoutFail($id);
if (empty($proioda)) {
Flash::error('Proioda not found');
return redirect(route('proiodas.index'));
}
return view('proiodas.edit')->with('proioda', $proioda);
}
/**
* Update the specified Proioda in storage.
*
* #param int $id
* #param UpdateProiodaRequest $request
*
* #return Response
*/
public function update($id, UpdateProiodaRequest $request)
{
$proioda = $this->proiodaRepository->findWithoutFail($id);
if (empty($proioda)) {
Flash::error('Proioda not found');
return redirect(route('proiodas.index'));
}
$proioda = $this->proiodaRepository->update($request->all(), $id);
Flash::success('Proioda updated successfully.');
return redirect(route('proiodas.index'));
}
/**
* Remove the specified Proioda from storage.
*
* #param int $id
*
* #return Response
*/
public function destroy($id)
{
$proioda = $this->proiodaRepository->findWithoutFail($id);
if (empty($proioda)) {
Flash::error('Proioda not found');
return redirect(route('proiodas.index'));
}
$this->proiodaRepository->delete($id);
Flash::success('Proioda deleted successfully.');
return redirect(route('proiodas.index'));
}
}
This is ProiodaDataTable.php
<?php
namespace App\DataTables;
use App\Models\Proioda;
use Form;
use Yajra\Datatables\Facades\Datatables;
use Illuminate\Support\Facades\View;
class ProiodaDataTable extends Datatables
{
/**
* #return \Illuminate\Http\JsonResponse
*/
public function ajax()
{
return $this->datatables
->eloquent($this->query())
->addColumn('action', 'proiodas.datatables_actions')
->make(true);
}
/**
* Get the query object to be processed by datatables.
*
* #return \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder
*/
public function query()
{
$proiodas = Proioda::query();
return $this->applyScopes($proiodas);
}
/**
* Optional method if you want to use html builder.
*
* #return \Yajra\Datatables\Html\Builder
*/
public function html()
{
return $this->builder()
->columns($this->getColumns())
->addAction(['width' => '10%'])
->ajax('')
->parameters([
'dom' => 'Bfrtip',
'scrollX' => false,
'buttons' => [
'print',
'reset',
'reload',
[
'extend' => 'collection',
'text' => '<i class="fa fa-download"></i> Export',
'buttons' => [
'csv',
'excel',
'pdf',
],
],
'colvis'
]
]);
}
/**
* Get columns.
*
* #return array
*/
private function getColumns()
{
return [
'onoma' => ['name' => 'onoma', 'data' => 'onoma'],
'perigrafi' => ['name' => 'perigrafi', 'data' => 'perigrafi'],
'timi' => ['name' => 'timi', 'data' => 'timi']
];
}
/**
* Get filename for export.
*
* #return string
*/
protected function filename()
{
return 'proiodas';
}
}
Can someone help me please!!

Couchbase with Laravel: Data cannot be inserted in the couchbase

I am new to couchbase and laravel. I am developing an entry form. I am using couchbase as database and in the back-end i am using laravel. when ever i try to insert data in the couchbase, although the query run, but it prints the data on the screen, rather than it stores in the database. Please help me in this issue
This is my model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Member extends Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Member extends Model
{
//
protected $table = '';
protected $primaryKey = 'id';
public $timestamps = false;
public static $couchbase_bucket = 'default';
public static $couchbase_doc = 'doc1';
protected $fillable = [
'id',
'name',
'father_name',
'constituency' ,
'seat_type',
'profession' ,
'deprtment' ,
'cabinet_post',
'party',
'date_of_birth',
'religon' ,
'marital_status',
'gender' ,
'education',
'present_contact',
'permanent_contact'
];
public static function create(array $attributes = array()){
die(print_r($attributes));
$value = [
'id' => intval($attributes['id']),
'name' => $attributes['name'],
'father_name' => $attributes['father_name'],
'constituency' => $attributes['constituency'],
'seat_type' => $attributes['seat_type'],
'profession' => $attributes['profession'],
'deprtment' => $attributes['department'],
'cabinet_post' => $attributes['cabinet_post'],
'party' => $attributes['party'],
'date_of_birth' => $attributes['date_of_birth'],
'religon' => $attributes['religon'],
'marital_status' => $attributes['marital_status'],
'gender' => $attributes['gender'],
'education' => $attributes['education'],
'present_contact' => $attributes['present_contact'],
'permanent_contact' => $attributes['permanent_contact'],
];
$key = 'insert:and:delete';
$result = \DB::connection('couchbase')->table(self::$couchbase_bucket)->key($key)->upsert($value);
return $result;
}
public static function all($columns = array()){
return \DB::connection('couchbase')->table(self::$couchbase_bucket)->get();
// DB::connection('couchbase')
// ->table('testing')->where('whereKey', 'value')->get();
}
public static function one($id){
return \DB::connection('couchbase')->table(self::$couchbase_bucket)->where('id',$id)->get();
}
}
And the controller is
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Member;
class memberController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
$memberdata = Member::all();
return view('member.index')->withuserdata($userdata);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
return view('member.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
$input = $request->all();
Member::create($input);
//return redirect('member/index');
}
/**
* 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)
{
//
}
}

Categories