Save user data on click button - php

I'm working on laravel 5.4 and I have this code:
public function apply($id){
$user = User::where('id', $id)->get()->first();
$data = [
'name' => $user->first_name,
'family' => $user->last_name,
'email' => $user->email,
'username' => $user->username,
'gender' => $user->gender,
'birthday' => $user->birthday,
'cv' => $user->cv,
'about' => $user->about,
'education' => $user->education,
'experiences' => $user->experiences,
];
$company = Company::get()->first();
Mail::send('emails.apply', $data, function ($message) use ($company)
{
$message->from('noreply#gmail.com', 'Robert Nicjoo');
$message->subject('New Apply');
$message->to($company->email);
});
Mail::send('emails.uapply', $data, function ($message) use ($user)
{
$message->from('noreply#gmail.com', 'Robert Nicjoo');
$message->subject('You Applied successfully');
$message->to($user->email);
});
Session::flash('success', 'Your application was sent to company.');
return redirect()->back()->with('session', $data);
}
This will send email to company when user click on apply button and send user info to them, now I also want to save data of the user include user_id, ad_id and company_id in another table so both user and company owners can have access to their history of applied ads.
I also have this table to save data on:
public function up()
{
Schema::create('applies', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('ad_id')->unsigned();
$table->integer('company_id')->unsigned();
$table->timestamps();
});
Schema::table('ads', function($table) {
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('ad_id')->references('id')->on('ads');
$table->foreign('company_id')->references('company_id')->on('ads');
});
}
but in my controller (first codes) I need to know how to save those information in new table (second codes)?
Update:
Ad Model >>
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Ad extends Model
{
protected $fillable = [
'company_id', 'title', 'slug', 'image', 'description', 'address', 'job_title', 'salary',
];
public function company(){
return $this->belongsTo(Company::class);
}
public function category(){
return $this->belongsTo(Category::class);
}
public function location(){
return $this->belongsTo(Location::class);
}
public function employment(){
return $this->belongsTo(Employment::class);
}
}

since your blade is like this:
<a class="btn btn-info btn-round" href="{{ route('apply.btn', Auth::user()->id) }}">
your route should look like
Route::get('apply/{id}', 'ApplyController#apply')->name('apply.btn');
why id only ? because in the discussion we had, i found out that ad_id and company_id was taken from the controller .. then in your controller this should work
public function apply($id)
{
$ad = Ad::first();
$company = Company::first();
$apply = new Apply();
$apply->user_id = $id
$apply->ad_id = $ad->id;
$apply->company_id = $company->id;
$apply->save();
// some more codes //
}
to avoid duplicates using user_id .. add a validation function like
function validateApply(array $data)
{
return Validator::make($data, [
'user_id' => 'required|numeric|unique:apply,user_id,NULL,id,ad_id,'.$data->ad_id,
]);
}
unique:apply - it means it will check the apply table the user_id already applied ..
then in the code above just do
$validateApply= $this->validateApply(['user_id'=>$id,'ad_id'=>$ad->id]);
if(!$validateApply->fails())
{
// do the above code here
}
else
{
// duplicate !!! so do your code here
}
then to retrieve the data assuming apply is already belongsTo the user as well the user hasOne apply
Auth::user()->apply->first()->somefield;
// im not sure how the hasOne works but try
Auth::user()->apply->somefield;

Your Route should be:
Route::post('apply/{$user_id}/{company_id}/{ad_id}','ApplyController#apply');
I think you have created model for ads.
So, simply save data like this:
Your function be like
public function apply(Request $request){
// other code
$apply = new Apply();
$apply->user_id = $request->user_id;
$apply->ad_id = $request->ad_id;
$apply->company_id = $request->company_id;
$apply->save();
// other code
}
And one more thing, You should have ad_id in your post request.

Related

DropDown: Validate 2 items on 3 only

