How to save user restriction in Laravel 5? - php

Can anyone help me with this error? I am making an application, I am using the Laravel Framework version 5.8.35.
ERROR :
Argument 1 passed to App\Http\Controllers\Auth\RegisterController::validator() must be an instance of Illuminate\Http\Request
Register Controller :
The idea of ​​control is to control the sending of data between the view and the database. This controller controls the application's remit.
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
use RegistersUsers;
protected $redirectTo = '/home';
public function __construct()
{
$this->middleware('guest');
}
protected function validator(Request $request)
{
$this->validate($request, [
'nome' => 'required|max:255',
'sobrenome' => 'required|max:255',
'email' => 'required|email|unique:users,email|max:255',
'cpf' => 'required|min:11|unique:users,cpf',
'rg' => 'required|min:7|unique:users,rg',
'telefone' => 'required',
'celular' => 'required',
'rua' => 'required|max:255',
'bairro' => 'required|max:255',
'complemento' => 'max:255',
'numero' => 'required',
'cep' => 'required|min:8',
'datanascimento' => 'required|date|before:today',
'password' => 'required|min:8|confirmed|max:60',
]);
$user = User::create(request([
'nome',
'sobrenome',
'email',
'cpf',
'rg',
'telefone',
'celular',
'rua',
'bairro',
'complento',
'numero',
'cep',
'datanascimento',
'password'
]));
auth()->login($user);
return redirect()->to('/home');
}
}
View Register:
The idea of ​​the view is to show the user in a friendlier way how to register to use the system.
#section('content')
<link href="{{ asset('css/sb-admin-2.min.css')}}" rel="stylesheet">
<div class="form-horizontal">
{{Form::model(['route' => 'register', 'method' => 'post'])}}
<div class="form-group">
{{Form::label('nome', 'Nome:',['class' => 'col-lg-2 control-label'])}}
{{Form::text('nome',null,['class' => 'col-lg-8 form'])}}
#if ($errors->has('nome'))
{{$errors->first('nome')}}
#endif
</div>
<div class="form-group">
{{Form::label('sobrenome', 'Sobrenome:',['class' => 'col-lg-2 control-label'])}}
{{Form::text('sobrenome',null,['class' => 'col-lg-8 form'])}}
#if ($errors->has('nome'))
{{$errors->first('nome')}}
#endif
</div>
<div class="form-group">
{{Form::label('datanascimento', 'Data de Nascimento:',['class' => 'col-lg-2 control-label'])}}
{{Form::date('datanascimento',null,['class' => 'col-lg-8 form'])}}
#if ($errors->has('datanascimento'))
{{$errors->first('datanascimento')}}
#endif
</div>
<div class="form-group">
{{Form::label('cpf', 'CPF:',['class' => 'col-lg-2 control-label'])}}
{{Form::text('cpf',null,['class' => 'col-lg-8 form'])}}
#if ($errors->has('cpf'))
{{$errors->first('cpf')}}
#endif
</div>
<div class="form-group">
{{Form::label('rg', 'RG:',['class' => 'col-lg-2 control-label'])}}
{{Form::text('rg',null,['class' => 'col-lg-8 form'])}}
#if ($errors->has('rg'))
{{$errors->first('rg')}}
#endif
</div>
<div class="form-group">
{{Form::label('telefone', 'Telefone:',['class' => 'col-lg-2 control-label'])}}
{{Form::text('telefone',null,['class' => 'col-lg-8 form'])}}
#if ($errors->has('telefone'))
{{$errors->first('telefone')}}
#endif
</div>
<div class="form-group">
{{Form::label('celular', 'Celular:',['class' => 'col-lg-2 control-label'])}}
{{Form::text('celular',null,['class' => 'col-lg-8 form'])}}
#if ($errors->has('celular'))
{{$errors->first('celular')}}
#endif
</div>
<div class="form-group">
{{Form::label('rua', 'Rua:',['class' => 'col-lg-2 control-label'])}}
{{Form::text('rua',null,['class' => 'col-lg-8 form'])}}
#if ($errors->has('rua'))
{{$errors->first('rua')}}
#endif
</div>
<div class="form-group">
{{Form::label('bairro', 'Bairro:',['class' => 'col-lg-2 control-label'])}}
{{Form::text('bairro',null,['class' => 'col-lg-8 form'])}}
#if ($errors->has('bairro'))
{{$errors->first('bairro')}}
#endif
</div>
<div class="form-group">
{{Form::label('complemento', 'Complemento:',['class' => 'col-lg-2 control-label'])}}
{{Form::text('complemento',null,['class' => 'col-lg-8 form'])}}
#if ($errors->has('complemento'))
{{$errors->first('complemento')}}
#endif
</div>
<div class="form-group">
{{Form::label('numero', 'Número:',['class' => 'col-lg-2 control-label'])}}
{{Form::text('numero',null,['class' => 'col-lg-8 form'])}}
#if ($errors->has('numero'))
{{$errors->first('numero')}}
#endif
</div>
<div class="form-group">
{{Form::label('cep', 'CEP:',['class' => 'col-lg-2 control-label'])}}
{{Form::text('cep',null,['class' => 'col-lg-8 form'])}}
#if ($errors->has('cep'))
{{$errors->first('cep')}}
#endif
</div>
<div class="form-group">
{{Form::label('email', 'Email:',['class' => 'col-lg-2 control-label'])}}
{{Form::text('email',null,['class' => 'col-lg-8 form'])}}
#if ($errors->has('email'))
{{$errors->first('email')}}
#endif
</div>
<div class="form-group">
{{Form::label('password', 'Senha:',['class' => 'col-lg-2 control-label'])}}
{{Form::password('password',['class' => 'col-lg-8 form', 'type' => 'password'])}}
#if ($errors->has('password'))
{{$errors->first('password')}}
#endif
</div>
<div class="form-group">
{{Form::label('password_confirmation', 'Confirmação Senha:',['class' => 'col-lg-2 control-label'])}}
{{Form::password('password_confirmation',['class' => 'col-lg-8 form'])}}
#if ($errors->has('password_confirmation'))
{{$errors->first('password_confirmation')}}
#endif
</div>
<div class="form-group">
{{Form::reset('Limpar', array('class' => 'btn btn-danger limpar'))}}
{{Form::submit('Salvar',array('class'=> 'btn btn-success salvar', 'id' => 'validar'))}}
{{Form::close()}}
</div>
</div>
#endsection

