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;
}
Related
hopefully someone can enlighten me on this bug. Laravel 8. I am replicating a simple blog from this url: https://www.codewall.co.uk/laravel-crud-demo-with-resource-controller-tutorial/
It seems like sometimes you do these tutorials but laravel 8 is slightly different. What am I missing here? Any suggestions would be greatly appreciated!
Getting error when going to /students & a /students/create urls , I am getting different errors for
/students (index) error -
Error
Class 'App\Student' not found
It doesn't like the create route either which is weird because I have store method in StudentController.
/students/create (create) error -
Action StudentController#store not defined. (View: C:\xampp\htdocs\laravel\lara-blog2\blog\resources\views\students\create.blade.php)
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Student;
class StudentController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$students = Student::all();
return view('students.index', compact('students','students'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('students.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'first_name' => 'required',
'last_name' => 'required',
'age' => 'required|numeric',
'email' => 'required|email',
]);
$input = $request->all();
Student::create($input);
return redirect()->route('students.index');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$student = Student::findOrFail($id);
return view('students.show', compact('student','student'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$student = Student::find($id);
return view('students.edit', compact('student','student'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$student = Student::findOrFail($id);
$this->validate($request, [
'first_name' => 'required',
'last_name' => 'required',
'age' => 'required|numeric',
'email' => 'required|email',
]);
$input = $request->all();
$student->fill($input)->save();
return redirect()->route('students.index');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$student = Student::findOrFail($id);
$student->delete();
return redirect()->route('students.index');
}
}
As you are using Laravel 8, all models now are located in App\Models directory in App directory as previous versions, so you need to update your import statement to be
use App\Models\Student;
Read more about Models new directory in Laravel Release Notes Here
In Laravel 8, all models now are located in App/Models so use
use App\Models\Student;
From Laravel 8, all models are now located in the App\Models directory in the App directory as in previous versions, so you need to update your import statement to be
App\Models\Student; instead of App\Student;
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 am using
Route::auth();
for making user login in Laravel.
There are multiple phones linked to a user and saved in table:phones.
Tables are
users : id,email,password
phones: id,user_id,phone_number
How to make user login with both Email/Phones and password
In App\Traits\Auth, create a file named LoginUser.php.
<?php
namespace App\Traits\Auth;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
trait LoginUser
{
/**
* Handle a Authenticates the User.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function login(Request $request)
{
$this->validateLogin($request);
if ($this->attemptLogin($request)) {
return $this->successfulLogin($request);
}
return $this->failedLogin($request);
}
/**
* Validate the user login request.
*
* #param \Illuminate\Http\Request $request
* #return void
*/
protected function validateLogin(Request $request)
{
$this->validate($request, [
'username' => 'required',
'password' => 'required',
]);
}
/**
* Attempt to log the user into the application.
*
* #param \Illuminate\Http\Request $request
* #return bool
*/
protected function attemptLogin(Request $request)
{
//Try with email AND username fields
if (Auth::attempt([
'phone' => $request['username'],
'password' => $request['password']
],$request->has('remember'))
|| Auth::attempt([
'email' => $request['username'],
'password' => $request['password']
],$request->has('remember'))){
return true;
}
return false;
}
/**
* This is executed when the user successfully logs in
*
* #var Request $request
* #return Reponse
*/
protected function successfulLogin(Request $request){
return redirect($this->redirectTo);
}
/**
* This is executed when the user fails to log in
*
* #var Request $request
* #return Reponse
*/
protected function failedLogin(Request $request){
return redirect()->back()->withErrors(['password' => 'You entered the wrong username or password']);
}
}
Then in
App\Http\Controllers\Auth
rewrite (or create) LoginController.php and paste this
<?php
namespace App\Http\Controllers\Auth;
use App\Traits\Auth\LoginUser;
use App\Http\Controllers\Controller;
class LoginController extends Controller
{
use LoginUser;
/**
* Where to redirect users after registration.
*
* #var string | URL
*/
protected $redirectTo = '/mPanel';
/**
* Displays login page
*
* #return \Illuminate\Http\Response
*/
public function show(){
return response()->view('LOGIN PAGE HERE');
}
}
Finally in your routes file, add these routes:
Route::get('login', 'Auth\LoginController#show');
Route::post('login', 'Auth\LoginController#login');
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)
{
//
}
}