Authenticate user Laravel - php

hi guys i have an simple application with laravel and i try to add a user Authentication to my app , this is my route.php file :
Route::model('task', 'Task');
Route::get('/login', 'HomeController#ShowLogin');
Route::post('/login', 'HomeController#doLogin');
Route::get('/logout' , 'HomeController#doLogout');
Route::group(array('before'=>'auth'), function(){
Route::get('/', 'TasksController#home');
Route::get('/create', 'TasksController#create');
Route::get('/edit/{task}', 'TasksController#edit');
Route::post('/edit', 'TasksController#doEdit');
Route::post('/create' , 'TasksController#saveCreate');
Route::get('/delete/{task}' , 'TasksController#delete');
Route::post('/delete', 'TasksController#doDelete');
Route::get('/task/{id}' , 'TasksController#show')->where('id', '\d+');
});
this is my HomeController.php ;
class HomeController extends BaseController {
public function showLogin()
{
return View::make('login');
}
public function doLogin()
{
$userdata = array(
'username' => Input::get('username'),
'password' => Input::get('password')
);
dd(Auth::attempt($userdata));
if(Auth::attempt($userdata))
{
return Redirect::to('/');
}
else
{
return Redirect::to('login');
}
}
public function doLogout()
{
Auth::logout();
return Redirect::to('login');
}
}
and this is my login.blade.php file :
#extends('layout')
#section('content')
<section class="header section-padding">
<div class="background"> </div>
<div class="container">
<div class="header-text">
<h1>Learning Laravel: The Easiest Way</h1>
<p>
Showing a single task <br/> using route parameter!
</p>
</div>
</div>
</section>
<div class="container">
<section class="section-padding">
<div class="jumbotron text-center">
<h1>
Login
</h1>
<P>
{{ $errors->first('username') }}
{{ $errors->first('password') }}
</P>
{{ Form::open(['url' => '/login', 'class' => 'form']) }}
<div class="form-group">
{{ Form ::label('username', 'Username:') }}
{{ Form::text('username')}}
</div>
<div class="form-group">
{{ Form::label('password', 'Password:') }}
{{ Form::password('password') }}
</div>
<div class="form-group">
{{ Form::submit('Login', ['class' => 'btn btn-primary']) }}
</div>
{{ Form::close() }}
</div>
</section>
</div>
#stop
when i input any username and password i got no error and i never login , and i redirect to login page and dd() always return bool(false), can any one help that , and explain more about Authentication in Laravel , Thank U :)
Edit
and this is my model/User.php and i dont add any code to this :
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $table = 'users';
protected $hidden = array('password', 'remember_token');
}
i create my user table manually

Auth::attempt($userdata) method will hash the password in $userdata array and check that hashed password with the database value,
so you need hashed passwords in the database,
to verify that,
please change the password in the database to $2y$10$3S3yDwfkwwLghedu4AoaTe//61QTaNC0ycTdp8hLfHtQS4XrgBPQy , and use a for the password field in the form
$2y$10$3S3yDwfkwwLghedu4AoaTe//61QTaNC0ycTdp8hLfHtQS4XrgBPQy is the laravel hashed password for a.

Related

Use a parameter from URL in a controller Laravel 5.8.22