The validator function you're overriding expects parameter 1 to be an array and you're passing a Request object to it through dependency injection
Change the parameter to an array and use the request() helper function to get the request object instead
protected function validator(array $data)
{
$this->validate(request(), [
// rest of code
 Explanation
The App\Http\Controllers\Auth\RegisterController class is using the trait Illuminate\Foundation\Auth\RegistersUsers so any missing function like say register are going to be executed there.
Let's take a look here
/**
* Handle a registration request for the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function register(Request $request)
{
$this->validator($request->all())->validate(); // <-- Here
event(new Registered($user = $this->create($request->all())));
$this->guard()->login($user);
return $this->registered($request, $user)
?: redirect($this->redirectPath());
}
We're passing the $request->all() which is an array, to the validator by default which means the function validator only accepts an array as
a parameter
Which is coming from vendor/laravel/framework/src/Illuminate/Foundation/helpers.php here
if (!function_exists('validator')) {
/**
* Create a new Validator instance.
*
* #param array $data
* #param array $rules
* #param array $messages
* #param array $customAttributes
* #return \Illuminate\Contracts\Validation\Validator|\Illuminate\Contracts\Validation\Factory
*/
function validator(array $data = [], array $rules = [], array $messages = [], array $customAttributes = [])
{
$factory = app(ValidationFactory::class);
if (func_num_args() === 0) {
return $factory;
}
return $factory->make($data, $rules, $messages, $customAttributes);
}
}
And it explictly states a requirement for parameter 1 to be an array
I hope this helps

Related

Laravel: Too few arguments to function when I want to update my database

I have to develop a reservation system for a hotel.
You first have to create a user and than you can make a reservation.
There is an option to edit the registered users but that is the part where I'm stuck.
I follow a very good tutorial but at the moment I can't figure out my error from his video or the internet or documentation..
I've used the post method to insert new data inside my database but to edit the data and update it, I have to use the put method. But it gives an error "Too few arguments in my function .. 1 passed in and 2 expected".
I am aware I have to cache the routes at every change!!
This is my controller:
public function store(Request $request)
{
$guest = Guest::create
([
'titel' => $request->input('title'),
'voornaam' => $request->input('fname'),
'achternaam' => $request->input('sname'),
'adres' => $request->input('address'),
'postcode' => $request->input('zipcode'),
'stad' => $request->input('city'),
'provincie' => $request->input('provincie'),
'email' => $request->input('email')
]);
return redirect('./clients.html');
}
public function edit($id)
{
$guest = Guest::find($id);
return view('edit')->with('guest', $guest);
}
public function update(Request $request, $id)
{
$guest = Guest::where('id', $id)
->update([
'titel' => $request->input('title'),
'voornaam' => $request->input('fname'),
'achternaam' => $request->input('sname'),
'adres' => $request->input('address'),
'postcode' => $request->input('zipcode'),
'stad' => $request->input('city'),
'provincie' => $request->input('provincie'),
'email' => $request->input('email')
]);
}
These are my routes:
Route::get('/', [PagesController::class, 'home']);
Route::get('/home.html', [PagesController::class, 'home']);
Route::get('/clients.html', [GuestsController::class, 'saveGuests']);
Route::post('/clients.html', [GuestsController::class, 'store']);
Route::put('/clients.html', [GuestsController::class, 'update']);
Route::get('/reservations.html', [PagesController::class, 'reservations']);
Route::get('/clients_new.html', [GuestsController::class, 'newclients']);
Route::get('/clients/{id}/edit.html', [GuestsController::class, 'edit']);
Route::get('/reservations_new.html', [PagesController::class, 'newReservations']);
And the file I have make the changes is (using the post method at first but inserted a put method):
<form action="/clients.html" method="POST" class="w-3/12 m-auto flex flex-col justify-evenly items-center text-xl">
#csrf
#method('PUT')
<div class="medium-6 columns py-4 text-3xl w-full flex flex-row items-center justify-between">
<label class="font-semibold">Titel</label>
<select name="title" class="w-22 border-solid border-2 border-grey-200 rounded-lg bg-gray-100 p-2" value="{{ $guest->titel }}">
<option value="Mr." selected="selected">Mr.</option>
<option value="Ms.">Mw.</option>
<option value="Mrs.">Juf.</option>
<option value="Dr.">Dr.</option>
</select>
</div>
<div class="medium-6 columns m-auto py-4 text-3xl w-full flex flex-row items-center justify-between">
<label class="font-semibold">Voornaam</label>
<input name="fname" type="text" class="border-solid border-2 border-grey-200 rounded-lg bg-gray-100 p-2 " value="{{ $guest->voornaam }}">
</div>
<div class="medium-6 columns m-auto py-4 text-3xl w-full flex flex-row items-center justify-between">
<label class="font-semibold">Achternaam</label>
<input name="sname" type="text" class="border-solid border-2 border-grey-200 rounded-lg bg-gray-100 p-2" value="{{ $guest->achternaam }}">
</div>
Route::put('/clients/{id}', [GuestsController::class, 'update']);
Route::get('/clients/{id}/edit', [GuestsController::class, 'edit']);
Controller functions:
public function edit($id)
{
$guest = Guest::find($id);
return view('edit',['guest'=> $guest]);
}
public function update(Request $request, $id)
{
$guest = Guest::where('id', $id)
->update([
'titel' => $request->input('title'),
'voornaam' => $request->input('fname'),
'achternaam' => $request->input('sname'),
'adres' => $request->input('address'),
'postcode' => $request->input('zipcode'),
'stad' => $request->input('city'),
'provincie' => $request->input('provincie'),
'email' => $request->input('email')
]);
}
in the form:
<form action="{{url("clients",$guest->id)}}" method="POST" class="w-3/12 m-auto flex flex-col justify-evenly items-center text-xl">
also i would encourage you to check the documentation for Laravel Validation and Routing
Use this code for routes :
Route::put('/clients/{id}', [GuestsController::class, 'update']);
Route::get('/clients/{id}/edit', [GuestsController::class, 'edit']);
Use this code for Controller: ‌
public function edit($id)
{
$guest = Guest::query()->find($id);
return view('edit',['guest'=> $guest]);
}
public function update(Request $request, $id)
{
$guest = Guest::query()->where('id', $id)->first();
if (!$guest){
Redirect()->back()->withErrors(['msg' => 'guest not found']);
}
$guest->update([
'titel' => $request->input('title'),
'voornaam' => $request->input('fname'),
'achternaam' => $request->input('sname'),
'adres' => $request->input('address'),
'postcode' => $request->input('zipcode'),
'stad' => $request->input('city'),
'provincie' => $request->input('provincie'),
'email' => $request->input('email')
]);
return redirect()
->action([GuestsController::class, 'edit'])
->with('success', 'Product updated successfully');
}
in form :
<form action="{{url("clients",$guest->id)}}" method="POST" class="w-3/12 m-auto flex flex-col justify-evenly items-center text-xl">
Use this code to display errors when updating: ‌
#if($errors->any())
<h4>{{$errors->first()}}</h4>
#endif
I hope it will be useful

What makes the "Add article" form in this Laravel 8 application fail?

I am making a blogging application with Laravel 8 and Bootstrap 5.
I run into a problem with adding an article into the articles table.
In the migration file that generated the articles table, I have:
public function up() {
Schema::create('articles', function (Blueprint $table) {
$table->id();
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
$table->unsignedInteger('category_id');
$table->foreign('category_id')->references('id')->on('catergories');
$table->string('title');
$table->string('slug');
$table->string('short_description');
$table->longText('content');
$table->tinyInteger('featured')->default('0');
$table->string('image')->nullable();
$table->timestamps();
});
}
In the Article model, I have:
class Article extends Model {
use HasFactory;
protected $fillable = [
'user_id',
'category_id',
'title',
'slug',
'short_description',
'content',
'featured',
'image',
];
// Join users to articles
public function user() {
return $this->belongsTo(User::class);
}
// Join categories to articles
public function category() {
return $this->belongsTo(ArticleCategory::class);
}
}
In the controller, I have:
namespace App\Http\Controllers\Dashboard;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use App\Models\ArticleCategory;
use App\Models\Article;
use Illuminate\Http\Request;
class ArticleController extends Controller {
private $rules = [
'category_id' => 'required|exists:article_categories,id',
'title' => 'required|string|max:255',
'short_description' => 'required|string|max:255',
'image' => 'image|mimes:jpeg,png,jpg|max:2048',
'content' => 'required|string',
'featured' => 'required'
];
private $messages = [
'category_id.required' => 'Please pick a category for the article',
'title.required' => 'Please provide a title for the article',
'short_description.required' => 'The article needs a short description',
'content.required' => 'Please add content'
];
public function categories() {
return ArticleCategory::all();
}
public function index() {
$articles = Article::paginate(10);
return view('dashboard/articles',
['articles' => $articles]
);
}
public function create() {
// Load the view and populate the form with categories
return view('dashboard/add-article',
['categories' => $this->categories()]
);
}
public function save(Request $request) {
// Validate form (with custom messages)
$validator = Validator::make($request->all(), $this->rules, $this->messages);
if ($validator->fails()) {
return redirect()->back()->withErrors($validator->errors())->withInput();
}
$fields = $validator->validated();
// Upload article image
$current_user = Auth::user();
if (isset($request->image)) {
$imageName = md5(time()) . $current_user->id . '.' . $request->image->extension();
$request->image->move(public_path('images/articles'), $imageName);
}
// Data to be added
$form_data = [
'user_id' => Auth::user()->id,
'category_id' => $fields['category_id'],
'title' => $fields['title'],
'slug' => Str::slug($fields['title'], '-'),
'short_description' => $fields['short_description'],
'content' => $fields['content'],
'image' => $fields['image'],
'featured' => $fields['featured']
];
// Insert data in the 'articles' table
$query = Article::create($form_data);
if ($query) {
return redirect()->route('dashboard.articles')->with('success', 'Article added');
} else {
return redirect()->back()->with('error', 'Adding article failed');
}
}
}
The form:
<form method="POST" action="{{ route('dashboard.articles.add') }}" enctype="multipart/form-data" novalidate>
#csrf
<div class="row mb-2">
<label for="title" class="col-md-12">{{ __('Title') }}</label>
<div class="col-md-12 #error('title') has-error #enderror">
<input id="title" type="text" placeholder="Title" class="form-control #error('title') is-invalid #enderror" name="title" value="{{ old('title') }}" autocomplete="title" autofocus>
#error('title')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row mb-2">
<label for="short_description" class="col-md-12">{{ __('Short description') }}</label>
<div class="col-md-12 #error('short_description') has-error #enderror">
<input id="short_description" type="text" placeholder="Short description" class="form-control #error('short_description') is-invalid #enderror" name="short_description" value="{{ old('short_description') }}" autocomplete="short_description" autofocus>
#error('short_description')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row mb-2">
<label for="category" class="col-md-12">{{ __('Category') }}</label>
<div class="col-md-12 #error('category_id') has-error #enderror">
<select name="category_id" id="category" class="form-control #error('category_id') is-invalid #enderror">
<option value="0">Pick a category</option>
#foreach($categories as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
</select>
#error('category_id')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row mb-2">
<div class="col-md-12 d-flex align-items-center switch-toggle">
<p class="mb-0 me-3">Featured article?</p>
<input class="mt-1" type="checkbox" name="featured" id="featured">
<label class="px-1" for="featured">{{ __('Toggle') }}</label>
</div>
</div>
<div class="row mb-2">
<label for="image" class="col-md-12">{{ __('Article image') }}</label>
<div class="col-md-12 #error('image') has-error #enderror">
<input type="file" name="image" id="file" class="file-upload-btn">
#error('image')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row mb-2">
<label for="content" class="col-md-12">{{ __('Content') }}</label>
<div class="col-md-12 #error('content') has-error #enderror">
<textarea name="content" id="content" class="form-control #error('content') is-invalid #enderror" placeholder="Content" cols="30" rows="6">{{ old('content') }}</textarea>
#error('content')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row mb-0">
<div class="col-md-12">
<button type="submit" class="w-100 btn btn-primary">
{{ __('Save') }}
</button>
</div>
</div>
</form>
The routes:
// Article routes
Route::group(['prefix' => 'articles'], function() {
Route::get('/', [ArticleController::class, 'index'])->name('dashboard.articles');
Route::get('/new', [ArticleController::class, 'create'])->name('dashboard.articles.new');
Route::post('/add', [ArticleController::class, 'save'])->name('dashboard.articles.add');
});
The problem:
Even though the form passes validation, and a redirect occurs, the record is not actually added to the articles table.
Laravel throws the error General error: 1366 Incorrect integer value: 'on' for column 'featured' at row 1.
What is my mistake?
When dealing with checkboxes you need to know that;
a) you cannot use required since the checkbox is not sent with the form data if it is unchecked.
b) the default value is 'on' but actually, the presence of the field in the data means it was checked so what I normally do is like;
'featured' => $request->has('featured')
this will return a boolean true or false, suitable for storing in your db
So you could write
// Turn the 'featured' field value into a tiny integer
//$fields['featured'] = $request->get('featured') == 'on' ? 1 : 0;
// If no image is uploaded, use default.jpg
$fields['image'] = $request->get('image') == '' ? 'default.jpg' : $imageName;
// Data to be added
$form_data = [
'user_id' => Auth::user()->id,
'category_id' => $fields['category_id'],
'title' => $fields['title'],
'slug' => Str::slug($fields['title'], '-'),
'short_description' => $fields['short_description'],
'content' => $fields['content'],
'featured' => $request->has('featured'),
'image' => $fields['image']
];
Your column is defined as a tinyInteger that can only accept a single digit, but you seem to be passing a string on to it.
$table->tinyInteger('featured')->default('0');
General error: 1366 Incorrect integer value: 'on' for column
'featured' at row 1
Try setting the value of your checkbox to 1.
<input class="mt-1" type="checkbox" name="featured" id="featured" value="1">
Edit, make sure to add boolean to your validation rules after adding the value to your input element.
private $rules = [
'category_id' => 'required|exists:article_categories,id',
'title' => 'required|string|max:255',
'short_description' => 'required|string|max:255',
'image' => 'image|mimes:jpeg,png,jpg|max:2048',
'content' => 'required|string',
'featured' => 'required|boolean'
];
In case it helps anyone, here is the working code for creating an article:
The routes:
// Article routes
Route::group(['prefix' => 'articles'], function() {
Route::get('/', [ArticleController::class, 'index'])->name('dashboard.articles');
Route::get('/new', [ArticleController::class, 'create'])->name('dashboard.articles.new');
Route::post('/add', [ArticleController::class, 'save'])->name('dashboard.articles.add');
});
In the controller:
namespace App\Http\Controllers\Dashboard;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use App\Models\ArticleCategory;
use App\Models\Article;
use Illuminate\Http\Request;
class ArticleController extends Controller
{
private $rules = [
'category_id' => 'required|exists:article_categories,id',
'title' => 'required|string|max:255',
'short_description' => 'required|string|max:255',
'image' => 'image|mimes:jpeg,png,jpg|max:2048',
'content' => 'required|string'
];
private $messages = [
'category_id.required' => 'Please pick a category for the article',
'title.required' => 'Please provide a title for the article',
'short_description.required' => 'The article needs a short description',
'content.required' => 'Please add content'
];
public function categories() {
return ArticleCategory::all();
}
public function index() {
$articles = Article::orderBy('id', 'desc')->paginate(10);
return view('dashboard/articles',
['articles' => $articles]
);
}
public function create() {
// Load the view and populate the form with categories
return view('dashboard/add-article',
['categories' => $this->categories()]
);
}
public function save(Request $request) {
// Validate form (with custom messages)
$validator = Validator::make($request->all(), $this->rules, $this->messages);
if ($validator->fails()) {
return redirect()->back()->withErrors($validator->errors())->withInput();
}
$fields = $validator->validated();
// Upload article image
$current_user = Auth::user();
if (isset($request->image)) {
$imageName = md5(time()) . $current_user->id . '.' . $request->image->extension();
$request->image->move(public_path('images/articles'), $imageName);
}
// Turn the 'featured' field value into a tiny integer
$fields['featured'] = $request->get('featured') == 'on' ? 1 : 0;
// If no image is uploaded, use default.jpg
$fields['image'] = $request->get('image') == '' ? 'default.jpg' : $imageName;
// Data to be added
$form_data = [
'user_id' => Auth::user()->id,
'category_id' => $fields['category_id'],
'title' => $fields['title'],
'slug' => Str::slug($fields['title'], '-'),
'short_description' => $fields['short_description'],
'content' => $fields['content'],
'featured' => $fields['featured'],
'image' => $fields['image']
];
// Insert data in the 'articles' table
$query = Article::create($form_data);
if ($query) {
return redirect()->route('dashboard.articles')->with('success', 'Article added');
} else {
return redirect()->back()->with('error', 'Adding article failed');
}
}
}

