Laravel : How to create custom Register - laravel

I have 2 register and login form. The one is used to user and others is used to admin role.
In user role, I using from laravel authentication, is good and work well.
But, the problem is when I create custom register from admin role, its can't work well.
It can't store to database, when I check using echo function, it's not print anything just refresh the page.
Could you help me, what is wrong ???
this is my route
Route::get('/adminregister', 'Auth\LoginController#formreg')->name('admin-reg');
this is my controller
namespace App\Http\Controllers\Admin\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
class AregisterController extends Controller
{
use RegistersUsers;
public function __construct()
{
// $this->middleware('guest');
}
public function create(Request $request)
{
$this->validate(request(),[
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
if ($request('confirmpassword') == $request('password')){
$user = User::create(request(['name','email' ,'password','is_admin' => True, ]));
// return redirect()->route('admin-login')->with('status', 'Successfully create account');;
}
else {
return redirect()->route('admin-reg')->with('status', 'Confirm Password not match');;
}
}
}
In this controller, fisrt I want to check the password will confirmation password then store it to database.
this is my view page
<form action ="{{ route('user-create') }}" method="POST" enctype="multipart/form-data" >
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<div class="row mb-3">
<div class="col-md-12">
<div class="form-floating mb-2 mb-md-0">
<input class="form-control" id="inputFirstName" type="text" placeholder="Enter your first name" name="name" />
<label for="inputFirstName">Name </label>
</div>
</div>
</div>
<div class="form-floating mb-3">
<input class="form-control" id="inputEmail" type="email" placeholder="name#example.com" name="email"/>
<label for="inputEmail">Email address</label>
</div>
<div class="row mb-3">
<div class="col-md-6">
<div class="form-floating mb-3 mb-md-0">
<input class="form-control" id="inputPassword" type="password" placeholder="Create a password" name="password" />
<label for="inputPassword">Password</label>
</div>
</div>
<div class="col-md-6">
<div class="form-floating mb-3 mb-md-0">
<input class="form-control" id="inputPasswordConfirm" type="password" placeholder="Confirm password" name="confirmpassword" />
<label for="inputPasswordConfirm">Confirm Password</label>
</div>
</div>
</div>
<div class="mt-4 mb-0">
<div class="d-grid"><button type="submit" class="btn btn-primary">Create account</button></div>
</div>
</form>
Do you have any suggestion of how to fix it? It cant store anything in database, and when I check it using " echo " there is nothing :)
Thank you

The confirmed rule is looking for a field name {field}_confirmation. So if you are trying to confirm the 'password' input it would be looking for a field named password_confirmation. So that input in the form needs to be changed to the name password_confirmation.
You won't need to compare the 2 password fields that are submitted since the confirmed rule has done that for you already (that is what it is for; to confirm that they match).
The Request class is not callable, $request(...). That will throw an error since it isn't callable (there is no __invoke method defined on it to make it callable).
To create the User you can get the fields you need easily with the only method:
$request->only('name', 'email', 'password')
You can add your is_admin value to the array returned from the only call:
User::create($request->only('name', 'email', 'password') + ['is_admin' => true])
You will have to make sure that the is_admin field is "fillable" on the Model.
In general you don't need to be calling request() any where in this method since you have a Request instance injected as $request already.
Also, your form isn't handling a file upload so you don't need enctype="multipart/form-data".

Related

Form Won't Pass Value Pair In Get Request Url After Submission

I'm familiarizing myself with API's Get & Post Request in Laravel. I have a form where an admin can send Points to an external API. Unfortunately, in the documentation the request has to be a GET request and the data which is being submitted has to append to the url
ie: myurl.com/my-end-point?platform_id=value&auth=value...
The issue is, whenever i fill the form and submit the url remains the same:
ie: myurl.com/my-end-point?platform_id=platform_id&auth=auth...
It does not pass the data in the get request.
Controller
public function sendCpdPoints(Request $request)
{
$response = Http::asForm()->get('myurl.com/my-end-point', [
'platform_id' => 'platform_id',
'auth' => 'auth',
'cpd_id' => 'cpd_id',
'registration_number' => 'registration_number',
'certificate' => 'certificate',
]);
dd($response);
}
View (Blade)
<form action="{{url('admin/rewards/points/manual_update/dashboard/store/participants-points') }}" method="POST">
<div class="modal-body">
{{ csrf_field() }}
<div class="form-group">
<label>Platform Id</label>
<input type="text" name="platform_id" id='platform_id' class="form-control" value="123" readonly>
</div>
<div class="form-group">
<label>Authentication Key</label>
<input type="text" name="auth" id='auth' class="form-control" value="123456789" readonly>
</div>
<div class="form-group">
<label>Cpd Id</label>
<input type="text" name="cpd_id" id='cpd_id' class="form-control" placeholder=".ie 587">
</div>
<div class="form-group">
<label>Registration Number</label>
<input type="text" name="registration_number" id='registration_number' class="form-control" placeholder=".ie MDC/PA/RNXXXX">
</div>
<div class="form-group">
<label>Certificate Serial Number</label>
<input type="text" name="certificate" id='certificate' class="form-control" placeholder=".ie 2022-03/001">
</div>
<button type="send" class="btn btn-primary">Send</button>
</div>
</form>
Help is greatly appreciated. As i really want to get better.
You need to pass the value from the form . You can use $request-> from the request facade
You can try this
public function sendCpdPoints(Request $request)
{
$response = Http::asForm()->get('myurl.com/my-end-point', [
'platform_id' => $request->platform_id,
'auth' => $request->auth,
'cpd_id' => $request->cpd_id,
'registration_number' => $request->registration_number,
'certificate' => $request->certificate,
]);
dd($response);
}
Let me see if I understand. Does your backend that handles the request call an external API? If that's the case, the problem is that you're passing strings as an argument. To retrieve the form values try something like:
$request->auth or
$request->get('auth')
If this is not the case, and you simply want to get the form data in your backend, I advise you to do it with JS using AJAX. You can use Fetch or install an external lib like axios to do this.
NOTE: the type of your submit button is incorrect, change it to type="submit"
https://www.w3schools.com/tags/att_button_type.asp

Login Form Not Working Correctly it keeps redirecting to the same page when the users try to access their account

I have an issue with my login form where when I press the login button, the web app just redirects me to the same page. This is first time I'm making a custom login form so it's a little complex for me as I used laravel/ui in my first project. I think the problem is that the model cannot directly access the users table that's in the db. I've linked the user model to the controller but that doesn't help. If anyone can take their time to show me how to connect the login form to the users table or tell me what's wrong with my code. Here's the code that I've written so far for the login.
Login Form
<form method="post" action="/login" enctype="multipart/form-data">
#csrf
<div class="col-md-12 mt-md-0 mt-3">
<label for="email" id="email">Email</label>
<input type="email" name="email" value="{{ old('email') }}" class="form-control" placeholder="E-mail" required>
#error('email')<p class="text-danger"><small>{{$message}}</small></p> #enderror
</div>
<div class="col-md-12 mt-md-0 mt-3">
<label for="password" id="password">Password</label>
<input type="password" name="password" class="form-control" placeholder="Password"required>
#error('password')<p class="text-danger"><small>{{$message}}</small></p> #enderror
</div>
<div class="col-md-12 text-center">
<button type="submit" class="btn btn-primary mb-4 w-50 py-2 fw-bold" >Login</button>
</div>
</form>
Routes
Route::get('login', [SessionsController::class, 'create'])->middleware('guest');
Route::post('login', [SessionsController::class, 'store'])->middleware('guest');
SessionsController
public function store()
{
$attributes = request()->validate([
'email' => 'required|email',
'password' => 'required'
]);
if (! auth()->attempt($attributes)) {
throw ValidationException::withMessages([
'email' => 'Your provided credentials could not be verified.'
]);
}
session()->regenerate();
return redirect('/')->with('success', 'Welcome');
}
I think the problem is that this form is not retrieving the data from the db that's being stored when the user registers an account.

CodeIgniter getMethod() Deprecated and Submit Button not functioning

I practice my CodeIgnitor right now and I'm new to them still. I am doing the inquiry form and wanted to make sure that it checks the form is correctly verified. After clicking on the submit button, It will send the form to a corresponding email.
but I'm having issues saying getMethod() is deprecated and my submit button is not responding too.
In fact, I don't grasp what deprecated means are, and are there anybody who can assist me clarify this part and provides any other approach before using getMethod().
Can you guys check what I did wrong with the submit button too? If you have a better approach to validate the form and send the email to the corresponding that somewhat cleaner. It's also wonderful.
This is my code:-
config/Controller/Contact Controller.php
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
class ContactController extends Controller
{
// CONTACT PAGE
public function contact()
{
//Library
helper(['form']);
//Contact Data Initiate
$contact_data = [];
$data = [
'meta_title' => 'Contact | MFD',
];
//Check request if it is post
if($this->request->getMethod() == 'post'){
// Setting Form Rules
$settings_rule = [
'email' => [
'name' => 'required|min_length[3]|max_length[20]',
'email' => 'required|valid_email',
'subject' => 'required',
],
'msg' => 'required',
];
if($this->validate($settings_rule)){
//Validation true send message successfully sent and return back to the same page
return view('page_templates/contact', $data);
}else {
// Will provide check list of error of the one we create
$contact_data['validation'] = $this->validator;
}
}
return view('page_templates/contact', $data);
}
views/page_templates/contact.php
<div class="col-lg-8 mt-5 mt-lg-0">
<?php if(isset($validation)) : ?>
<div class="error-message">
<?= $validation->listErrors(); ?>
</div>
<?php endif ?>
<form method="post" role="form" class="php-email-form">
<div class="row">
<div class="col-md-6 form-group">
<input type="text" name="name" class="form-control" id="name"
value="<?= set_value('name'); ?>" placeholder="Your Name">
</div>
<div class="col-md-6 form-group mt-3 mt-md-0">
<input type="email" class="form-control" name="email" id="email"
value="<?= set_value('email'); ?>" placeholder="Your Email">
</div>
</div>
<div class="form-group mt-3">
<input type="text" class="form-control" name="subject" id="subject"
value="<?= set_value('subject'); ?>" placeholder="Subject">
</div>
<div class="form-group mt-3">
<textarea class="form-control" name="message" rows="5" placeholder="Message"><?= set_value('msg'); ?></textarea>
</div>
<!-- <div class="my-3">
<div class="loading">Loading</div>
<div class="error-message"></div>
<div class="sent-message">Your message has been sent. Thank you!</div>
</div> -->
<div style="height: 10px;"></div>
<div class="text-left button">
<button type="submit" name="submit">Send Message</button>
</div>
</form>
</div>
Really appreciate it if anyone that can help me with this. Thank you
vscode also notified me the same, and then I added the line below before the controller class and it works fine.
/**
* #property IncomingRequest $request
*/
class ContactController extends Controller{
public function contact(){
}
}
What is the exact deprecation message that you are getting? And which version of CodeIgniter are you using?
Deprecation just means that the interface will be removed in future revisions.
But I just looked at the source and documentation and the method doesn't appear to be deprecated. The optional parameter $upper is deprecated though.
So you would not want to use $this->request->getMethod(TRUE | FALSE) since that wont be supported in the future. But $this->request->getMethod() should be fine.
As for your button problem... You didn't provide enough information.
For the client rendered button to respond to a click event you will need to add a listener. I am guessing you have not. It goes something like this.
<script>
let button = document.querySelector(".button button");
button.addEventListener("click", function(event) {
// Do your work here...
});
</script>
I am using CI4 and having the same issue, but the below solution working fine for me
if($this->request->getMethod() == 'post'){}
change to this
if ($this->request->getPost()) {}
if ($this->request->getGet()) {}

How to develop custom login by auth middleware using laravel

I want to make a custom login system by auth middleware.
I don't have an idea how to do that.
controller
public function dologin(Request $request)
{
$request->validate([
'username' => 'required',
'password' => 'required'
]);
$username = $request->username;
$password = $request->password;
if (Auth::attempt(['username' => $username, 'password' => $password])) {
}
}
Blade view
<form action="{{route('login.action')}}">
<br>
<div class="form-row">
<div class="col">
<label>USERNAME</label>
<input type="text" class="form-control" placeholder="Enter Username" name="username">
</div>
</div>
<!--form-row-->
<br>
<div class="form-row">
<div class="col">
<label>PASSWORD</label>
<input type="password" class="form-control" placeholder="Enter password" name="password">
</div>
</div>
<!--form-row-->
<br>
<div class="form-group">
<input type="submit" name="btnsubmit" class="btn btn-success col-md-3" id="signup-btn" value="Login">
</div>
</form>
Route
// Login
Route::get('/login', 'LoginController#create')->name('login');
Route::get('/login/action', 'LoginController#dologin')->name('login.action');
Create your LoginController by runing this command in terminal:
php artisan make:controller LoginController
Then find your newly created controller under App\Http\Controllers\ and add a the use of Auth at the top of your controller
use Illuminate\Support\Facades\Auth;
Then add your dologin function to the controller and you're ready to go.

PUT/POST in Laravel

I'm brand new to Laravel and am working my way through the [Laravel 6 from Scratch][1] course over at Laracasts. The course is free but I can't afford a Laracasts membership so I can't ask questions there.
I've finished Section 6 of the course, Controller Techniques, and am having unexpected problems trying to extend the work we've done so far to add a few new features. The course has students build pages that let a user show a list of articles, look at an individual article, create and save a new article, and update and save an existing article. The course work envisioned a very simple article containing just an ID (auto-incremented in the database and not visible to the web user), a title, an excerpt and a body and I got all of the features working for that, including updating an existing article and saving it.
The update form sets method to POST but then uses a #METHOD('PUT') directive to tell the browser that it is actually supposed to do a PUT. This worked perfectly in the original code. However, now that I've added two more fields to the form, when I click Submit after editing an existing record, the save fails with this message:
Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The PUT method is not supported for this route. Supported methods: GET, HEAD, POST.
http://localhost:8000/articles
I don't understand why adding two fields to the form would cause this to break. Can someone enlighten me? I added the two new fields/columns to the migration and ran migrate:rollback and migrate. I've also added the new fields/columns to the fillable attribute and added validations for them in the ArticlesController.
Here is my routing:
Route::get('/articles', 'ArticlesController#index');
Route::post('/articles', 'ArticlesController#store');
Route::get('/articles/create', 'ArticlesController#create');
Route::get('/articles/{article}', 'ArticlesController#show');
Route::get('/articles/{article}/edit', 'ArticlesController#edit');
Route::put('/articles/{article}', 'ArticlesController#update');
//Route::delete('/articles/{article}', ArticlesController#destroy');
This is my ArticlesController:
<?php
namespace App\Http\Controllers;
use App\Article;
use Illuminate\Http\Request;
class ArticlesController extends Controller
{
public function index()
{
$articles = Article::latest()->get();
return view ('articles.index', ['articles' => $articles]);
}
public function show(Article $article)
{
return view('articles.show', ['article' => $article]);
}
public function create()
{
return view('articles.create');
}
public function store()
{
//Stores a NEW article
Article::create($this->validateArticle());
return redirect('/articles');
}
public function edit(Article $article)
{
return view('articles.edit', ['article' => $article]);
}
public function update(Article $article)
{
//Updates an EXISTING article
$article->update($this->validateArticle());
return redirect('/articles/', $article->id);
}
public function validateArticle()
{
return request()->validate([
'title' => ['required', 'min:5', 'max:20'],
'author' => ['required', 'min:5', 'max:30'],
'photopath' => ['required', 'min:10', 'max:100'],
'excerpt' => ['required', 'min:10', 'max:50'],
'body' => ['required', 'min:50', 'max:500']
]);
}
public function destroy(Article $article)
{
//Display existing record with "Are you sure you want to delete this? Delete|Cancel" option
//If user chooses Delete, delete the record
//If user chooses Cancel, return to the list of articles
}
}
Here's my edit form, edit.blade.php:
#extends('layout')
#section('content')
<div id="wrapper">
<div id="page" class="container">
<h1>Update Article</h1>
<form method="POST" action="/articles">
#csrf
#method('PUT')
<div class="form-group">
<label class="label" for="title">Title</label>
<div class="control">
<input class="form-control #error('title') errorborder #enderror" type="text" name="title" id="title" value="{{ $article->title }}">
#error('title')
<p class="errortext">{{ $errors->first('title') }}</p>
#enderror
</div>
</div>
<div class="form-group">
<label class="label" for="author">Author</label>
<div class="control">
<input class="form-control #error('author') errorborder #enderror" type="text" name="author" id="author" value="{{ $article->author }}">
#error('title')
<p class="errortext">{{ $errors->first('author') }}</p>
#enderror
</div>
</div>
<div class="form-group">
<label class="label" for="photopath">Path to Photo</label>
<div class="control">
<input class="form-control #error('photopath') errorborder #enderror" type="text" name="photopath" id="photopath" value="{{ $article->photopath }}">
#error('title')
<p class="errortext">{{ $errors->first('photopath') }}</p>
#enderror
</div>
</div>
<div class="form-group">
<label class="label" for="excerpt">Excerpt</label>
<div class="control">
<textarea class="form-control #error('excerpt') errorborder #enderror" name="excerpt" id="excerpt">{{ $article->excerpt }}</textarea>
#error('excerpt')
<p class="errortext">{{ $errors->first('excerpt') }}</p>
#enderror
</div>
</div>
<div class="form-group">
<label class="label" for="body">Body</label>
<div class="control">
<textarea class="form-control #error('body') errorborder #enderror" name="body" id="body">{{ $article->body }}</textarea>
#error('body')
<p class="errortext">{{ $errors->first('body') }}</p>
#enderror
</div>
</div>
<div class="control">
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</form>
</div>
</div>
#endsection
Is there anything else you need to see?
[1]: https://laracasts.com/series/laravel-6-from-scratch/episodes/33?autoplay=true
Your Laravel route is:
Route::put('/articles/{article}', 'ArticlesController#update');
So your form action url should match that uri:
<form action="{{ url('/articles/'.$article->id) }}">
where the {article} parameter is the record id (you can read more about in the docs here).
Then in your controller update() method, you have:
return redirect('/articles/', $article->id);
which means redirect to /articles with status code $article->id (you can read more about in the docs here). I think you are trying to redirect to the show route, which is:
Route::get('/articles/{article}', 'ArticlesController#show');
So change the , (comma) to a . (dot) to concatenate the article id with the uri:
return redirect('/articles/' . $article->id);
The route in the form for /articles, However your route for updating should be /articles/{article}
Try this:
<form method="POST" action="/articles/{{ $article->id }}">

Resources