I have 2 tables, the first is Students with 3 fields (name, firstname, fk_diploma).Then, my second table is named Diplomas and there is 1 field named (type_diploma).
For information, I have 3 values in my field type_diploma:
1) DiplomaA
2) DiplomaB
3) DiplomaC
In my validate system, I want the DiplomaA or DiplomaB to be validated but not the DiplomaC, I must have an error message.
For example: * "Sorry, you do not have the skills for the diplomaC."
Do you have an idea of how I can do that ?
public function store(Request $request)
{
$diploma = Diploma::select('type_diploma')->where('id',$request->fk_diploma)->get();
if($diploma->type_diploma != 'DiplomaC')
{
$request->validate([
'name' => 'required|min:3',
'firstname' => 'required|min:2|max:200',
'fk_diploma' => 'required'
]);
}
$exists = Student::where('name', $request->get('name'))->where('firstname', $request->get('firstname'))->where('fk_diploma', $request->get('fk_diploma'))->count();
if (!$exists){
Student::create($request->all());
return redirect()->route('students.index')
->with('success', 'new data created successfully');
}
else{
return redirect()->route('students.index')
->with('error', 'duplicate');
}
}
My model Diploma
class Diploma extends Model
{
protected $fillable = ['type_diploma'];
public function diplomas(){
return $this->hasMany('App\Student', 'fk_diploma');
}
}
Model Student
class Student extends Model
{
protected $fillable = ['name', 'firstname', 'fk_diploma'];
public function diplomas(){
return $this->belongsTo('App\Diploma' , 'fk_diploma');
}
This is not the best way to do it, but its the only one i could think right now:
1) change the type of your request to public function store(Request $request)
2) Do this in your function:
public function store(dateRequest $request)
{
$diploma = Diploma::select('type_diploma')->where('id',$request->fk_diploma)->get();
if($diploma->type_diploma != 'DiplomaA' && $diploma->type_diploma != 'DiplomaB')
{
$request->validate([
'name' => 'required|min:3',
'firstname' => 'required|min:2|max:200',
'fk_diploma' => 'required'
]);
}
$exists = Student::where('name', $request->get('name'))->where('firstname', $request->get('firstname'))->where('fk_diploma', $request->get('fk_diploma'))->count();
if (!$exists){
Student::create($request->all());
return redirect()->route('students.index')
->with('success', 'new data created successfully');
}
else{
return redirect()->route('students.index')
->with('error', 'duplicate');
}
}
This will work for you:
$this->validate($request, [
'fk_diploma' => 'required|not_in:XXX',
]);
XXX - id of the diploma you don't want to accept

Insert into two tables that are in one to one relationslip laravel