Why is the section of my view disappears?

I have a view made with livewire and it contains two dynamically add sections for spoken languages and the other one for courses and certificates. The language section was working fine until I added the add certificates section. now when the user clicks on the add section for the certificate section to add a new one, one of the added language sections disappears and then will appear again once you add another one. I guess it will appear again once the view re-renders. I have been going back and force moving functions around from render method to update/updated/hydrate/dehydrate but got no luck. at first, I thought it had something to do with the $loop->index that I use in my view but after changing that I realized it was not it. I'm hitting a dead-end here and can't figure out what's going on here.
I also made a screen record of what is happening so it might help:
https://drive.google.com/file/d/1Hq2wTKcPvhs05SKFMICaRoOAzpSyj9Iz/view?usp=sharing
View section:
<!-- language section -->
<div class="card card-profile shadow-sm mt-4">
<div class="px-4 mt-4 mb-4">
<div class="h5 font-weight-bold mb-4">Spoken languages</div>
<div class="heading text-muted mb-4">you only can add 3 languages to your profile.</div>
#foreach ($languages as $lindex => $language)
<div class="card card-body mb-4" wire:key="{{ $lindex }}">
<div class="text-left"><span class="fa fa-trash text-gray language-delete" wire:click="removeLanguage({{ $lindex }}, {{ !empty($language['id']) ? $language['id'] : 0 }})"></span></div>
<div class="row">
<div class="form-group col-md-6">
<label class="" for="languageName">language</label>
<select class="form-control form-control-alternative" name="language-name" {{-- id="languageName" --}} wire:model="languages.{{ $lindex }}.language_name">
<option value="" class="form-control" selected disabled>select language</option>
#foreach ($language_names as $name)
<option value="{{ $name->abbreviation }}" class="form-control">{{ $name->language }}</option>
#endforeach
</select>
</div>
<div class="form-group col-md-6">
<label class="" for="languageProficiency">proficiency level</label>
<select class="form-control form-control-alternative" name="language-proficiency" {{-- id="languageProficiency" --}} wire:model="languages.{{ $lindex }}.language_level">
<option value="" class="form-control" selected disabled>proficiency level</option>
#foreach ($language_levels as $level)
<option value="{{ $level->level }}" class="form-control">{{ $level->name }}</option>
#endforeach
</select>
</div>
</div>
</div>
#endforeach
#error('languages.*.language_level')
<small class="text-warning">{{ $message }}</small>
#enderror
#error('languages.*.language_language')
<small class="text-warning">{{ $message }}</small>
#enderror
#if (count($languages) < 3)
<div class="row">
<div class="col-md-12">
<button type="button" class="btn btn-outline-secondary btn-round btn-block" wire:click="addLanguage"><span class="btn-inner--icon"><i class="fa fa-plus fa-2x"></i></span></button>
</div>
</div>
#endif
</div>
</div>
<!-- end language section -->
<!-- other certificates section -->
<div class="card card-profile shadow-sm mt-4">
<div class="px-4 mt-4 mb-4">
<div class="h5 font-weight-bold mb-4">Other related certificates</div>
<div class="heading text-muted mb-4">if you have other related certificates in your files you can add then here.</div>
#foreach ($certificates as $cindex => $certificate)
<div class="card card-body mb-4" wire:key="{{ $cindex }}">
<div class="row">
<div class="form-group col-md-6">
<label class="" for="other-certificates-name">certificate name</label>
<input type="text" class="form-control form-control-alternative" placeholder="" name="ptherCertificatesName">
</div>
<div class="form-group col-md-6">
<label class="" for="other-certificates-school-name">School name</label>
<input type="text" class="form-control form-control-alternative" placeholder="" name="otherCertificatesSchoolName">
</div>
<div class="form-group col-md-6">
<label class="" for="other-certificates-verification-link">URL<small>(optional)</small></label>
<input type="text" class="form-control form-control-alternative text-left" placeholder="" name="otherCertificatesVerificationLink">
</div>
<div class="form-group col" dir="ltr">
<label class="" for="other-certificates-grad-date" dir="rtl">finished date</label>
<div class="input-group input-group-alternative">
<div class="input-group-prepend">
<span class="input-group-text"><i class="ni ni-calendar-grid-58"></i></span>
</div>
<input type="text" class="form-control form-control-alternative datePicker" placeholder="" name="otherCertificatesGradDate" value="">
</div>
</div>
</div>
</div>
#endforeach
#if (count($certificates) < 5)
<div class="row">
<div class="col-md-12">
<button type="button" class="btn btn-outline-secondary btn-round btn-block" wire:click="addCertificate"><span class="btn-inner--icon"><i class="fa fa-plus fa-2x"></i></span></button>
</div>
</div>
#endif
</div>
</div>
<!-- end other certificates section -->
Livewire component controller:
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\CityName;
use App\Models\Language;
use App\Models\LanguageLevel;
use App\Models\User;
use App\Models\UserLanguage;
use App\Models\UserProfile;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Auth;
class UserInfo extends Component
{
public $name;
public $email;
public $phone;
public $states = [];
public $selectedstate;
public $cities = [];
public $selectedcity;
public $jobTitle;
public $aboutMe;
public $employer;
public $position;
public $edu_course;
public $edu_school;
public $edu_level;
public $edu_start_date;
public $edu_end_date;
public $employment_looking;
public $employment_hired;
public $twitter;
public $linkedin;
public $github;
public $instagram;
public $website;
public $languages = [];
public $language_names;
public $language_levels;
public $languageToDelete = [];
public $certificates = [];
public $certificate_name;
public $certificate_school;
public $certificate_link;
public $certificate_date;
public $certificateToDelete = [];
public $skillsQuery;
public $skillResults;
public $skills;
public function render()
{
$this->retriveStates();
$this->retriveCities();
$this->retriveLanguages();
return view('livewire.user-info');
}
public function retriveStates()
{
$this->states = CityName::distinct()->get(['state']);
}
public function retriveCities()
{
$this->cities = CityName::where('state', $this->selectedstate)->get(['city']);
}
public function updatedSkillsQuery()
{
$this->skillResults = $this->skills->where('name', 'like', $this->skillsQuery) ?? collect();
}
public function retriveLanguages()
{
$this->language_names = Language::all();
$this->language_levels = LanguageLevel::all();
}
public function addLanguage()
{
if (count($this->languages) <= 3)
{
array_push($this->languages, ['language_name'=>'', 'language_level'=>'', 'id'=>'']);
}
else
{
$this->sweetAlert('error', 'you only can add 3 languages to your profile.');
}
}
public function getUserLanguages()
{
$this->languages = auth()->user()->userLanguages->toArray();
}
public function removeLanguage($languagePosition, $languageId)
{
if (isset($languageId))
{
if ($languageId == 0)
{
array_splice($this->languages, $languagePosition, 1);
}
else
{
array_push($this->languageToDelete, $languageId);
array_splice($this->languages, $languagePosition, 1);
}
}
}
public function addCertificate()
{
if (count($this->certificates) <= 5)
{
array_push($this->certificates, ['name'=>'', 'school'=>'', 'link'=>'', 'date'=>'', 'id'=>'']);
/* dd($this->languages); */
}
else
{
$this->sweetAlert('error', 'you only can add 5 certificates to your profile.');
}
}
public function mount()
{
$this->skills = collect([
['name' => 'vue'],
['name' => 'vue'],
['name' => 'vue'],
['name' => 'laravel'],
['name' => 'laravel'],
['name' => 'laravel'],
]);
$this->skillResults= [];
$this->skillsQuery = '';
/* $this->retriveLanguages();
$this->retriveStates();
$this->retriveCities(); */
$this->getUserLanguages();
$this->name = auth()->user()->name;
$this->email = auth()->user()->email;
$this->phone = auth()->user()->phone;
$this->selectedstate = auth()->user()->userprofile->state;
$this->selectedcity = auth()->user()->userprofile->city;
$this->jobTitle = auth()->user()->userprofile->job_title;
$this->aboutMe = auth()->user()->userprofile->about_me;
$this->employer = auth()->user()->userprofile->employer;
$this->position = auth()->user()->userprofile->position;
$this->edu_course = auth()->user()->userprofile->edu_course;
$this->edu_school = auth()->user()->userprofile->edu_school;
$this->edu_level = auth()->user()->userprofile->edu_level;
$this->edu_start_date = auth()->user()->userprofile->edu_start_date;
$this->edu_end_date = auth()->user()->userprofile->edu_end_date;
$this->employment_looking = auth()->user()->userprofile->employment_looking;
$this->employment_hired = auth()->user()->userprofile->employment_hired;
$this->twitter = auth()->user()->userprofile->twitter;
$this->linkedin = auth()->user()->userprofile->linkedin;
$this->github = auth()->user()->userprofile->github;
$this->instagram = auth()->user()->userprofile->instagram;
$this->website = auth()->user()->userprofile->website;
}
public function rules()
{
return [
'name' => ['required', 'string', 'max:250'],
'email' => [
'required',
'email',
'max:250',
Rule::unique('users')->ignore(auth()->id()),
],
'phone' => ['required', 'digits:11'],
'selectedstate' => 'required',
'selectedcity' => 'required',
'jobTitle' => ['required', 'string', 'max:250'],
'aboutMe' => ['required', 'string', 'max:250'],
'employer' => ['string', 'max:250'],
'position' => ['string', 'max:250'],
'edu_course' => ['nullable', 'string', 'max:250'],
'edu_school' => ['nullable', 'string', 'max:250'],
'edu_level' => ['nullable', 'string', 'max:250'],
'edu_start_date' => ['nullable', 'string'],
'edu_end_date' => ['nullable', 'string'],
'employment_looking' => ['nullable', 'boolean'],
'employment_hired' => ['nullable', 'boolean'],
'twitter' => ['nullable', 'string', 'max:250'],
'linkedin' => ['nullable', 'string', 'max:250'],
'github' => ['nullable', 'string', 'max:250'],
'instagram' => ['nullable', 'string', 'max:250'],
'website' => ['nullable', 'string', 'max:250'],
'languages.*.language_name' => ['required', 'exists:App\Models\Language,abbreviation'],
'languages.*.language_level' => ['required', 'exists:App\Models\LanguageLevel,level'],
];
}
public function submit()
{
$user = Auth::user();
$this->validate();
User::where('id', auth()->id())->update([
'name' => $this->name,
'email' => $this->email,
'phone' => $this->phone,
]);
UserProfile::where('user_id', auth()->id())->update([
'state' => $this->selectedstate,
'city' => $this->selectedcity,
'job_title' => $this->jobTitle,
'about_me' => $this->aboutMe,
'employer' => $this->employer,
'position' => $this->position,
'edu_course' => $this->edu_course,
'edu_school' => $this->edu_school,
'edu_level' => $this->edu_level,
'edu_start_date' => $this->edu_start_date,
'edu_end_date' => $this->edu_end_date,
'employment_looking' => $this->employment_looking,
'employment_hired' => $this->employment_hired,
'twitter' => $this->twitter,
'linkedin' => $this->linkedin,
'github' => $this->github,
'instagram' => $this->instagram,
'website' => $this->website,
]);
if (!empty($this->languageToDelete))
{
/* $user = Auth::user(); */
foreach ($this->languageToDelete as $delete)
{
$user->userLanguages()->where('id', $delete)->delete();
}
}
foreach ($this->languages as $language)
{
/* $user = Auth::user(); */
$user->userLanguages()->updateOrCreate([
'language_name' => $language['language_name'],
],
[
'language_name' => $language['language_name'],
'language_level' => $language['language_level']
]
);
}
$this->getUserLanguages();
$this->sweetAlert('success', 'changes saved!');
}
public function sweetAlert($type, $message)
{
$this->alert($type, $message, [
'position' => 'bottom-end',
'timer' => 5000,
'toast' => true,
'text' => null,
'showCancelButton' => false,
'showConfirmButton' => false
]);
}
}
The issue has been solved. the problem indeed was a DOM issue caused by multiple loop index. as what I thought at first the $loop->index was causing it and I was on the right track to change it to something else like $languages as $lindex => $language but apparently even by doing that those two sections will still have the same wire:key because of the loop iterations which returns 0,1,2 and so on in order. so by appending a string to the key like lang{{ $loop->index }} they will be unique and therefore problem solved.

