Laravel, Check if name of user exist on original laravel auth - php

I have laravel application! I use original laravel authentication from
php artisan make:auth
My question is how to check if name already exist in database and if exist to return error message!
My user table structure is:-
user:
id - UNIQUE
name
email
password
remembertoken
timestamps

Laravel form validation
Following is quoted from there:
Use the "unique" rule for name.
$request->validate([
'name' => 'required|unique:users'
]);
And display error like this:
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div> #endif

You actually have two solutions:
Make sure you have an unique constraint on your database for name
See the code below
$user = User::where("name", $nameToTestAgainst)->first();
if($user!= null) {
$v->errors()->add('Duplicate', 'Duplicate user found!');
return redirect('to-your-view')
->withErrors($v)
->withInput();
}

You can use auth()->user()->name in blade file.
<?php $name=auth()->user()->name; ?>

Related

laravel check if it exists and send an alert

I need help with Laravel
I need to get a code that runs: if and send a message ::
$text = App\Nota::select('nombre')->where('id', 3);
I need to check that if a string = 'hello' arrives it will print a message in .blade
in short check if it exists and send an alert
Help me please
you can do in this way.
$text = App\Nota::select('nombre')->where('id', 3);if($text->nombre=="hello"){Session::flash('message', 'This is a message!');Session::flash('alert-class', 'alert-danger'); }
In the view you can make it display like this.
#if(Session::has('message'))<p class="alert {{ Session::get('alert-class', 'alert-info') }}">{{ Session::get('message') }}</p>#endif
Try this way using exist() method if you just want to check record is exists or not. Here, in your case, you just want to check that modal Nota having id 3 and it's nombre column should be equal to hello. There is no need to load the modal, you can try specifying both conditions in where() method and use exist() to check the record exist.
Controller
$exist = App\Nota::where([
'id' => 3,
'nombre => 'hello'
])->exists();
if(!$exist){
Session::flash('message', 'This is a message!');
Session::flash('alert-class', 'alert-danger');
}
View
#if(Session::has('message'))
<p class="alert {{ Session::get('alert-class', 'alert-info') }}">{{
Session::get('message') }}</p>
#endif

Laravel array validation dont show error message

Firstly I can say that after search I dont find any solution about this. I do validation array like this post: laravel validation array
I need validate each size array position. I write this validation code:
// Fields validation
$request->validate([
'name' => 'required|max:150',
'theySay' => 'nullable|array',
'theySay.*' => 'string|max:1000',
'theyDontSay' => 'nullable|array',
'theyDontSay.*' => 'string|max:1000',
]
Where theySay and theyDontSay are both array of strings. In migration I have both fields (text) like strings of 1000 characters.
$table->string('text', 1000);
And validation works correctly. I mean, if put a text greater than 1000 chars I cannot save but..dont show any error message.
I want the error message to be shown in the input just like the rest of the fields.
What am I doing wrong?
Best regards
'YOUR_FIELD' => '...|...|max:1000| ...'
Look at the Laravel validation docs for more information
Please put below code in your blade file for show any error message.
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif

laravel send data to view via route and display it in view without altering url

on signup i am checking the invitation code the user uses using:
$match_code = DB::table('codes')->where('code', $code)->pluck('code');
if($code == $match_code){
$ip->save();
$user->save();
Auth::login($user);
return redirect()->route('news');
}else{
return redirect()->route('home')->with('message','Invalid Invite Code');
}
i tried adding this in my view :
#if(isset($message))
<li>{{ $message }}</li>
#endif
but this does not display anything, i am new to laravel. i know this is basics but i have been googling for over 45 mins with no results
The data you have send using with() is available in session, check this:
return redirect('dashboard')->with('status', 'Profile updated!');
After the user is redirected, you may display the flashed message from the session. For example, using Blade syntax:
#if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
#endif
Reference

Laravel form validation, why I don't have the $errors variable available on my view?

Taken from lrvl 5.1 documentation, I read:
using these lines in the controller:
$this->validate($request, [
'title' => 'required|unique:posts|max:255',
'author.name' => 'required',
'author.description' => 'required',
]);
If validation doesn't pass controller stops execution and redirect back to previous location.
This is happening correctly.
Then doc says:
"$errors variable will always be available in all of your views on every request"
And then suggests the following blade code:
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
But actually I'll get a ErrorException undefined variable errors....
What am I missing?
Thanks
I'll answer myself to this question,
just in case It was not clear the commented solution.
(Thanks to train_fox for the hint).
Just add 'web' middleware usage.
in your routing that is target in form action (get/post)
Example:
Route::group(['middleware' => 'web'],
function(){
Route::post('/edit' , 'My_Controller#edit');
});
Variable $errors the becomes available on view to be parsed.

Laravel - getting the validation error

in Laravel, is there any way to know which rule was invalid. For example:
'email': 'email|max:20'
And let's assume that I want to know is the email max rule failed
If you want to get error message considering specific field, then mention the name of the Validation object key on messages array. Ref
If validation has failed, you may retrieve the error messages from the validator.
if ($validator->fails())
{
$messages = $validator->messages();
}
echo $messages;
You may also access an array of the failed validation rules, without messages. To do so, use the failed method:
$failed = $validator->failed();
Retrieving All Error Messages For A Field
foreach ($messages->get('email') as $message)
{
//
}
By default all validation errors will be flashed to the session and available through $errors array in the template. Every failed rule will generate a separate error.
Example of displaying the errors using Bootstrap classes, taken from the documentation. Place this somewhere in your Blade template:
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
See more details in the official documentation
In my opinion it is better to use custom validation message for email max. I assume you are doing like this
$data = 'data_to_validate';
$rule = array('email': 'email|max:20') ;
$validator = Validator::make($data,$rule);
Add custom validation for email max like this
$message = array('email.max' => 'Exceeded max. email length');
new validator
$validator = Validator::make($data,$rule,$message);
Now if $validator->fails() for email max then $validator->messages() will show your custom validation. This way you can know your max rule failed.

Categories