this is my blade file
#csrf
name
#if ($errors->has('name'))
{{ $errors->first('name') }}
#endif
<div class="form-group col-md-6">
<label>email</label>
<input type="email" name="email" class="form-control" id="email" placeholder="Enter your email" required autofocus>
#if ($errors->has('email'))
<span class="Enter properly">{{ $errors->first('email') }}</span>
#endif
</div>
<div class="form-group col-md-6">
<label>Mobile-no</label>
<input type="text" name="mobile-no" class="form-control" id="mobile_no" placeholder="Enter your mobile no" required>
#if ($errors->has('mobile-no'))
<span class="Enter 10digits">{{ $errors->first('mobile_no') }}</span>
#endif
</div>
<div class="form-group col-md-6">
<label>Password</label>
<input type="password" name="password" class="form-control" id="password" placeholder="Enter your password" required>
#if ($errors->has('password'))
<span class="Enter properly">{{ $errors->first('password') }}</span>
#endif
</div>
<div class="form-group col-md-6">
<label>Confirm-password</label>
<input type="password" name="confirm_password" class="form-control" id="confirm_password" placeholder="Re-enter your password" >
</div>
<div class="form-group col-md-6" align="center">
<button class="btn btn-success" style="width:80px;">Submit</button>
</div>
</div>
</div>
</form>
#endsection
This is my controller file
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\FormController;
use Illuminate\Http\Request;
use Hash;
use Session;
use App\Models\User;
use Illuminate\Support\Facades;
class FormController extends Controller
{
public function index()
{
return view ('login');
}
public function postLogin(Request $request)
{
$request->validate([
'email' => 'required',
'password' => 'required',
]);
$credentials = $request->only('email', 'password');
if (User::attempt($credentials)) {
return redirect()->intended('dashboard')
->withSuccess('Signed in');
}
return redirect("login")->withSuccess('Login details are not valid');
}
public function registration()
{
return view('registration');
}
public function postRegistration(Request $request)
{
$request->validate([
'name' => 'required',
'email' => 'required',
'mobile_no' => 'required',
'password' => 'required|min:6',
'confirm_password' => 'required',
]);
$data = $request->all();
$check = $this->create($data);
return redirect("dashboard")->withSuccess('have signed-in');
}
public function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password'])
]);
}
public function dashboard()
{
if(User::check()){
return view('dashboard');
}
return redirect("login")->withSuccess('are not allowed to access');
}
public function signOut()
{
Session::flush();
User::logout();
return Redirect('login');
}
}
//this is my route file
Route::get('dashboard', [FormController::class, 'dashboard']);
Route::get('login', [FormController::class, 'index'])->name('login');
Route::post('post-login', [FormController::class, 'postLogin'])->name('login.post');
Route::get('registration', [FormController::class, 'registration'])->name('register');
Route::post('post-registration', [FormController::class, 'postRegistration'])->name('register.post');
//this is my migration
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up()
{
Schema::create('customRegistration', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->string('name');
$table->string('email');
$table->integer('mobile_no');
$table->string('password');
$table->string('confirm_password');
$table->timestamps();
});
}
public function down()
{
Schema::drop('form');
}
}
i created simple laravel login & registration form.laravel is not genrating errors. but it is not stored a data into the database i.e any of data will be not stored in database.
Related
I can fill my table with User::create(). It works, but I want fill with class, which I create in migrations. How I can do it? I am beginner at php laravel and can`t find information on this case.
web.php:
<?php
Route::name('user.')->group(function (){
Route::view('/private','private')->middleware('auth')->name('private');
Route::get('/login',function(){
// Проверка на авторизацию пользователя. Если уже авторизован, то редирект на страницу профиля
return view('login');
})->name('login');
Route::post('/login',[\App\Http\Controllers\LoginController::class,'login']);
Route::get('/logout',function(){
Auth::logout();
return redirect('/');
})->name('logout');
Route::get('/registration', function () {
if(Auth::check()){
return redirect(route('user.private'));
}
return view('registration');
})->name('registration');
Route::post('/registration',[\App\Http\Controllers\RegisterController::class,'save']);
});
registration.blade.php:
#extends('layouts.app')
#section('title-block')
Регистрация
#endsection
#section('content')
<h1>Вход</h1>
<form class="col-3 offset-4 border rounded" method="POST" action="{{route('user.registration')}}">
#csrf
<div class="form-group">
<label for="number" class="col-form-label-lg">Имя</label>
<input class="form-control" id="number" name="number" type="text" placeholder="number">
</div>
<div class="form-group">
<label for="surname" class="col-form-label-lg">surname</label>
<input class="form-control" id="surname" name="surname" type="text" placeholder="surname">
</div>
<div class="form-group">
<label for="name" class="col-form-label-lg">Имя</label>
<input class="form-control" id="name" name="name" type="text" placeholder="Имя">
</div>
<div class="form-group">
<label for="password" class="col-form-label-lg">Пароль</label>
<input class="form-control" id="password" name="password" type="password" placeholder="Пароль">
</div>
<div class="form-group">
<button class="btn btn-lg btn-primary" type="submit" name="sendMe" value="1">Войти</button>
</div>
</form>
#endsection
RegisterController.php:
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
class RegisterController extends Controller
{
public function save(Request $request){
if(Auth::check()){
return redirect(route('user.private'));
}
$validateFields = $request->validate([
'number' =>'required',
'password' => 'required',
]);
if(User::where('number',$request['number'])->exists()){
return redirect(route('user.registration'))->withErrors([
'number' => 'Такой пользователь уже зарегистрирован'
]);
}
$user = User::create([
'password' => $request['password'],
'name' => $request['name'],
'surname'=>$request['surname'],
'number'=>$request['number']
]);
if($user){
Auth::login($user);
return redirect(route('user.private'));
}
return redirect(route('user.login'))->withErrors([
'formError' => 'Произошла ошибка при сохранении пользователя'
]);
}
}
Migration file. This file creates the users schema. With this class I want to save users
create_users_table:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users',function (Blueprint $table) {
$table->increments('id');
$table->string('surname',255)->nullable(false);
$table->string('name',255)->nullable(false);
$table->string('number',255)->nullable(false)->unique();
$table->string('father`s name',255)->nullable(false);
$table->string('parent`s number',255)->nullable(false);
$table->string('password',255)->nullable(false);
$table->string('studies',255)->nullable(false);
$table->string('classes',255)->nullable(false);
$table->string('remember_token',100)->nullable(true);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
I am trying to allow users to edit posts, however I keep getting this error:
Property [caption] does not exist on this collection instance. (View: C:\xampp\htdocs\myprojectname\resources\views\posts\edit-post.blade.php)
My edit function in Post Controller is:
use App\Models\Post;
public function edit(Post $post)
{
return view('posts.edit-post', ['post' => $post]);
}
My update function in Post Controller is:
public function update(Post $post, Request $request)
{
$data = request()->validate([
'caption' => 'nullable',
'url' => 'nullable',
'image' => 'nullable',
]);
$updateData = [
'caption' => $data['caption'],
'url' => $data['url'],
];
if (request('image')) {
$imagePath = request('image')->store('uploads', 'public');
$updateData['image'] = $imagePath;
}
auth()->user()->posts()->id()->update($updateData);
return redirect('/users/' . auth()->user()->id);
}
My edit-post.blade.php file code is:
#section('content')
<body class="create_body">
<div class="create_container_div">
<form action="{{('/users/' . auth()->user()->id)}}" enctype="multipart/form-data" method="post">
#csrf
#method('PATCH')
<div class="form-group">
<label for="caption" class="create_caption_label">Post Caption</label>
<div class="create_caption_div">
<input id="caption"
type="text"
class="form-control #error('caption') is-invalid #enderror"
name="caption"
value="{{ old('caption') ?? auth()->user()->posts->caption }}"
autocomplete="caption" autofocus>
#error('caption')
<div class="invalid-feedback-div">
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
</div>
#enderror
</div>
</div>
<div class="form-group">
<label for="url" class="edit_title_label">URL</label>
<div class="edit_url_div">
<input id="url"
type="text"
class="form-control #error('url') is-invalid #enderror"
name="url"
value="{{ old('url') ?? auth()->user()->posts->url }}"
autocomplete="url" autofocus>
#error('url')
<div class="invalid-feedback-div">
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
</div>
#enderror
</div>
</div>
<div class="create_post_image_div">
<label for="image" class="create_image_label">Post Image</label>
<input type="file" class="form-control-file" id="image" name="image">
#error('image')
<div class="invalid-feedback-div">
<strong>{{ $message }}</strong>
</div>
#enderror
<div class="create_post_btn_div">
<button class="create_post_btn">Save Changes</button>
</div>
</div>
</form>
</div>
</body>
#endsection
My create_posts_table migration file is:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->string('caption');
$table->string('url');
$table->string('image');
$table->timestamps();
$table->index('user_id');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
And my Post.php model file is:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
protected $guarded = [];
public function user()
{
return $this->belongsTo(User::class);
}
}
Finally my routes in web.php are:
use App\Http\Controllers\PostsController;
Route::get('/posts/{post}/edit', [PostsController::class, 'edit']);
Route::patch('/posts/{post}', [PostsController::class, 'update'])->name('posts.update');
How can I resolve this issue, and furthermore, how do I allow users to edit posts?
This line is not correct, i don't know if you are coming from some other language, this makes no sense at all for me.
auth()->user()->posts()->id()->update($updateData);
You have the Post already in the context you are, due to it being Model bound in your controller method public function update(Post $post, Request $request), you can use that to just update it. fill() applies you $updateData to the model and save() writes it to the database.
$post->fill($updateData);
$post->save();
As the comments stated, the edit function is missing an id, again you have already bound your model to the method, then just use it.
public function edit(Post $post)
{
return view('posts.edit-post', ['post' => $post]);
}
I want to make Laravel's "remember me" feature. The problem is that, whenever I create a remember_token column, I am unable to log in or register a user, as it gives some unknown error that I cannot find in any way. Also, I have no idea how to apply this functionality with my code.
Login and Registration Form (except that the registration form does not have a checkbox):
<form class="login-form needs-validation" method="POST" action="{{ route('loja.logar') }}" novalidate>
#csrf
<div class="form-group">
<input type="email" id="email" name="email" aria-describedby="emailHelp" placeholder="Email" required>
</div>
<div class="form-group">
<input type="password" id="password" name="password" placeholder="Password" required>
</div>
<div class="custom-control custom-checkbox mr-sm-2">
<input type="checkbox" name="remember" class="custom-control-input" id="remember">
<label class="custom-control-label" for="remember">Remember me</label>
</div>
<button type="submit" id="submit" name="submit">Enviar</button>
</form>
I'm not using Model, just a controller that is the SiteController:
public function logar(Request $req)
{
$data = $req->all();
$user = Auth::attempt(['email' => $data['email'], 'password' => $data['password']]);
$this->validate($req, [
'email' => ['required', 'email'],
'password' => 'required'
]);
if ($user) {
return redirect()->route('loja.index');
} else {
return redirect()->route('loja.login')
->with('status-verification', 'Error. Try again!');
}
}
public function regist(Request $req)
{
$data = $req->all();
$validator = $this->validate($req, [
'email' => [
'required',
'email',
function ($attribute, $value, $fail) {
if (Users::whereEmail($value)->count() > 0) {
echo 1;
}
},
]
]);
if ($validator) {
Users::create([
'email' => $data['email'],
'password' => Hash::make($data['password'])
]);
return redirect()->route('loja.register');
}
}
User Table:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id')->unique();
$table->string('email', 191)->unique();
$table->string('password');
});
}
I am Login my Backend page he is getting error Username and password does not match, But my email id and password are correct in MySQL Server.
What is the problem in my code? Why I don't log in my page. Thank you
AuthController.php
namespace App\Http\Controllers;
use App\Models\Block;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Session;
class AuthController extends Controller
{
public function getLogin(){
return view('login');
}
public function login(Request $request){
// dd($request->all());
if( Auth::attempt(['email' => $request->email, 'password' => $request->password])){
// login code here
return redirect('/');
}
Session::flash('danger', 'Username and password does not match');
return redirect('login');
// login failed here
}
}
'''
LoginBlade.php
'''
</head>
<body>
<div class="limiter">
<div class="container-login100">
<div class="wrap-login100 p-l-55 p-r-55 p-t-65 p-b-50">
<form class="login100-form validate-form" method="POST" action="{{URL::to('login')}}">
#csrf
#include('backend.layouts.alerts')
<span class="login100-form-title p-b-33">
Account Login
</span>
<div class="wrap-input100 validate-input #error('email') is-invalid #enderror " data-validate = "Valid email is required: valid#email.xyz">
<input class="input100" type="email" name="email" placeholder="Email" required>
<span class="focus-input100-1"></span>
<span class="focus-input100-2"></span>
</div>
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
<div class="wrap-input100 rs1 validate-input" data-validate="Password is required" >
<input class="input100 #error('password') is-invalid #enderror" type="password" name="password" placeholder="Password" required>
<span class="focus-input100-1"></span>
<span class="focus-input100-2"></span>
</div>
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
<div class="container-login100-form-btn m-t-20">
<button class="login100-form-btn" value="submit">
Sign in
</button>
</div>
</form>
</div>
</div>
</div>
The code you wrote isn't too far off, The most likely culprit for the issue you are having is how you register or create your user.
This would work provided somewhere in your Registration controller you are hashing the password using bcrypt() or Hash::make()
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class AuthController extends Controller
{
public function getLogin()
{
return view('login');
}
public function login(Request $request)
{
// validate your request
$credentials = $request->validate([
'email' => 'required|string',
'password' => 'required|string',
]);
if (auth()->attempt($credentials)) return redirect('/');
return redirect('login')
->with('danger', 'Username and password does not match');
}
protected function register(Request $request)
{
// validate your request
$data = $request->validate([
'name' => 'required|string',
'email' => 'required|string',
'password' => 'required|string',
]);
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
auth()->login($user);
return redirect('/');
}
}
I have a Laravel registration form (code below). When I press the Submit button, it is supposed to read function register(RegisterRequest $request) in class RegisterController. Instead it returns to the function showRegistrationForm(). The register form appears again and is empty. Assuming that because register does not run, the register request is not completed. How do I complete a registration request?
register.blade.php
<form method="POST" action="{{ route('register.post') }}">
#csrf
<div class="form-group row">
<label for="name" class="col-md-3 col-form-label">{{ __('First Name') }}</label>
<div class="col-md-3">
<input id="name" type="text" class="form-control #error('name') is-invalid #enderror" name="firstname" value="{{ old('name') }}" required autocomplete="name" autofocus>
#error('name')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<label for="name" class="col-md-2 col-form-label">{{ __('Last Name') }}</label>
<div class="col-md-3">
<input id="name" type="text" class="form-control #error('name') is-invalid #enderror" name="lastname" value="{{ old('name') }}" required autocomplete="name" autofocus>
#error('name')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-7 offset-md-3">
<button type="submit" class="btn btn-primary">
{{ __('Register') }}
</button>
</div>
</div>
</form>
web.php routes
Route::group(['middleware' => 'guest'], function () {
// Authentication Routes
Route::get('login', [LoginController::class, 'showLoginForm'])->name('login');
Route::post('login', [LoginController::class, 'login'])->name('login.post');
// Registration Routes
Route::get('register', [RegisterController::class, 'showRegistrationForm'])->name('register');
Route::post('register', [RegisterController::class, 'register'])->name('register.post');
});
RegisterController.php
class RegisterController extends Controller {
use RegistersUsers;
protected $userRepository;
public function __construct(UserRepository $userRepository)
{
$this->userRepository = $userRepository;
}
public function redirectPath()
{
return route(home_route());
}
public function showRegistrationForm()
{
abort_unless(config('access.registration'), 404);
return view('client.auth.register')
->withSocialiteLinks((new SocialiteHelper)->getSocialLinks());
}
public function register(RegisterRequest $request)
{
abort_unless(config('access.registration'), 404);
$user = $this->userRepository->create($request->only('first_name', 'last_name', 'email', 'password'));
if (config('access.users.confirm_email') || config('access.users.requires_approval')) {
event(new UserRegistered($user));
return redirect($this->redirectPath())->withFlashSuccess(
config('access.users.requires_approval') ?
__('exceptions.client.auth.confirmation.created_pending') :
__('exceptions.client.auth.confirmation.created_confirm')
);
}
auth()->login($user);
event(new UserRegistered($user));
return redirect($this->redirectPath());
}
}
RegisterRequest.php
class RegisterRequest extends FormRequest{
public function authorize()
{
return true;
}
public function rules()
{
return [
'first_name' => ['required', 'string', 'max:191'],
'last_name' => ['required', 'string', 'max:191'],
'email' => ['required', 'string', 'email', 'max:191', Rule::unique('users')],
'password' => ['required', 'string', 'min:6', 'confirmed'],
'g-recaptcha-response' => ['required_if:captcha_status,true', 'captcha'],
];
}
public function messages()
{
return [
'g-recaptcha-response.required_if' => __('validation.required', ['attribute' => 'captcha']),
];
}
}