I'm trying to pass anINT from this URL: myapp.build/courses/anINT (implemented in the CoursesController) to $id in the Lesson_unitsController function below. I've tried a lot of solutions, but I can't seem to get it right.
The function in the CoursesController which implements the url is:
public function show($id)
{
$course = Course::find($id);
return view('courses.show')->with('course', $course);
}
Part of the show.blade.php file is:
#if(!Auth::guest())
#if(Auth::user()->id == $course->user_id)
Edit Course
Lesson Units
{!!Form::open(['action'=> ['CoursesController#destroy', $course->id], 'method' => 'POST', 'class' => 'float-right'])!!}
{{Form::hidden('_method', 'DELETE')}}
{{Form::submit('Delete', ['class' => 'btn btn-danger'])}}
{!!Form::close()!!}
#endif
#endif
The Lesson_unitsController functions are:
public function index()
{
$lesson_units = Lesson_unit::orderBy('title','asc')->paginate(10);
return view('lesson_units.index')->with('lesson_units', $lesson_units);
}
public function specificindex($id)
{
$course = Course::find($id);
return view('lesson_units.specificindex')->with('lesson_units', $course->lesson_units);
}
And the specificindex.blade.php file is:
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Dashboard</div>
<div class="card-body">
Create lesson unit
<p>
<h3>Your lesson_units</h3>
#if(count($lesson_units) > 0)
<table class="table table-striped">
<tr><th>Title</th><th></th><th></th></tr>
#foreach($lesson_units as $lesson_unit)
<tr><td>{{$lesson_unit->title}}</td>
<td>Edit</td>
<td>
{!!Form::open(['action'=> ['Lesson_unitsController#destroy', $lesson_unit->id], 'method' => 'POST', 'class' => 'float-right'])!!}
{{Form::hidden('_method', 'DELETE')}}
{{Form::submit('Delete', ['class' => 'btn btn-danger'])}}
{!!Form::close()!!}
</td>
</tr>
#endforeach
</table>
#else
<p>You have no lesson unit.</p>
#endif
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
You are logged in!
</div> </div> </div> </div> </div>
#endsection
The routes in web.php are:
Route::resource('courses', 'CoursesController');
Route::resource('lesson_units', 'Lesson_unitsController');
Route::get('/courses/{id}', 'Lesson_unitsController#specificIndex');
I want that when the link for Lesson Units is clicked on the page, the id in the url is passed to the specificindex function in the Lesson_unitsController. Now, I get just a blank page. What am I doing wrong?
Try to understand the concept of RESTful and CRUD.
By using Route::resource('courses', 'CoursesController');, Laravel has helped you to register the following routes:
Route::get('courses', 'CoursesController#index');
Route::get('courses/create', 'CoursesController#create');
Route::post('courses/{course}', 'CoursesController#store');
Route::get('courses/{course}/edit', 'CoursesController#edit');
Route::put('courses/{course}', 'CoursesController#update');
Route::delete('courses/{course}', 'CoursesController#destroy');
Then, when you make GET request to myapp.build/courses/123, Laravel will pass the request to the show function of your CoursesController like:
public function show(Course $course)
{
return view('lesson_units.index')->with('lesson_units', $course->lesson_units);
}
Laravel will automatically resolve the Course from your database using the parameter passed into the route myapp.build/courses/{course}.
Note: The variable name $course has to match with the one specify in route /{course}.
You don't have a route set up to handle the $id coming in. The resource method within the Route class will provide a GET route into your Lesson_unitsController controller without an expectation of any variable. It is the default index route, and by default doesn't pass a variable.
There are a couple of ways to do this, but the easiest is to just create a new route for your specific need:
Route::get('lesson_units/{id}', 'Lesson_unitsController#specificIndex');
And then make your specificIndex function in your controller with an incoming variable:
public function specialIndex($id)
{
$course = Course::find($id);
// return view to whatever you like
}
HTH

Edit a form with Laravel Framework

I'm new to laravel and trying to learn using it. I created a little project for threads. Nothing special. The thing is, the function to edit something doesn't work and I cant see why. Maybe someone of you see the mistake?
thats my Routes:
Route::get('/index', 'Test\\TestController#index');
Route::get('/add', 'Test\\TestController#add');
Route::post('/test', 'Test\\TestController#store');
Route::get('/show/{id}', 'Test\\TestController#show');
Route::get('/show/{id}/edit', ['as' => 'edit', 'uses' => 'Test\\TestController#edit']);
Route::put('/show/{id}/edit', ['as' => 'editing', 'uses' => 'Test\\TestController#update']);
thats the important parts of the edit method:
public function edit($id) {
$thread = Thread::query()->findOrFail($id);
return view('test.edit', [
'thread' => $thread
]);
}
public function update($id, StoreRequest $request) {
$thread = Thread::query()->findOrFail($id);
$thread->fill($request->all());
$thread->save();
return redirect(action('Test\\TestController#show', [$thread->id]));
}
}
show.blade
#extends('master')
#section('content')
<div class="panel panel-primary">
<div class="panel-heading">
<div class="panel-title">
{{ $thread->thread }}
</div>
</div>
<div class="form-body">
<div class="form-group"><br>
<ul>
{{$thread->content }}<br><br>
{{$thread->created_at->format('d.m.Y H:i:s')}}
</ul>
</div>
</div>
<div class="panel-footer">
<div class="btn btn-primary">Thread bearbeiten</div>
</div>
</div>
#stop
edit blade ( formular where the text I want to add is in the textbox and the save button )
#extends('master')
#section('content')
{!! Former::horizontal_open()->method('PUT')->action(action("Test\\TestController#update", [$thread->id])) !!}
{!! Former::populate($thread) !!}
{!! Former::text('thread')->label('Thread') !!}
{!! Former::text("content")->label("Content") !!}
{!! Former::large_primary_submit('Save!') !!}
{!! Former::close() !!}
#stop
model:
<?php
namespace App\Models\Thread;
use Illuminate\Database\Eloquent\Model;
class Thread extends Model {
public $table = 'thread';
public $fillable = [
'thread',
'content',
];
}
ERROR MESSAGE :
No query results for model [App\Models\Thread\Thread].

