functions random from database in php? - 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');
});

Related

Laravel unknown column

I have a problem with this error:
https://pastebin.com/cgm5yq0P
This is my form:
https://pastebin.com/bSU5X5EC
This is my web.php (route controller):
Route::post('/komentarz', 'VideosController#postComment');
This is my VideoController postComment function:
https://pastebin.com/SYbEjB8H
This is my Comment model:
https://pastebin.com/SxHX6gTP
This is my User model comments function:
public function comments() {
return $this->hasMany('App\Comment');
}
This is my Video model comments function:
public function comments(){
return $this->belongsToMany('App\Comment')->withTimestamps();
}
And finally, Migration file named create_comments_table:
https://pastebin.com/2cHscQfq
My Routes:
https://pastebin.com/ki8FZ0C6
Please help me with this.. I dunno what is wrong
Your foreign keys are wrong. Change your migration to this.
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->unsignedInteger('video_id');
$table->foreign('video_id')->references('id')->on('videos')->onDelete('cascade');
Edit : This adds the comment and attaches it to the video and user.
// model fillable property
protected $fillable = [
'text', 'user_id', 'video_id',
];
// route
Route::post('/film/{id}/komentarz', 'VideosController#postComment');
// controller method
public function postComment(CreateCommentRequest $request, $id)
{
$video = Video::findOrFail($id);
$video->comments()->create([
'text' => $request->text,
'user_id' => auth()->id(),
]);
return 'works';
}
// form
{!! Form::open(['url' => "/film/{$video->id}/komentarz", 'method' => 'post','class' => 'form-horizontal']) !!}
<div class="form-group">
<div class="col-md-3 control-label">
{!! Form::label('text', 'Treść komentarza:') !!}
</div>
<div class="col-md-8">
{!! Form::textarea('text', null, ['class'=>'form-control', 'size' => '5x5']) !!}
</div>
</div>
<div class="form-group">
<div class="col-md-8 col-md-offset-3">
{!! Form::submit('Dodaj', ['class'=>'btn btn-primary btn-comment']) !!}
</div>
</div>
{!! Form::close() !!}
in comment model i see 'user' in fillable, not 'user_id'. i think it should be user_id. or you could use
protected guarded = [];
instead of using fillable array.

Contact Form Laravel 5.4

I'm trying to build contact form in Laravel 5.4. I'm almost succeeded but besides actual message, on my mail i'm getting the structure of the page (look screenshot). Can you help me with that?
enter image description here
my View Form:
<div class="row">
{{ Form:: open(array('action' => 'ContactController#getContactUsForm')) }}
<ul class="errors">
#foreach($errors->all('<li>:message</li>') as $message)
{{ $message }}
#endforeach
</ul>
<div class="form-group">
{{ Form:: textarea ('message', '', array('placeholder' => 'Message', 'class' => 'form-control', 'id' => 'message', 'rows' => '7' )) }}
</div>
<div class="modal-footer">
{{ Form::submit('Submit', array('class' => 'btn btn-primary')) }}
{{ Form:: close() }}
</div>
</div>
And my Controller:
namespace App\Http\Controllers;
use Input;
use Illuminate\Http\Request;
use Validator;
use Mail;
use Redirect;
class ContactController extends Controller
{
public function getContactUsForm(Request $request){
//Get all the data and store it inside Store Varible
$data = \Input::all();
//$data = $request->message;
//$data = $request->input('message');
//Validation rules
$rules = array (
//'first_name' => 'required', uncomment if you want to grab this field
//'email' => 'required|email', uncomment if you want to grab this field
'message' => 'required|min:5'
);
//Validate data
$validator = Validator::make ($data, $rules);
//If everything is correct than run passes.
if ($validator -> passes()){
Mail::send('support/contact', $data, function($message) use ($data)
{
//$message->from($data['email'] , $data['first_name']); uncomment if using first name and email fields
$message->from('masha#mail.com', 'contact form');
//email 'To' field: cahnge this to emails that you want to be notified.
$message->to('masha#mail.com', 'Masha')->subject('Contact Form');
});
// Redirect to page
return Redirect::route('contact')
->with('message', 'Your message has been sent. Thank You!');
//return View::make('contact');
}else{
//return contact form with errors
return Redirect::route('contact')
->with('error', 'Feedback must contain more than 5 characters. Try Again.');
}
}
}
change this:
<div class="modal-footer">
{{ Form::submit('Submit', array('class' => 'btn btn-primary')) }}
{{ Form:: close() }}
</div>
To this:
<div class="modal-footer">
{{ Form::submit('Submit', array('class' => 'btn btn-primary')) }}
</div>
{{ Form:: close() }}
I think ordering break the structure.

