On Laravel 5.4.1 I'm always getting this error when using ajax
FatalThrowableError in avController.php line 53: Call to a member function addvoter() on null
but it seems to work perfectly without ajax. I think the problem starts from $request->user()->addvoter()->save($voter); which is my line 53 but I don't understand it;
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
if ($request->isMethod('post')){
$voter = new voter();
$voter->FirstName = $request->fname;
$voter->LastName= $request->lname;
$voter->Email = $request->email;
$voter->PhoneNumber = $request->phone;
$voter->Gender = $request->optradio;
$voter->StudentID = $request->sID;
$voter->Level = $request->level;
$voter->Course = $request->course;
$voter->Stream = $request->stream;
$voter->Nationality = $request->nat;
$voter->ProfileImg = $request->image;
$request->user()->addvoter()->save($voter);
$response = array(
'fname' => $request->fname,
'lname' => $request->lname,
'msg' => 'Setting created successfully',
);
return response()->json($response);
}
return response()->json(['response' => 'This is get method']);
}
my user model
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function addcandidate(){
return $this->hasMany('elpebi\addcandidate');
}
public function addstcandidate(){
return $this->hasMany('elpebi\stcandidate');
}
public function addvoter(){
return $this->hasMany('elpebi\voter');
}
public function newelection(){
return $this->hasMany('elpebi\election');
}
my voter model
protected $fillable = ['FirstName', 'LastName', 'Email',
'Gender', 'StudentID', 'Level', 'Course',
'Stream', 'Nationality', 'ProfileImg' ];
public function user(){
return $this->belongsTo('elpebi\User');
}
If your user is logged in, I think you can do this:
auth()->user()->addvoter()->save($voter);
Related
i'm new in laravel php and i try to create a new user with api post request and when i send this request i have a porblem when i do it
I use psgql and laravel 9. i use that
link to do this and custom somthing
This is my code:
i has User model like
class User extends Authenticatable
{
use HasApiTokens,HasFactory, Notifiable;
public $timestamps = false;
protected $table = 'user';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'first_name',
'last_name',
'email',
'password',
];
/**
* 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 here is my AuthController to create new user
class AuthController extends Controller
{
/**
* Create User
* #param Request $request
* #return User|\Illuminate\Http\JsonResponse
*/
public function createUser(Request $request){
try{
$validateUser = Validator::make($request->all(),[
'first_name'=>'required',
'last_name'=>'required',
'email'=>'required|email|unique:users,email',
'password'=>'required'
]);
if($validateUser->fails()){
return response()->json([
'status'=>false,
'message'=>'validation error',
'errors'=>$validateUser->errors()
],401);
}
$user = User::create([
'first_name'=>$request->first_name,
'last_name'=>$request->last_name,
'email'=>$request->email,
'password'=> Hash::make($request->password)
]);
return response()->json([
'status'=>true,
'message'=>'User created successfully',
'token'=>$user->createToken("API TOKEN")->plainTextToken
],200);
}
catch (\Throwable $th){
return response()->json([
'status'=>false,
'message'=>$th->getMessage()
],500);
}
}
}
and i got problem when i send post request json
like
{
"status": false,
"message": "SQLSTATE[42P01]: Undefined table: 7 ERROR: relation \"users\" does not exist\nLINE 1: select count(*) as aggregate from \"users\" where \"email\" = $1\n ^ (SQL: select count(*) as aggregate from \"users\" where \"email\" = something#abc.com)"
}
please help me
Instead of:❌
'email'=>'required|email|unique:users,email',
Use this:✅
'email'=>'required|email|unique:user,email',
Note the table name defined in your User Model is user.
Hence, that has to be reflected in your validation rules as well.
You forget to check you table in in validation
'email'=>'required|email|unique:users,email',
replace users to user
You are using the wrong table name in the validation, you need to replace 'users' by 'user' :
'email'=>'required|email|unique:users,email' to be 'email'=>'required|email|unique:user,email'
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 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)
I'm trying to make a belongstoMany relationship in Laravel 5.2.39 between people and places but am unable to pass the information into a view in a select box. I just get: "Error Exception: Undefined variable: people". It also is not saving and making the pivot table entries.
I have created the pivot table person_place with 'place_id' and 'person_id' columns which correspond to the 'people' and 'places' table.
App/Person.php (Person Model)
<?php
namespace ss;
use ss\Place;
use Illuminate\Database\Eloquent\Model;
class Person extends Model
{
/**
* Fillable fields
*
* #var array
*/
protected $fillable = [
'name',
'type',
'status',
'notes',
'email',
'phone',
'alt',
'web',
'first',
'last',
'title',
];
public function places()
{
return $this->belongsToMany('Place');
}
}
App/Place.php (Place Model)
<?php
namespace ss;
use ss\Person;
use Illuminate\Database\Eloquent\Model;
class Place extends Model
{
/**
* Fillable fields
*
* #var array
*/
protected $fillable = [
'name',
'type',
'status',
'notes',
'email',
'phone',
'alt',
'web',
'address1',
'address2',
'city',
'state',
'zip',
'country',
];
public function people()
{
return $this->belongsToMany('Person');
}
}
App/Http/Controllers/PlaceController.php (Places Controller)
<?php namespace ss\Http\Controllers;
use ss\Place;
use ss\Person;
use ss\Http\Requests;
use Illuminate\Http\Request;
use View;
use Session;
class PlaceController extends Controller
{
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
$places = Place::all();
$people = Person::pluck('name','id')->all();
return View::make('places.index', compact('places','people'));
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
$people = Person::lists('last', 'id');
return view('places.create', compact('people'));
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required'
]);
$input = $request->all();
Place::create($input);
Session::flash('flash_message', 'Place successfully added!');
return redirect()->action('PlaceController#index');
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id)
{
$place = Place::findOrFail($id);
return view('places.show')->withPlace($place);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{
$place = Place::findOrFail($id);
$people = Person::pluck('name','id')->all();
return view('places.edit', compact('place','people'));
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id, Request $request)
{
$this->validate($request, [
'name' => 'required'
]);
$input = $request->except('people');
$place = Place::findOrFail($id);
$peopleIDs = $this->place->people($peopleIds);
$place->fill($input)->save();
Session::flash('flash_message', 'Place successfully edited!');
return redirect()->action('PlaceController#index', $place);
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
$place = Place::findOrFail($id);
$place->delete();
Session::flash('flash_message', 'Place successfully deleted!');
return redirect()->action('PlaceController#index');
}
}
resources/views/places/edit.blade.index.php (Places View, where I'm trying to build select list -not working)
#section('aside')
{!! Form::select('people', $people, null, ['class' => '', 'multiple']) !!}
<ul class="section table-of-contents">
<li>New Time</li>
<li>New Money</li>
<li> </li>
<li>New Sub-Task</li>
</ul>
#endsection
resources/views/places/create.blade.index.php (Places View with a select list that works but does not make a pivot table when saving)
#section('aside')
{!! Form::select('people', $people, null, ['class' => '', 'multiple']) !!}
#endsection
Have tried various methods of "with" and "attach" and am unable to get a result. Interestingly, even if I specifically place "$person = "foo"; in my edit method it still says it is undefined.
Thank you for your help.
EDIT: Updated Code
In the PlacesController, your edit($id) method does not pass an array of people to the view.
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{
$place = Place::findOrFail($id);
$people = People::pluck('name','id')->all();
return view('places.edit', compact('place', 'people');
}
I'm using the way/database package for validation with Laravel 4.2 and have set up a simple user registration method.
I'm testing this by trying to create a new user with an email address that is already present. The validator returns true, and then goes onto give the error:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'test2#test.com' for key 'users_email_unique' (SQL: insert into `users` (`email`, `password`, `updated_at`, `created_at`) values (test2#test.com, 123, 2015-01-29 11:50:37, 2015-01-29 11:50:37))
So is this something wrong with my model?
The controller:
public function store()
{
$user = User::create(Input::only('email', 'password'));
if ($user->hasErrors()){
return Response::json(array(
'error' => $user->getErrors()
));
}
Auth::login($user);
return Response::json(array('success' => 'true'));
}
The User.php model:
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Model implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $fillable = array(
'email', 'password'
);
protected static $rules = [
'email' => 'required:unique'
];
//Use this for custom messages
protected static $messages = [
'email.required' => 'An email address is required'
];
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
}
Here's the validation model from way/database:
class Model extends Eloquent {
/**
* Error message bag
*
* #var Illuminate\Support\MessageBag
*/
protected $errors;
/**
* Validation rules
*
* #var Array
*/
protected static $rules = array();
/**
* Custom messages
*
* #var Array
*/
protected static $messages = array();
/**
* Validator instance
*
* #var Illuminate\Validation\Validators
*/
protected $validator;
public function __construct(array $attributes = array(), Validator $validator = null)
{
parent::__construct($attributes);
$this->validator = $validator ?: \App::make('validator');
}
/**
* Listen for save event
*/
protected static function boot()
{
parent::boot();
static::saving(function($model)
{
return $model->validate();
});
}
/**
* Validates current attributes against rules
*/
public function validate()
{
$v = $this->validator->make($this->attributes, static::$rules, static::$messages);
if ($v->passes())
{
return true;
}
$this->setErrors($v->messages());
return false;
}
/**
* Set error message bag
*
* #var Illuminate\Support\MessageBag
*/
protected function setErrors($errors)
{
$this->errors = $errors;
}
/**
* Retrieve error message bag
*/
public function getErrors()
{
return $this->errors;
}
/**
* Inverse of wasSaved
*/
public function hasErrors()
{
return ! empty($this->errors);
}
}
Can anyone point me towards what I'm doing wrong?
Try changing
protected static $rules = [
'email' => 'required:unique'
];
to
protected static $rules = [
'email' => 'required|unique'
];
The Laravel docs will help
http://laravel.com/docs/4.2/validation