I am student and i am new with Laravel and i have this UserController which used to assign multi Roles to User (using pivot table user_role) but i want to assign one role to each user (without pivot table) so i added role_id foreign in table user but i dont know what to change in UserController file.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use App\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('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('display_name','id');
return view('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)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required|same:confirm-password',
'roles' => 'required'
]);
$input = $request->all();
$input['password'] = Hash::make($input['password']);
$user = User::create($input);
foreach ($request->input('roles') as $key => $value) {
$user->attachRole($value);
}
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('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('display_name','id');
$userRole = $user->roles->pluck('id','id')->toArray();
return view('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('role_user')->where('user_id',$id)->delete();
foreach ($request->input('roles') as $key => $value) {
$user->attachRole($value);
}
return redirect()->route('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('users.index')
->with('success','User deleted successfully');
}
}
and you can find all the code here:
http://itsolutionstuff.com/post/laravel-52-user-acl-roles-and-permissions-with-middleware-using-entrust-from-scratch-tutorialexample.html
this mean so much to me if you help me and thanks.
Related
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)
Currently I have users.index blade which I would like to restrict. However, I failed to restrict it.
I have tried to create another test blade and a TestController and I have set permission to it and it works fine.
However with UserController, there is just no way to restrict Users from accessing it:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use DB;
class TestController extends Controller
{
/**
* Restricting pages
*/
public function __construct()
{
$this -> middleware('permission:test-list', ['only' => ['index']]);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('test.index');
}
/**
* 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)
{
//
}
}
views/test/index.blade.php
#extends('layouts.app')
#section('content')
<p>Testing Page</p>
#endsection
These are the results if I don't permit a particular user role to access this page.
enter image description here
enter image description here
So the above is the correct behavior.
However when it comes to user.index , I applied the same technique in the constructor of the UserController but it doesn't work
app/Http/Controllers/UserController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use Spatie\Permission\Models\Role;
use DB;
use Hash;
class UserController extends Controller
{
public function construct()
{
$this -> middleware('permission:user-list', ['only' => ['index']]);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$data = User::orderBy('id','DESC') -> paginate(5);
return view('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('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)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required|same:confirm-password',
'roles' => 'required'
]);
$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('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('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('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('users.index') -> with('success','User deleted successfully');
}
}
Result [I am still able to view this Blade in front end despite not having the permission to view this page]
enter image description here
This is my role-has-permission tablerole-has-permission
This is my role table
role
This is my permission table
permissions
This is my model-has-roles table model-has-roles
This is my model-has-permissions table model-has-permissions
If you want to restrict specific routes or all you can do something like this:
Route::middleware(['auth', 'permission:user-list'])->group(function (){
Route::get('/create', 'WelcomeController#create')->name('welcome');
...
...
..
});
or you can replace
public function construct()
{
$this -> middleware('permission:user-list', ['only' => ['index']]);
}
to
public function construct()
{
$this -> middleware('permission:user-list')->except(['index']);
}
I have a problem with inserting Data into Database. Let's say I have a controller named HeroController and I want to create a new hero object and insert it to my database as a new hero.
My controller contains the following method:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
// return response()->json([
// 'name' => 'Abigail',
// 'state' => 'CA'
// ]);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6',
]);
}
public function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data[password]),
]);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$user = $request->isMethod('put');
$user = new User;
$user->name = $request->name;
$user->email = $request->email;
$user->password = $request->password;
$user->save();
return response()->json($usere, 201);
}
/**
* 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)
{
//
}
}
My routes.php file:
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('/users/create', 'UserController#create');
This is the error that i got. Type error: Too few arguments to function App\Http\Controllers\UserController::attendance(), 0 passed and exactly 1 expected". I am new to laravel.
You are using a get request to call create function.
Route::get('/users/create', 'UserController#create');
So, you are not passing any data to that controller. Hence the error.
First, you'll want to change the visibility of create and validator:
protected function create(array $data)
And the validator method:
protected function validator(array $data)
Then you'll want to change your /users/create route to a post and to use the store method:
Route::post('/users/create', 'UserController#store');
In your UserController update your store method to:
public function store(Request $request)
{
// validate the request
$validator = $this->validator($request->all());
if ($validator->fails()) {
return response()
->json(422,$validator->errors()->messages());
}
$user = $this->create($request->all());
return response()->json($user, 201);
}
If you need some sort of form to register or create a user, add an additional method in your controller:
public function register()
{
return view('user.register');
}
Then define another get route:
Route::get('/users/register', 'UserController#register');
Route::delete('/file/{id}','FileController#destroy')->name('deletefile');
Hope it will be helpful
I have created a form request using php artisan make:request ValidateRegistration. It created a ValidateRegistration.php file under App\Http\Requests\ directory. After this I have made changes in the store() function of my registration controller ie UserController.php, means I have changed it
FROM
public function store(Request $request)
{
// Save the data
User::create(request(['fname','lname','phone','email','password']));
// redirect to home page
return redirect('/registration-success');
}
TO
public function store(ValidateRagistration $request)
{
// Save the data
User::create(request(['fname','lname','phone','email','password']));
// redirect to home page
return redirect('/registration-success');
}
And added use App\Http\Requests\ValidateRagistration; at the top of the UserController.php file. But when I submit the form without filling anything it shows me an error which is Class App\Http\Controllers\ValidateRegistraion does not exist
EDIT
Added UserController.php and ValidateRegistration.php files.
UserController.php
<?php
use App\Http\Requests\ValidateRegistration;
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$title = "Registration";
return view('/registration', compact('title'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(ValidateRegistration $request)
{
//// validate requested data
//$this->validate(request(), [
// 'fname' => 'required',
// 'lname' => 'required',
// 'phone' => 'required|size:10',
// 'email' => 'required',
// 'password' => 'required'
//]);
// Save the data
User::create(request(['fname','lname','phone','email','password']));
// redirect to home page
return redirect('/registration-success');
}
/**
* 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)
{
//
}
}
ValidateRegistration.php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ValidateRegistration extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return false;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'fname' => 'required',
'lname' => 'required',
'phone' => 'required|size:10',
'email' => 'required',
'password' => 'required'
];
}
/**
* Get the error messages for the defined validation rules.
*
* #return array
*/
public function messages()
{
return [
'fname.required' => 'Firstname is mandatoy',
'lname.required' => 'Lastname is mandatory',
'phone.required' => 'Phone is mandatory',
'phone.size' => 'Phone must be 10 digit',
'email.required' => 'Email is mandatory',
'password.required' => 'Password is mandatory',
];
}
}
spot the difference in your class names:
ValidateRagistration
ValidateRegistraion
and I'm guessing it should read ValidateRegistration, clear up typos, they will only confuse things later
at the top of UserController.php swap the positions of the namespace and use lines, namespace should always be first
<?php
namespace App\Http\Controllers;
use App\Http\Requests\ValidateRegistration;
use Illuminate\Http\Request;
use App\User;
and ValidateRegistration.php is in your App\Http\Requests directory
in ValidateRegistration.php I modified the authorize() function. It was returning false. Changed it to true. It is working now.
From
public function authorize()
{
return false;
}
To
public function authorize()
{
return true;
}
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)
{
//
}
}