functions random from database in php?

I have a function:
function nomor_registrasi() {
$sql=mysql_query("select * from pendaftaran order by no_registrasi DESC LIMIT 0,1");
$data=mysql_fetch_array($sql);
$kodeawal=substr($data['no_registrasi'],6,7)+1;
if($kodeawal<10) {
$kode='SMKGJ00'.$kodeawal;
} else if ($kodeawal > 9 && $kodeawal <=99) {
$kode='SMKGJ0'.$kodeawal;
} else {
$kode='SMKGJ'.$kodeawal;
}
return $kode;
}
If a user registers from a form, the user will have no_registrasi, for example: last no_registrasi record in the table is SMKGJ006, so the user will have SMKGJ007, etc..
I'm starting learning the php framework: laravel.
How can I code this function using laravel?
I use laravel 4!
If you want to put your function to run when user register you need to put it in Controller that respond for registration of users.
The Controllers are in folder /app/controllers .
If you recent(1 minute ago) installed **laravel 4.1 and not have the Controller that respond for registration of users (like me, after installation I have a page on with is only image and you arrived and no link to register and login like after installation of yii), when you need to create it.
To create controller UsersController put in /app/controllers file with name UsersController.php and code:
<?php
class UsersController extends BaseController {
//!!show the form for registration from root /app/views/some_file name_like_register.blade.php in witch is html form
public function getRegister() {
return View::make('users/register');
}
//!! register user when post data come from form
public function postRegister() {
//Here you can put your function
$rules = User::$validation;
$validation = Validator::make(Input::all(), $rules);
if ($validation->fails()) {
return Redirect::to('public/users/register')->withErrors($validation)->withInput();
}
$user = new User();
$user->fill(Input::all());
$id = $user->register();
return $this->getMessage("Registered successfull.");
}
}
Add changes to User model. After
class User extends Eloquent implements UserInterface, RemindableInterface {
add
//form validation
public static $validation = array(
'email' => 'required|email|unique:users',
'username' => 'required|alpha_num|unique:users',
'password' => 'required|confirmed|min:6',
);
//for registration
protected $fillable = array('username', 'email', 'password');
//
public function register() {
//Here you can put your function
$this->password = Hash::make($this->password);
$this->activationCode = $this->generateCode();
$this->save();
Log::info("User [{$this->email}] registered. Activation code: {$this->activationCode}");
/*$this->sendActivationMail();*/ //send email with activation code, set 1 to isActive value
return $this->id;
}
protected function sendActivationMail() { /*do*/}
protected function generateCode() {
return Str::random();
}
Make file with name register.blade.php in /app/views/ with code:
#section('title')
#section('content')
<div class="container">
#if ($errors->all())
<div class="alert alert-danger">
#foreach ($errors->all() as $error)
<p>{{ $error }}</p>
#endforeach
</div>
#endif
<h1>Registration</h1>
{{ Form::open(array('url' => '/users/register', 'role' => 'form', 'class' => 'form-horizontal')) }}
<div class="form-group">
{{ Form::label('email', 'E-Mail', array('class' => 'col-sm-2 control-label')) }}
<div class="col-sm-5">
{{ Form::email('email', null, array('class' => 'form-control')) }}
</div>
</div>
<div class="form-group">
{{ Form::label('username', 'login', array('class' => 'col-sm-2 control-label')) }}
<div class="col-sm-5">
{{ Form::text('username', null, array('class' => 'form-control')) }}
</div>
</div>
<div class="form-group">
{{ Form::label('password', 'password', array('class' => 'col-sm-2 control-label')) }}
<div class="col-sm-5">
{{ Form::password('password', array('class' => 'form-control')) }}
</div>
</div>
<div class="form-group">
{{ Form::label('password_confirmation', 'retype pass', array('class' => 'col-sm-2 control-label')) }}
<div class="col-sm-5">
{{ Form::password('password_confirmation', array('class' => 'form-control')) }}
</div>
</div>
<div class="form-group">
<div class="col-sm-2"> </div>
<div class="col-sm-5">
<button type="submit" class="btn btn-primary">Go</button>
</div>
</div>
{{ Form::close() }}
In table user add your registraci cell. Table structure is
Schema::create('users', function(Blueprint $table) {
$table->increments('id');
$table->string('email')->unique();
$table->string('password', 60);
$table->string('username')->unique();
$table->boolean('isAdmin');
$table->boolean('isActive')->index();
$table->string('activationCode');
$table->rememberToken();
$table->timestamps();
// also add your registraci
$table->string('registraci', 200);
});
To turn on database driver open /app/config/database.php and change if need
//select mysql or other
'default' => 'mysql'
...
//database and other change here
'mysql' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'laravel',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
)
If I lost something you will get errors messages not like oops but real problems
To see errors go to /app/config/app.php and set to
'debug' => true,
Add a column with name no_registrasi in laravel table with users and use your old code when register new user, only change table name and other columns name.
https://laravel.com/docs/5.0/schema
Schema::table('users', function($table)
{
$table->string('no_registrasi');
});