I have 2 tables that are in one to one relationship:
tours :
id|title|content
featured_image:
id|tour_id|name|path
My models FeaturedImage.php:
class FeaturedImage extends Model
{
public function tour()
{
return $this->hasOne('App\Tour');
}
}
Tour.php
class Tour extends Model
{
public function featuredimage()
{
return $this->belongsTo('App\FeaturedImage');
}
}
I want to save tour_id in featured_image table when tour is created. I'm using same form to fill tours table and to upload featured_image.
This is my store method looks like:
public function store(Request $request)
{
//validate the date
$this->validate($request, [
'title' => 'required|max:255',
'content' => 'required'
]);
//store the date
$tour = new Tour;
$tour->title = $request->title;
$tour->content = $request->trip_code;
$tour->save();
$featured_image= new FeaturedImage;
// save featured_image
if($request->hasFile('featured_image')){
$image = $request->file('featured_image');
$filename = $image->getClientOriginalName();
$location = public_path('images/featured_image/'.$filename);
Image::make($image)->resize(800, 600)->save($location);
$featured_image->path= $location;
$featured_image->tour()->associate($tour);
$featured_image->save();
}
//redirect to
Session::flash('success','Tour is successfully created !');
return redirect()->route('tours.show',$tour->id);
}
I'm successful to save data into tours table but unable to save in featured_image table. I 'm getting this error:
Call to undefined method Illuminate\Database\Query\Builder::associate()
I would be thankful if anyone can help me out.
You can user Mass Assignment to create your entries into DB like this:
$this->validate(request()->all(), [
'title' => 'required|max:255',
'content' => 'required'
]);
$tour_inputs = array_only(
$tour_inputs.
[
'title',
'content',
]
);
$tour = Tour::create($tour_inputs);
if($request->hasFile('featured_image')) {
$image = $request->file('featured_image');
$filename = $image->getClientOriginalName();
$location = public_path('images/featured_image/'.$filename);
Image::make($image)->resize(800, 600)->save($location);
$featuredImage = $tour->featuredImage()->save(new FeaturedImage([
'name' => $filename,
'path' => $location,
]));
}
Remember to define the $fillables inside your models, your models should look like this,
do check your relations, that you've made in the models, according to me they aren't correct:
class Tour extends Model
{
protected $fillables = [
'title',
'content',
];
public function featuredImage()
{
return $this->hasOne('App\FeaturedImage');
}
}
class FeaturedImage extends Model
{
protected $fillables = [
'name',
'path',
'tour_id',
];
public function tour()
{
return $this->belongsTo('App\Tour');
}
}
Hope this helps!
From your code the relationships that you have defined are in reverse order.
I mean logically, a Tour has one FeaturedImage and a FeaturedImage belongs to a Tour.
class Tour extends Model
{
//Mass Assignable fields for the model.
$fillable = ['title', 'content'];
public function featuredimage()
{
return $this->hasOne('App\FeaturedImage');
}
}
and
class FeaturedImage extends Model
{
//Mass Assignable fields for the model
$fillable = ['tour_id', 'name', 'path'];
public function tour()
{
return $this->belongsTo('App\Tour');
}
}
Then in your controller
public function store(Request $request)
{
//validate the data
$this->validate($request, [
'title' => 'required|max:255',
'content' => 'required'
]);
//store the data
$tour = Tour::firstOrCreate([ //protection against duplicate entry
'title' => $request->get('title'),
'content' => $request->get('trip_code')
]);
if($tour) //if the Tour exists then continue
{
// save featured_image
if($request->hasFile('featured_image')){
$image = $request->file('featured_image');
$filename = $image->getClientOriginalName();
$location = public_path('images/featured_image/'.$filename);
Image::make($image)->resize(800, 600)->save($location);
$featured_image = $tour->featuredimage()->create([
'path' => $location,
'name' => $filename //if you have this field on your FeaturedImage
}
//you could also have an else block to redirect back if the input doesn't have a file
//redirect to
Session::flash('success','Tour is successfully created !');
return redirect()->route('tours.show',$tour->id);
}
else
{
//if there occurs any error display the error message and redirect back - probably with validation errors or exception errors
Session::flash('error','Error message');
return redirect()->back()->withInput()->withErrors();
}
}
And don't forget to add the mass assignable fields to the $fillable array on your models.
UPDATE
For cases where a single form submission includes database transactions in multiple tables, you should use a try{}catch{} to ensure that either all related transactions run without any issue or neither of the transactions go through - to avoid data discrepancy.
You can rewrite your controller code as
public function store(Request $request)
{
//validate the data
$this->validate($request, [
'title' => 'required|max:255',
'content' => 'required'
]);
//store the data
//use the DB::beginTransaction() to manually control the transaction
//You would ideally want to persist the data to the database only if the input provided by the user
//has valid inputs for Tour as well as FeaturedImage, in case if any one invalid input you do not
//want to persist the data
DB::beginTransaction();
try
{
//firstOrCreate gives protection against duplicate entry for tour with same title and content
$tour = Tour::firstOrCreate([
'title' => $request->get('title'),
'content' => $request->get('trip_code')
]);
//proceed further only if $tour exists
if($tour)
{
// get featured_image
if($request->hasFile('featured_image')){
$image = $request->file('featured_image');
$filename = $image->getClientOriginalName();
$location = public_path('images/featured_image/'.$filename);
Image::make($image)->resize(800, 600)->save($location);
//save the featured_image
$featured_image = $tour->featuredimage()->create([
'path' => $location,
'name' => $filename //if you have this field on your FeaturedImage
}
}
}
catch(\ValidationException $e)
{
//In case of validation error, rollback the database transactions to avoid data discrepancy.
DB::rollBack();
$errors = $e->getMessage();
Session::flash('error', 'Whoops.. Please check the provided inputs');
return redirect()->back()->withInput()->withErrors['errors', $errors];
}
catch(\Exception $e)
{
//In case of any other error, rollback the database transactions to avoid data discrepancy.
DB::rollBack();
$errors = $e->getMessage();
Session::flash('error', 'Whoops.. Something went wrong. Please try again');
return redirect()->back()->withInput()->withErrors['errors', $errors];
}
//If both the transactions to the database i.e. saving the Tour as well as FeaturedImage ran without problem
//Commit to the database
DB::commit();
//redirect to
Session::flash('success','Tour is successfully created !');
return redirect()->route('tours.show',$tour->id);
}
Hope this helps.

Laravel: Can't save user object to database

I'm following this Laravel login/register tutorial on YouTube and I ran into a problem.
It seems I cannot insert the data from the $user object into my database.
Everything I have so far works perfectly fine until I reach the $user->save() method.
The following is my AccountController.php. You'll notice that I'm using print_r to try and debug the process. The first print_r gets printed to my page, but the second never does: Laravel just stops and outputs a cryptic Whoops, looks like something went wrong. warning.
class AccountController extends BaseController {
public function getCreate()
{
return View::make('account.create');
}
public function postCreate()
{
$validator = Validator::make(Input::all(), array(
'email' => 'required|max:64|min:3|email|unique:users',
'name' => 'required|max:64|min:3',
'password' => 'required|max:64|min:6'
));
if ($validator->fails())
{
// Return to form page with proper error messages
return Redirect::route('account-create')
->withErrors($validator)
->withInput();
}
else
{
// Create an acount
$email = Input::get('email');
$name = Input::get('name');
$password = Input::get('password');
// Activation code
$code = str_random(64);
$user = User::create(array(
'active' => 0,
'email' => $email,
'username' => $name,
'password' => Hash::make($password),
'code' => $code
));
if ($user)
{
// Send the activation link
Mail::send('emails.auth.activate', array(
'link' => URL::route('account-activate', $code),
'name' => $name
), function($message) use($user) {
$message
->to($user->email, $user->username)
->subject('Jasl | Activate your new account');
});
return Redirect::route('home')
->with('success', 'One more step! You\'ll get an email from us soon. Please follow the activation link to activate your account.');
}
}
}
public function getActivate($code)
{
// Find user whose code corresponds to the one we've previously sent through email
$user = User::where('code', '=', $code)->where('active', '=', 0);
if ($user->count())
{
$user = $user->first();
$user->active = 1;
$user->code = '';
echo '<pre>', print_r($user), '<pre>';
if ($user->save())
{
echo '-----------------------';
echo '<pre>', print_r($user), '<pre>';
}
}
}
}
I've googled a bit and found out that I should create a $fillable array in my User class, so I did it:
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
protected $fillable = array('active', 'name', 'email', 'password', 'password_temp', 'code', 'salt', 'created_at', 'updated_at', 'pref_weight', 'pref_units', 'pref_time', 'pref_ener');
use UserTrait,
RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
}
Those are actually all the elements that my users table has.
This did not solve the problem.
What am I missing? Why isn't $user->save() working properly?
I got it.
My problem was that I created the id column of my users table with a custom name, user_id, instead of simply id. Apparently Laravel does not like this at all. The debugger pointed me to:
C:\xampp\htdocs\laravel\vendor\laravel\framework\src\Illuminate\Database\Connection.php
with the error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: update users set active = 1, code = , updated_at = 2015-01-20 21:28:14 where id is null)
I didn't know you shouldn't customize id columns. Renaming it solved the problem entirely and the database now updates correctly.
Thanks #patricus for the useful debugging tip, that's what allowed me to track this error down.

Laravel SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry

i am very new in Laravel and this is my first project in Laravel.As usual, first of all i am developing a full user authentication system.I can registered an single user,can send an user verification email and after clicking that link i can activate a new user account, can login and can logout.But after that whenever i am trying to registered another new user and after clicking the verification link , i am facing an exception which is,
Illuminate \ Database \ QueryException
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'users_code_unique' (SQL: update `users` set `code` = , `active` = 1, `updated_at` = 2014-07- 25 04:26:06 where `id` = 41)
now this is my route.php,
<?php
Route::get('/',array(
'as' =>'home',
'uses' =>'HomeController#index'
));
Route::get('/signin',array(
'as' =>'signin',
'uses' =>'AccountController#signinGet'
));
Route::get('/signup',array(
'as' => 'signup',
'uses' => 'AccountController#signupGet'
));
/*
/*
/Authenticated Group
*/
Route::group(array('before' => 'auth'),function(){
/*
/Sign Out(GET)
*/
Route::get('/signout',array
(
'as' => 'signout',
'uses' => 'AccountController#signoutGet'
));
});
/*
/UnAuthenticated Group
*/
Route::group(array('before' => 'guest'),function(){
/* CSRF Protect*/
Route::group(array('before' => 'csrf'),function(){
/*
/ Create Account(POST)
*/
Route::post('/signup',array(
'as'=> 'signup',
'uses'=>'AccountController#signupPost'
));
/*
/ Sign In(POST)
*/
Route::post('/signin',array(
'as' => 'signin-post',
'uses' => 'AccountController#signinPost'
));
});
/*
/ Sign In (GET)
*/
Route::get('/signin',array(
'as' => 'signin',
'uses' => 'AccountController#signinGet'
));
/*
/Create Account(GET)
*/
Route::get('/signup',array(
'as' => 'signup',
'uses'=> 'AccountController#signupGet'
));
Route::get('signup/account/activate/{code}',array(
'as' =>'activate-account',
'uses' =>'AccountController#activatePost'
));
});
?>
and this is my AccountController
<?php
class AccountController extends \BaseController {
public function signinGet()
{
return View::make('account.signin');
}
public function signinPost(){
$validator = Validator::make(Input::all(),array(
'email' => 'required|email',
'password' => 'required'
));
if($validator->fails()){
//redirect to the signin page
return Redirect::route('signin')
->withErrors($validator)
->withInput();
}else{
//Attempt user singin
$auth = Auth::attempt(array
(
'email' => Input::get('email'),
'password' => Input::get('password'),
'active' => 1
));
if($auth){
//Redirect To intented URL
return Redirect::intended('/');
}
else
{
return Redirect::route('signin')
->with('global','The username or password you provided is wrong or account not activated!');
}
}
return Redirect::route('signin')
->with('global','There is a problem Signing You in.');
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function signupGet()
{
return View::make('account.signup');
}
public function signupPost()
{
$validator = Validator::make(Input::all(), array(
'email' => 'required|max:255|email|unique:users',
'username' => 'required|min:3|unique:users',
'password' => 'required|min:6',
'password_again' => 'required|same:password'
)
);
if($validator->fails())
{
return Redirect::route('signup')
->withErrors($validator)
->withInput();
}else
{
$email = Input::get('email');
$username = Input::get('username');
$password = Input::get('password');
//Activation Code
$code = str_random(60);
$user = User::create(array(
'email' => $email,
'username' => $username,
'password' => Hash::make($password),
'code' => $code,
'active' => 0
)
);
if($user){
//User Activation Code Creation
Mail::send('emails.auth.activate', array('link' => URL::route('activate-account',$code), 'username' => $username),function($message) use ($user)
{
$message->to($user->email,$user->username)->subject('Activate Your Account');
});
return Redirect::route('signup')
->with('global','Your Account has been created! We have sent you an email to activate your account.Please Check the both the Inbox and Spam Folder.');
}
}
//return 'This is a Post Result';
}
public function activatePost($code){
$user = User::where('code','=',$code)->where('active','=',0);
if($user->count()){
$user = $user->first();
$user->active = 1;
$user->code = '';
if($user->save()){
return Redirect::route('home')
->with('global','Activated!.You can sign in now!');
}
}
else{
return Redirect::route('signup')
->with('global','Sorry!We could not activate your acount,please try again later.');
}
}
public function signoutGet(){
Auth::logout();
return Redirect::route('home');
}
}
?>
and this is my create user migration file
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration {
public function up()
{
Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->string('username',255)->unique();
$table->string('email',255)->unique();
$table->string('password',60);
$table->string('password_temp',60);
$table->string('code',60)->unique();
$table->integer('active');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('users');
}
}
?>
and this is my user.php
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
public function getRememberToken()
{
return $this->remember_token;
}
public function setRememberToken($value)
{
$this->remember_token = $value;
}
public function getRememberTokenName()
{
return 'remember_token';
}
protected $fillable = array('email','username','password','password_temp','code','active');
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
}
?>
now whats the problem?
Make sure your code field is nullable, then instead of setting it's value to empty string, make it null:
$code = null;
Then you will be able to save it as NULL (MySQL) while it remains unique.
Also change this one:
$user = User::where('code','=',$code)->where('active','=',0);
if($user->count()){
$user = $user->first();
To:
$user = User::where('code','=',$code)->where('active','=',0)->first();
if(count($user)){
You don't need to call db twice, just check if returned result is not null (count will do), meaning it returned a User object.
your problem can use validator to check. simply use as this:
use Validator;
use Request;
//...
//unique will pre check the key code weather if unique in tbl_name
public function yourfunc(Request $request) {
// set the rules to check
$rules = ['code'=>'required|unique:tbl_name'];
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
// handler errors
$erros = $validator->errors();
}
//... everything is ok here
}
you can explore more at laravel validation
I found it. You've set code column as unique, though you're setting it to empty string after user click an activation link. And there already is a row in table with code=''; so it throws an error. The problem is here (activatePost):
$user->code = '';
So either don't empty it, set it to something else or set db colums as not unique.
I would leave the code without emptying it and additionally I would check if user was activated - a simple if in activatePost. Maybe it's a good idea to verify user not only according to code, but also with a hashed id in link.
There a few things you need to do to improve your code. But duplicate entry usually happens when you set a column to unique and tries to re inset the same data into another row. The most time it get confusing is when you check your table and and find the column empty. Whoop! When a column is set to unique and empty, it means no other column can contain empty data.
In simple terms the form of the column can not be duplicated, either null or with data.
Integrity constraint violation Duplicate entry problems are due to database schema inconsistence being detected by laravel.
Integrity constraint violation Duplicate entry problems are likely to occur when the database schema was preserved by laravel migration, and then the db scheme is updated somehow outside of laravel migration's control (eg. developers manually (without via performing a laravel migration) alter the db schema in a db client OR the db scheme is updated by importing a piece of SQL dump that is inconsistent with the db scheme -- as a result of that, the importing unexpectedly updates the laravel-migration-preserved db schema.
To avoid the second kind of harm, be careful when importing SQL dump data into db: ensure the SQL dump data is consistent with the current db schema before your SQL dump is imported.
Overall, when doing laravel development, the db schema should always be preserved by laravel migration to avoid db schema inconsistence.

How to use Sentry 2 in Laravel 4

I have a Personcontroller and a Festivalcontroller in my laravel4 application. The actions in those controllers can only be accessible by an administrator.
If my database only has a user with test#hotmail.com, that user can access the routes of those 2 controllers. If my database has no user with test#hotmail.com, but it has other users, those other users can't access the routes of those 2 controllers. And when my database has a user with test#hotmail.com, and has other users, everyone can access the routes of those 2 controllers.
I only want the user with email test#hotmail.com to access the routes of those controllers.
I installed Sentry2 by doing this:
In composer.json file require:
"cartalyst/sentry": "2.0.*"
Run
php composer.phar update
In app > config > app.php:
'Cartalyst\Sentry\SentryServiceProvider', => to the providers array
'Sentry' => 'Cartalyst\Sentry\Facades\Laravel\Sentry', => to the aliases array
After the installation I made the SentrySeeder file:
<?php
class SentrySeeder extends Seeder {
public function run()
{
DB::table('users')->delete();
DB::table('groups')->delete();
DB::table('users_groups')->delete();
Sentry::getUserProvider()->create(array(
'email' => 'test#hotmail.com',
'password' => "test",
'activated' => 1,
));
$user = Sentry::getUserProvider()->findByLogin('test#hotmail.com');
$adminGroup = Sentry::getGroupProvider()->findByName('Test');
$user->addGroup($adminGroup);
}
}
In my PersonController
class PersonController extends BaseController {
public function index()
{
try
{
$user = Sentry::findUserByLogin('test#hotmail.com');
if ($user)
{
$person = Person::with('user')->orderBy('person_id')->paginate(10);
return View::make('persons.index')
->with('person', $person);
}
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User was not found.';
}
}
}
Login action in LoginController
public function login()
{
$input = Input::all();
$rules = array(
'user_email' => 'required',
'user_password' => 'required'
);
$validator = Validator::make($input, $rules);
if ($validator->fails()) {
return Redirect::to('login')
->withErrors($validator) // send back all errors to the login form
->withInput(Input::except('user_password'));
}
else {
$attempt = Auth::attempt([
'user_email' => $input['user_email'],
'password' => $input['user_password']
]);
if ($attempt) {
return Redirect::to('/home');
}
else {
return Redirect::to('login');
}
}
Store a user in database
public function store()
{
$input = Input::all();
$rules = array(
'user_email' => 'required|unique:users|email',
'user_username' => 'required|unique:users',
);
$validator = Validator::make($input, $rules);
if($validator->passes())
{
$password = $input['user_password'];
$password = Hash::make($password);
$location = new Location();
$person = new Person();
$user = new User();
$person->person_firstname = $input['person_firstname'];
$person->person_surname = $input['person_surname'];
$user->user_username = $input['user_username'];
$user->user_email = $input['user_email'];
$user->user_password = $password;
$location->save();
$person->save();
$user->location()->associate($location);
$user->person()->associate($person);
$user->save();
Session::flash('message', 'Successfully created user!');
return Redirect::to('login');
}
else {
return Redirect::to('persons/create')->withInput()->withErrors($validator);
}
}
Looks like you need to use your own users table and also use Sentry's. So you'll need to add related Sentry's columns to yours. It's easy:
1) Go to vendor\cartalyst\sentry\src\migrations.
2) Create one new migration for every file you see there, example:
php artisan migrate:make add_sentry_groups_table
3) Copy the up() and down() code (ONLY!) to your new migrations.
4) And, for the users migration, you'll have to do some changes:
Instead of Schema::create('users' ... you do Schema::table('users' ..., to add more columns to your table.
Delete all commands for columns that you alread have in your current users table, examples of lines you must delete:
$table->increments('id');
$table->timestamps();
5) Run a normal ´php artisan migrate´.
After that you should have the Sentry's tables ready to work.
EDIT
As you're not using the usual 'email' and 'password' columns, publish Sentry's configuration:
php artisan config:publish cartalyst/sentry
And alter
'login_attribute' => 'user_email',

Categories