Laravel Custom Admin Login is not working

I have been developing a Laravel Auth system where there is a admin panel I had to create a custom admin authentication system. After after going through all the steps the login system is not working. After submitting the login form it redirect me to the same login page again instead of redirecting to the dashboard page. I am giving details of my whole system.
Let me know if anyone could help.
Admin Model
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Admin extends Authenticatable
{
use HasFactory;
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
Admin DB Migrations
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateAdminsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('admins', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('admins');
}
}
Config\Auth.php
<?php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Models\Admin::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
'admins' => [
'provider' => 'admins',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
'password_timeout' => 10800,
];
Login.Blade.php
#extends('layouts.app')
#section('pagetitle', 'Admin-Login')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card raleway">
<div class="card-header text-center font-weight-bold"><i class="fas fa-lock"></i> {{ __('Admin Login') }}</div>
<div class="card-body" style="padding-top:10%;padding-bottom:10%;">
<form method="POST" action="{{ route($loginRoute) }}">
#csrf
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control{{ $errors->has('email') ? ' is-invalid' : '' }}" name="email" value="{{ old('email') }}" required autofocus>
#if ($errors->has('email'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control{{ $errors->has('password') ? ' is-invalid' : '' }}" name="password" required>
#if ($errors->has('password'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<div class="col-md-6 offset-md-4">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>
<label class="form-check-label" for="remember">
{{ __('Remember Me') }}
</label>
</div>
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-8 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Login') }}
</button>
#if (Route::has('password.request'))
<a class="btn btn-link" href="{{ route($forgotPasswordRoute) }}">
{{ __('Forgot Your Password?') }}
</a>
#endif
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
LoginController.php
<?php
namespace App\Http\Controllers\Admin\Auth;
use Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\ThrottlesLogins;
class LoginController extends Controller
{
/**
* Show the login form.
*
* #return \Illuminate\Http\Response
*/
public function showLoginForm()
{
return view('admin.login',[
'loginRoute' => 'admin.login',
'forgotPasswordRoute' => 'admin.password.request',
]);
}
/**
* Login the admin.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse
*/
public function login(Request $request)
{
$this->validator($request);
if(Auth::guard('admin')->attempt($request->only('email','password'),$request->filled('remember'))){
//Authentication passed...
return redirect()
->intended(route('admin.dashboard'))
->with('status','You are Logged in as Admin!');
}
//Authentication failed...
return $this->loginFailed();
}
/**
* Logout the admin.
*
* #return \Illuminate\Http\RedirectResponse
*/
public function logout()
{
Auth::guard('admin')->logout();
return redirect()
->route('login')
->with('status','Admin has been logged out!');
}
/**
* Validate the form data.
*
* #param \Illuminate\Http\Request $request
* #return
*/
private function validator(Request $request)
{
//validation rules.
$rules = [
'email' => 'required|email|exists:admins|min:5|max:191',
'password' => 'required|string|min:4|max:255',
];
//custom validation error messages.
$messages = [
'email.exists' => 'These credentials do not match our records.',
];
//validate the request.
$request->validate($rules,$messages);
}
/**
* Redirect back after a failed login.
*
* #return \Illuminate\Http\RedirectResponse
*/
private function loginFailed()
{
return redirect()
->back()
->withInput()
->with('error','Login failed, please try again!');
}
}
Web.php
Route::prefix('/admin')->name('admin.')->namespace('Admin')->group(function(){
Route::get('/dashboard', [App\Http\Controllers\Admin\DashboardController::class, 'index'])->name('dashboard');
Route::namespace('Auth')->group(function(){
//Login Routes
Route::get('/login',[App\Http\Controllers\Admin\Auth\LoginController::class,'showLoginForm'])->name('login');
Route::post('/login',[App\Http\Controllers\Admin\Auth\LoginController::class,'login']);
Route::post('/logout',[App\Http\Controllers\Admin\Auth\LoginController::class,'logout'])->name('logout');
});
});
Solution
So I have solved my problem today.
The problem was occurring because of the below function in my AdminDashboardController.php
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
After removing it. Everything working fine now.