laravel 4 Undefined index: password

My code used to work properly but now there is an error
(ErrorException (E_NOTICE)Undefined index: password)
I really dont know why, so if you know please help me. I searched google for similar exceptions and try everything I see but still no success ... Here is my code
route.php
Route::resource('login', 'LoginController');
LoginController
public function store(){
/*$credentials = array(
'username' => Input::get('username'),
'password' => Hash::make(Input::get('password')),
);*/
if(Auth::attempt(['active' => 1])) {
// if(Auth::attempt($credentials)){
if(Auth::attempt(Input::only('username', 'password'))){
return Auth::user();
//return Redirect::back()->with('message','You are now logged in!');
//return Redirect::to('/')->with('message','You are now logged in!');
}
else{
//$errors = ['password' => "Username and/or password invalid."];
//return Redirect::back()->withErrors($errors)->withInput(Input::except('password'));
return 'Failed~';
}
}
else{
//$errors = ['password' => "Please check your email to activate your account"];
//return Redirect::back()->withErrors($errors)->withInput(Input::except('password'));
return 'Failed~';
}
}
}
View login/create.blade.php
#section('content')
<div class="col-lg-3"></div>
<div class="form col-lg-6 box">
{{ Form::open(['route' => 'login.store'], array('class' => 'form-horizontal')) }}
{{-- #if ($error = $errors->first('password'))
<div class="alert alert-danger">
{{ $error }}
</div>
#endif--}}
<div class="input-group form-group-md">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
{{ Form::text('username', null,['class' => 'form-control','autofocus'=>'autofocus', 'placeholder' => 'Username']) }}
</div>
<div class="input-group form-group-md">
<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
{{ Form::password('password', array('class' => 'form-control', 'placeholder' => 'Password')) }}
</div>
<div class="form-group-md">
Forgot your password?
</div>
<div class="form-group-md">
{{ Form::submit('Log In', array('class' => 'login navbar-btn btn-block form-control', 'autofocus'=>'autofocus')) }}
</div>
<div class="question form-group-md">
{{ Form::label('register', 'Do not have an account?! ') }} Register here!
</div>
{{ Form::close() }}
</div>
<div class="col-lg-3"> </div>
#stop
error
Rewrite your code as below.
$username = Input::get('username');
$password = Input::get('password');
// You also may add extra conditions to the authenticating query
if (Auth::attempt(array('username' => $username, 'password' => $password, 'active' => 1)))
{
// The user is active, not suspended, and exists.
}else{
// user not exist or suspended
}
Refer this link also.
The problem is that the validateCredentials method which is belongs to your class provider EloquentUserProvider expects that the $credentials array have array element called password and expects it to be hashed .
as shown here :
/**
* Validate a user against the given credentials.
*
* #param \Illuminate\Contracts\Auth\Authenticatable $user
* #param array $credentials
* #return bool
*/
public function validateCredentials(UserContract $user, array $credentials)
{
$plain = $credentials['password'];
return $this->hasher->check($plain, $user->getAuthPassword());
}
and you in your code are sending wrong array in the first attempt call
if(Auth::attempt(['active' => 1]))
to solve this you may have to rewrite your code some thing like this ,
public function store()
{
$credentials = array(
'username' => Input::get('username'),
'password' => Hash::make(Input::get('password')),
'active' => 1
);
if(Auth::attempt($credentials)) {
return Auth::user();
} else {
return 'Failed~';
}
}

Laravel change password right after email confirmation view not working

When a user is created a random password (and a auth code) will be created and send with an email to the user.
When clicked on the link in the email the user status will be 1 (so active) and the user will be able to change his password right away.
Now it doesn't work as I want to.
UserController:
public function store(CreateUserRequest $request, User $user, Attribute $attribute)
// some unnecessary code
if ((Input::get('usertype_id')) > 1) {
$randomPassword = str_random(8);
$user->password = Hash::make($randomPassword);
$authentication_code = str_random(12);
$user->authentication_code = $authentication_code;
$user->active = 0;
};
$user->save();
if ((Input::get('usertype_id')) > 1) {
// Email sturen met verficatie code
$email = Input::get('email');
Mail::send('emails.user', ['user' => $user, 'password' => $randomPassword, 'authentication_code' => $authentication_code], function ($message) use ($email) {
$message->to($email, 'Lilopel')->subject('Lilopel: Verify your account!');
});
};
public function confirmUser($authentication_code)
{
if (!$authentication_code)
{
return 'auth code not found!';
}
$user = User::where('authentication_code', '=', $authentication_code)->first();
if (!$user)
{
return 'user not found!';
}
$user->active = 1;
$user->save();
Session::put('user_id', $user->id);
return view('user.setpassword', ['user' => $user]);
//return redirect()->route('user.setPassword', [$user_id]);
}
public function setPassword(SetPasswordRequest $request)
{
$user_id = Session::get('user_id');
$user = $this->user->find($user_id);
$user->fill($request->only('password'));
$user->save();
}
Route:
Route::get('user/verify/{authenticationCode}', 'UserController#confirmUser');
Route::get('user/password', 'UserController#setPassword');
View:
{!! Form::model($user, ["route"=>['user.setPassword', $user->id] , "method" => 'PATCH']) !!}
<div class="form-group {{ $errors->has('password') ? 'has-error' : '' }}">
{!! Form::label('password', trans('common.password'), ['class' => 'form-label col-sm-3 control-label
text-capitalize']) !!}
<div class="col-sm-6">
{!! Form::password('password', ['name' => 'password', "class"=>"form-control","placeholder" =>
trans('common.password') ]) !!}
{!! $errors->first('password', '<span class="help-block">:message</span>') !!}
</div>
</div>
<div class="form-group {{ $errors->has('confirm_password') ? 'has-error' : '' }}">
{!! Form::label('password_confirmation', trans('common.confirmpassword'), ['class' => 'form-label
col-sm-3 control-label text-capitalize']) !!}
<div class="col-sm-6">
{!! Form::password('password_confirmation', ['name' => 'password_confirmation',
"class"=>"form-control","placeholder" => trans('common.confirmpassword') ]) !!}
{!! $errors->first('password_confirmation', '<span class="help-block">:message</span>') !!}
</div>
</div>
{!! Form::submit( trans('common.edit'), ["class"=>"btn btn-primary text-capitalize center-block "]) !!}
{!! Form::close() !!}
Email links works, the status of the user gets active, but then the .blade will give a Route [user.setPassword] not defined. (View: public_html/server2/resources/views/user/setpassword.blade.php) error.
work togetherTo use the route as you do, you need a named route.
Change this
Route::get('user/password', 'UserController#setPassword');
to this
Route::get('user/password', [
'as' => 'user.setPassword',
'uses' => 'UserController#showProfile'
]);
Also, make sure the HTTP verbs of the route and your form's method work together.

Authenticate user Laravel

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.

Categories