How to auth user for login in laravel using auth() - laravel

i have started learning laravel and i am trying to create login.
i have tried this
route
Route::post('userLogin', [\App\Http\Controllers\LoginController::class,'userLogin'])->name('userLogin');
blade.php
<form role="form" method="POST" action="{{ route('userLogin') }}">
#csrf
.........
</form>
controller
<?php
namespace App\Http\Controllers;
use App\Models\Login;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
class LoginController extends Controller
{
public function userLogin(Request $request){
$email = $request['email'];
$pass = $request['pass'];
if (auth()->attempt(['u_email' => $email, 'u_pass' => $pass])){
print 'ok';
}
else{
print 'none';
}
}
}
Problem
it is showing none, i have tried to print the values before auth() it print correct values.
Any solution

Use email and password instead of u_email and u_pass

You must pass the password as the field named 'password' in the credentials passed to Auth::attempt. This does not directly relate to the field in the table but the system needs to know what field in the credentials is the password so it can not include it in the query and then do a hash check against it if it finds a record. All the credentials passed to attempt except the 'password' field are where conditions on the query.
If you need to adjust what the password field is for that model you must adjust it on the model using the getAuthPassword method.

Related

Select option in Laravel, how to store in a database? [duplicate]

Hello i´m new in laravel. I dont know how to store the value of a select in a variable.
This is how i do it in php. But how in laravel?
Thank you for help :)
<?php
session_start();
//Database
$servername = "127.0.0.1";
$username = "root";
$password = "root";
//Connection to Database
$conn = new mysqli($servername, $username, $password);
//Connection Test
if(!$conn) {
echo "Not connected to Server"
}
if(!mysqli_select_db($conn, 'test')){
echo "No connection to Database";
}
//store data in variable
$vorname = $_POST['name'];
$name = $_POST['age'];
?>
<!--Form Select-->
<form action="test.php" method="post">
<select name="name">
<option value="Lisa"></option>
<option value="Laura"></option>
</select>
<select name="age">
<option value="20">20</option>
<option value="21">21</option>
</select>
<button type="submit">Sent</button>
</form>
<?php
$query = "SELECT * FROM test WHERE name = $name AND age = $age";
$profile = $conn->query($query);
?>
I want a Form with a select and the selected option should be stored in a variable.
Then checked in the database. And then show the results.
i dont know how to do thisin laravel.
thanks :)
All right let's get started. I suggest you study laravel documentation so things get more clear to you.
First of all you need to create your routes in your web.php file.
Route::get('/test', 'testController#index')->name('test.index');
Route::post('/values', 'testController#getValues')->name('test.values');
The first one will return your view the second one is to insert the data. Hang in there i will explain everything in the next lines.
Now you need a controller to handle the data and of course a view to preview your dropdowns.
In order to make a controller you can simple use php artisan make:controller testController command.
This will create a controller named testController like we named it in our routes.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class testController extends Controller
{
public function index()
{
return view('test');
}
}
This is how your controller will look on this step. Simply return your view template (which i named it test for example pursposes). Now you actually need to create this view that you are trying to return. So inside the views file you create a test.blade.php file and post your html code a bit modified.
<form action="{{ action('testController#getValues') }}" method="post" id="postData">
{{ csrf_field() }}
<select name="name">
<option value="Lisa">Lisa</option>
<option value="Laura">Laura</option>
</select>
<select name="age">
<option value="20">20</option>
<option value="21">21</option>
</select>
<button type="submit">Sent</button>
</form>
You will notice that the action of the form is pointing straight to a controller function which will create in the next step. It's used to insert the data in the Database.
The csrf_field creates a token. For now you will realize that it helps your session not to "timeout" but does a lot more than that. Read more about it here!!!
The way to access your form is simple that's why laravel's routing makes things so simple. Go like "localhost/my_project_folder/test" and you should be able to see your view.
All right moving forward. Now you need to send the data from view to controller so you store it in the db.
We need a new function in the controller named getValues like we named it in the web.php file in the beginning. Now your controller should look like that:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class testController extends Controller
{
public function index()
{
return view('test');
}
public function getValues(Request $request){
$name=$request->get('name');
$age=$request->get('age');
$insertData=DB::table('data')->insert(
['name' => $name, 'age' => $age]
);
}
}
Request method is really useful in laravel so investigate some more about this method here!!!
Now the final part. Connect your database. All the connections happen in the .env file.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=testingdata
DB_USERNAME=root
DB_PASSWORD=root
This is my private database in my localhost so you can modify it using your credentials. After doing this step you are good to go.
If you have used different database or made a lot of changes etc etc and feel like you are using old settings run php artisan config:cache command to configure your cache with the latest changes.
This is the simplest walk through for insert data from the form to the database. You can optimize it and expand it a lot so my suggestion to you is to start reading laravel documentation, if possible get access to laracast and if you have time participate in the laracasts forum.

if else condition in routes laravel