Laravel PHP, trying to redirect to an id

I am a beginner with php and laravel. I have recently created a form at the bottom of my website, that when you click the submit button it sends the data to an email address.
However if you don't fill it in correctly and click submit it refreshes the page and returns to the top of the page. If you submit the form correctly it goes to /contact.
What I am desperate to do is keep the page at the same point on the website (with the form on the screen) instead of refreshing the screen. Same if the form is submitted correctly I would like the screen to stay still.
Routes/web.php:
Route::get('/', 'PagesController#home');
Route::get('about', 'PagesController#about');
Route::get('contact',
['as' => 'contact', 'uses' => 'AboutController#create']);
Route::post('contact',
['as' => 'contact_store', 'uses' => 'AboutController#store']);
ContactFormRequest.php:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ContactFormRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'name' => 'required',
'email' => 'required|email',
'number' => 'required',
'message' => 'required',
];
}
}
AboutController.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\ContactFormRequest;
class AboutController extends Controller
{
public function create()
{
return view('pages.contact');
}
public function store(ContactFormRequest $request)
{
\Mail::send('emails.contact',
array(
'name' => $request->get('name'),
'email' => $request->get('email'),
'number' => $request->get('number'),
'user_message' => $request->get('message')
), function($message)
{
$message->from('sketchsitestest#gmail.com');
$message->to('sketchsitestest#gmail.com', 'Admin')->subject('Testing');
});
return \Redirect::route('contact')->with('message', 'Thanks for contacting us!');
}
}
contact.blade.php
<div class="one-half">
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
{!! Form::open(array('route' => 'contact_store', 'class' => 'form')) !!}
<div class="form-group">
{!! Form::text('name', null,
array('required',
'class'=>'form-control',
'placeholder'=>'Your name')) !!}
</div>
<div class="form-group">
{!! Form::text('email', null,
array('required',
'class'=>'form-control',
'placeholder'=>'Your e-mail address')) !!}
</div>
<div class="form-group">
{!! Form::number('number', null,
array('required',
'class'=>'form-control',
'placeholder'=>'Your Number')) !!}
</div>
<div class="form-group">
{!! Form::text('message', null,
array('required',
'class'=>'form-control',
'placeholder'=>'Your message')) !!}
</div>
<div class="form-group">
{!! Form::submit('Contact Us!',
array('class'=>'form-button btn btn-primary')) !!}
</div>
{!! Form::close() !!}
</div>
I am also new to using stackoverflow, so I apologise ahead if I have missed anything or done anything incorrectly. Please let me know if you need anything more.
Can't really understand your problem, but try to add this in your store() method:
return \Redirect::back()->with('message', 'Thanks for contacting us!');
But it looks like you want to submit/validate your forms without refreshing the page, so the only solution for this is to use AJAX requests.
May be this can be something. Using the validation helper.
function store(ContactFormRequest $request)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required',
'number' => 'required',
'message' => 'required',
]);
// If !$this->validate Laravel will automatic return to the previous page (the form page)
// And you can grab the errors with $errors->first('name'), $errors->first('email') etc
\Mail::send('emails.contact',
array(
'name' => $request->get('name'),
'email' => $request->get('email'),
'number' => $request->get('number'),
'user_message' => $request->get('message')
), function($message)
{
$message->from('sketchsitestest#gmail.com');
$message->to('sketchsitestest#gmail.com', 'Admin')->subject('Testing');
});
return \Redirect::route('contact')->with('message', 'Thanks for contacting us!');
}
Grab the errors like this:
#if ($errors->has('message'))
<span class="help-block">
<strong>{{ $errors->first('message') }}</strong>
</span>
#endif
Here you the docs about the validation, if you are using Laravel 5.3

Categories