Laravel 4 Form Submission and Input Retrieval

I am a beginner in Laravel. I am trying to make a simple login form, by using a controller to manipulate the input. However everytime the code just ignore the controller function and keep calling the index everytime I submit. Please advise.
Here is the code for my form
{{ Form::open(array('action' => 'CoverController#authent')) }}
<div class="col-md-3 text-box pull-left">
{{ Form::email('email', '', array('placeholder'=>'Email')); }}
</div>
<div class="col-md-3 text-box pull-left">
{{ Form::password('password', array('placeholder'=>'Password')); }}
</div>
<div class="clearfix"> </div>
<div class="con-button">
{{ Form::submit('Sign Up / Log In'); }}
</div>
{{ Form::close() }}
Below is my routes
Route::get('/',array('as'=>'users','uses'=>'CoverController#index'));
Route::post('/','CoverController#authent');
Here is my controller function
class CoverController extends BaseController {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
$view = View::make('cover');
return $view;
}
public function authent()
{
$email = Input::get('email');
$pwd = Input::get('password');
$view = View::make('formoid')->with('email',$email)->with('password',$pwd);
return $view;
}
}
With the above code,everytime the login button is pressed, the index() function is called instead of authent(), what am I doing wrong?
Try:
{{ Form::open(array('url' => '/', 'method' => 'post')) }}
Form Doc

Laravel Auth Redirect to Previous Page

I am attempting to create a single page like application with Laravel 4. When the user arrives at the site, they should be prompted to log in. Once the user logs in, the view (not the URL) will switch and the user will be able to see information as if they are authenticated.
My HTML (if authroized should show "Auth" in h1, if not, it shows login form)
<div class="container">
#if(Auth::check())
<h1>Auth</h1>
#else
{{ Form::open(array('url'=>'login', 'method'=>'post')) }}
<div class="row">
<div class="col-xs-12">
<div class="form-group">
{{ Form::label('email', 'Email Address') }}
{{ Form::text('email', Input::old('email'), array('class'=>'form-control', 'placeholder'=>'example#test.com')) }}
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<div class="form-group">
{{ Form::label('password', 'Password') }}
{{ Form::password('password', array('class'=>'form-control')) }}
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
{{ Form::submit('Log In', array('class'=>'btn btn-primary pull-right')) }}
</div>
</div>
{{ Form::close() }}
#endif
</div>
Controller
class SiteController extends BaseController {
public function getIndex()
{
return View::make('index');
}
public function postLogin() {
$email = Input::get('email');
$password = Input::get('password');
if (Auth::attempt(array('email'=>$email, 'password'=>$password)))
{
return Redirect::route('index');
}
}
}
My user model is the default that ships with Laravel 4. As of now, I am passing the Auth::attempt and getting the return Redirect::route('index');, but the #if(Auth::check()) doesn't seem to be firing. Instead it continues to show me the log in form. Am I doing something wrong here?
I don't see anything wrong here, but you need to be sure what's happening, it looks like your authenticated session is not sticking, but to be sure you could:
<?php
class SiteController extends BaseController {
public function getIndex()
{
Log::info('index - authed: '. Auth::check() ? 'yes' : 'no');
return View::make('index');
}
public function postLogin() {
$email = Input::get('email');
$password = Input::get('password');
if (Auth::attempt(array('email'=>$email, 'password'=>$password)))
{
Log::info('postLogin - attempt successful');
return Redirect::route('index');
}
Log::info('postLogin - error on attempt');
}
}
And then check your logs:
php artisan tail

Categories