I want only user with same name with the url id can access using if condition
Example
User logged on with name jer
He should only access url with /User-Profile/jer
And not access other page /User-Profile/abc that are not equal to his
name
Doing something like Example:
if{id}!=={{auth->name}}
{
Route::get('NoPermission', 'Restriction#index');
}
else
{
Route::get('/User-Profile/{name}/', 'AccountController#index');
}
How can I compare {name} from url to {auth->name} ?
Route
Route::get('/User-Profile/{name}/', 'AccountController#index');
Blade
<a href="/dashboard/User-Profile/{{ Auth::user()->name }}">{{ Auth::user()->name
}}</a>
You can't access Auth like that in your routes, compare it in your AccountController instead:
public function index($name){
if($name != Auth::user->name()) abort(403);
else...
}
In a service provider (Doesn't really matter which one, but it would be clearer if done in the RouteServiceProvider), add a route binding in the boot method as documented in https://laravel.com/docs/6.x/routing#explicit-binding
public function boot()
{
// Declare binding 'name'.
Route::bind('name', function ($name) {
return App\User::where('name', $name)->first() ?? abort(404);
});
}
Then, use that binding in your routes file
// Use binding name and middleware auth to make sure this route can't be accessed by guest users.
Route::get('/User-Profile/{name}/', 'AccountController#index')->middleware('auth')->name('account_profile');
In your blade file, you can do the following
{{-- Make sure the link is only visible for authenticated users https://laravel.com/docs/6.x/blade#if-statements --}}
#auth
<a href="{{ route('account_profile', ['name' => auth()->user()->name]) }}</a>
#endauth
Allow acces to the page , but before showing content ,check if the url path is == to the id name .
Actually, you can check in your routes like this:
Route::get('/profile/{name}', function(String $name) {
if (!Auth::check() || $name !== Auth::user()->name) {
abort(404);
}
return view("view.auth.profile", ['profile => App\Profile::where('user_id', '=', Auth::id())->first()]);
});
However if you use
Route::get('/profile', 'AuthController#profile')->middleware('auth');
and use Auth::user() in your controller to select the correct profile.
The benefit here is that any unauthenticated users will be automatically redirected to your login page, and there's no need to include the name on your profile link.

how to make a password hash laravel 5.8

// method untuk insert data ke table d_rak
public function store(Request $request)
{
$data=new User();
$data->name=$request->get('name');
$data->username=$request->get('username');
$data->nip=$request->get('nip');
$data->level=$request->get('level');
$data->email=$request->get('email');
$data->password=$request->get('password');
$data->save();
return redirect ('/users')->with('alert-success','Berhasil Menambahkan Data!');
}
Try this
use Illuminate\Support\Facades\Hash;
$data->password= Hash::make($request->get('password'));
Simply use bcrypt helper.
$data->password = bcrypt($request->get('password'));
or Hash facade.
$data->password = Hash::make($request->get('password'));
For use in controller:
$request->user()->fill([
'password' => Hash::make($request->newPassword)
])->save();
And check if is the correct password
The check method allows you to verify that a given plain-text string corresponds to a given hash. However, if you are using the LoginController included with Laravel, you will probably not need to use this directly, as this controller automatically calls this method:
if (Hash::check('plain-text', $hashedPassword)) {
// The passwords match...
}

How to pass id from (form) of view blade to route (web.php) :Route

I need to pass an id to the route (web.php) from the form. My application has comment section at opporunities/id (id in value) , Whenever non-Auth user submits comment , my app will ask login and redirects to /opportunities but i need /opportunities/id. In the form of comment i have submitted page id. I have setup my route as
Route::post('/opportunities', 'OpportunitiesController#postPost')->name('posts.post'); Now if i can pass that id to as /opportunities/id then after login user will automatically lands on that page. I have manually tested and attached id and it works. Do I need to use "use Illuminate\Http\Request;" to get form data to web.php (route)? to get request post id? All i need is to add id after Route:post('/opportunites/'). Any suggestion and help will be appropriated.
What I did was and figured out is that
action="{{route('opportunities',['returnvalue'=> $post['id']]) }}" I still got error #bipin answer but i passed it with as parameter and solved. Thanks bipin for suggestion though!
One solution could be, pass your post id inside the form
View Blade
{{ Form::hidden('post_id', 'value', array('id' => 'post_id')) }}
Controler
use Illuminate\Http\Request;
public function comment(Request $request)
{
//Validation
$this->validate($request, [
'post_id' => 'required'
]);
//Inside variable
$input = $request->all();
// OR
$request->post_id;
}

Laravel insert into mysql db from a controller function

I am trying to submit records into a mysql table with many fields by using a Laravel .blade.php view ( php form)
I made some trials but I get
FatalErrorException in loginController.php line 54: Class 'App\Http\Controllers\Input' not found.
Mysql
create table users(id int primary key auto_increment,username varchar(20),password varchar(20),createDate timestamp );
My controller function
public function formSubmit()
{
if (Input::post())
{
$username = Input::get('username');
$password = Input::get('password');
DB::table('users')->insert(array ('username' => $username,'password' => $password));
return View::make('view2')->with(array('username' =>$username, 'password' => $password));
}
}
view1.blade.php form
<form action="{{url('/view2') }}" method="POST">
{{ csrf_field() }}
<input type ="hidden" name="">
User name: <input type ="text" name="username"> <br/>
Password <input type="password" name="password"> <br/>
<input type="submit" name="formSubmit" value="formSubmit">
</form>
Route
Route::get('/view1', 'loginController#formSubmit');
Add use Input; to the top of your class right after namespace clause.
Or use full namespace:
$username = \Input::get('username');
$password = \Input::get('password');
Or you just could use only() method to get an array from request:
DB::table('users')->insert(request()->only('username', password));
Also, never save raw passwords. Use bcrypt() to encrypt passwords.
Since you're using Laravel 5, use the Request Facade and acces input this way:
Request::input()
instead of using Input();
https://laravel.com/docs/5.0/requests
And, just in case, include it at the top of the Controller with
use Illuminate\Support\Facades\Request;
Referring to Amarnasan answer I used request and include use Illuminate\Http\Request; at the top of my controller.
So I changed my controller method to
public function formSubmit(Request $req)
{
$username =$req->input('username');
$password =$req->input('password');
DB::table('users')->insert(array ('username' => $username,'password' => $password));
return view ('view2')->with(array('username' =>$username, 'password' => $password));
}
}
and I changed my routes according to Shubham pokhriyal commit to:
Route::post('/view2', 'loginController#formSubmit');
Route::get('view1',function()
{
return view('view1');
}
);
and it works fine.

Resources