laravel 5 multi form data save in database - php

I use two different forms and connected to database it's working fine. But when I do an insert values stored as two different rows in database.
When do we have to use seeder? Is what I wrote coding proper laravel 5?
Controller file
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Requests\ListFormRequest;
use App\Http\Requests\LoginFormRequest;
use Illuminate\Support\Facades\Input;
use Illuminate\Http\Request;
use Response;
use App\Test;
class testController extends Controller {
public function test()
{
return view('test',array('title' => 'test'));
}
public function lockTest(ListFormRequest $test)
{ $user = new Test();
$user->firstname = Input::get('firstname');
$user->password = Input::get('password');
$user->email = Input::get('email');
$user->save();
return view('login');
}
public function login()
{
return view('login',array('title' => 'login'));
}
public function userLogin(LoginFormRequest $test1)
{
$user = new Test();
$user->lastname = Input::get('lastname');
$user->middlename = Input::get('middlename');
$user->save();
return Response::make('Sucessfully Registered!');
}
}
Route file
<?php
Route::get('/', 'testController#test');
Route::post('login', 'testController#lockTest');
Route::get('login', 'testController#login');
Route::post('userLogin', 'testController#userLogin');
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
Seeder file
<?php
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
use App\Test;
class TestsSeeder extends Seeder {
public function run() {
DB::table('users')->truncate();
$qwerty = Input::all();
foreach($qwerty as $qwertySingle) {
Test::create([
'firstname' => $qwertySingle->firstname,
'password' => $qwertySingle->password,
'email' => $qwertySingle->email,
'lastname' => $qwertySingle->lastname,
'middlename' => $qwertySingle->middlename,
]);
}
DB::table('tests')->insert($qwerty);
}
}
Model file
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
use App\DB;
class Test extends Model {
protected $guarded = array();
protected $table = 'tests';
protected $fillable = ['firstname', 'password', 'email', 'lastname', 'middlename'];
}

The seeder is used when you want to populate your database with fake data, so you can test the waters of your app with thousands of dummy records.
The run method from your seeder should be something like the following, to give you some ideas:
Test::truncate();
Test::unguard();
$password = Hash::make('secret');
foreach (range(1, mt_rand(10, 20)) as $index) {
Test::create([
'firstname' => "first name {$index}",
'password' => $password,
'email' => "myemail{$index}#mydomain.com",
'lastname' => "last name {$index}",
'middlename' => "middlename {$index}",
]);
}

Related

codeigniter 4, update model

I connected my codeigniter app with mysql. I created a table model like that:
<?php namespace App\Models;
use CodeIgniter\Model;
class UserModel extends Model{
protected $table = 'I_user';
protected $allowedFields = ['email', 'password','active', 'hash'];
}
And now in my Controller, I want to update user by changing email for example. How to do that?
My controller:
<?php namespace App\Controllers;
use App\Models\UserModel;
class Confirm extends BaseController
{
public function index($email, $hash)
{
if(!isset($email) || !isset($hash)){
return redirect()->to('/');
}
$model = new UserModel();
$user = $model->where('email', $email)->first();
if($user['hash'] == $hash){
// update $user email..
??
}
}
}
You can do it in such way:
$model->where('email', $user['email'])->set(['email' => 'YourNewEmailAddress'])->update();
or
$model->update(['email'=> $user['email']], ['email' => 'YourNewEmailAddress']);
You could use update directly to the model data
$data = [
'email' => 'Yourupdatedemailhere'
];
$model->update($user['email'], $data);
If the Primary key is not "id" in your data-table, then you need to mention that in your Model.
protected $primaryKey = 'email';
Then use:
$model->update(['email'=> $user['email']], ['email' => 'newemail#example.com']);

Auth::attempt returns false when credentials are true

I have spent countless hours on this. Looked through the internet and cannot find a solution. The data is being passed through the form but will not authenticate with the database. The password is hashed upon registration also.
I have dumped the inputs and the credentials are being posted but will authenticate through the database. Any help is appreciated Thanks in advance!
Routes
Route::get('/login', function() {
return view('pages.login');
});
Route::get('/register', function() {
return view('pages.register');
});
Route::post('/register_action', [
'uses' => 'RegisterController#store',
'as' => 'signup'
]);
Route::post('/login_action', [
'uses' => 'LoginController#LogIn',
'as' => 'signin'
]);
Route::get('/dashboard', [
'uses' => 'RegisterController#getDashboard',
'as' => 'dashboard'
]);
Login Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\User;
use Input;
class LoginController extends Controller
{
public function LogIn(Request $request) {
$data = array(
'email' => Input::get('useremail'),
'password' => Input::get('userpass'),
);
dd($data);
if(Auth::attempt($data)) {
return redirect()->route('dashboard');
}else {
echo "Fail";
}
}
}
Register Controller
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Input;
class RegisterController extends Controller
{
public function getDashboard() {
return view('pages.dashboard');
}
public function store(Request $request) {
$username = $request['username'];
$email = $request['email'];
$first_name = $request['userfname'];
$last_name = $request['userlname'];
$password = bcrypt($request['password']);
$user = new User();
$user->email = $email;
$user->username = $username;
$user->firstname = $first_name;
$user->lastname = $last_name;
$user->password = $password;
$user->save();
return redirect()->route('dashboard');
}
}
You should check your database migration.Password hushing needs at least 120 char.

Laravel: PDOException in Connection.php line 319: SQLSTATE[42S02]

During database update, I try to validate my inputs, but I get this error message every time (clicked on submit button):
PDOException in Connection.php line 319: SQLSTATE[42S02]: Base table
or view not found: 1146 Table 'app_db.user_id' doesn't exist
Without validation my update works on the user_details table.
UserDetailsController.php
<?php
namespace App\Http\Controllers;
use Session;
use App\UserDetails;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
class UserDetailsController extends Controller
{
public function index()
{
$details = UserDetails::all()->where('user_id', \Auth::user()->id);
return \View::make('pages.personal_datas')
->with('details', $details);
}
public function update()
{
$details = UserDetails::where('user_id', \Auth::user()->id)->first();
$validator = UserDetails::validate(Input::all());
if($validator->fails())
{
$messages = $validator->messages();
return redirect()->action('UserDetailsController#index')
->withErrors($validator);
}
else
{
$details->email = Input::get('email');
$details->phone = Input::get('phone');
$details->country = Input::get('country');
$details->city = Input::get('city');
$details->address = Input::get('address');
$details->save();
Session::flash('message', 'Successfully updated!');
return redirect()->action('UserDetailsController#index');
}
}
}
UserDetails.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Validator;
class UserDetails extends Model
{
public $timestamps = false;
protected $guarded = [];
protected $primaryKey = 'user_id';
protected $table = 'user_details';
public static $rules = array(
'email' => 'email|unique:user_id|required',
'phone' => 'min:11|required',
'country' => 'min:4|required',
'city' => 'min:2|required',
'address' => 'min:4|required',
);
public static function validate($data)
{
return Validator::make($data, static::$rules);
}
}
UPDATE
Your issue lies with your validation of the user email
unique:user_id -> unique:user_details, user_id should be the proper rule format
full rule will read: 'email' => 'email|unique:user_details,user_id|required'
Your original validation rule is trying to query the user_id table, which doesn't exist.

Laravel manual auth - Never works

I am trying to make Auth for an API Rest manually, but the response for Auth::attempt is always false.
Route
Route::group(["prefix"=>"api"], function(){
Route::post('/login', [
'as' => 'checkLogin',
'uses' => 'LoginCtrl#checkLogin'
]);
});
Controller
class LoginCtrl extends Controller
{
public function checkLogin(Request $request){
$input = $request->all();
if(Auth::attempt(['username' => $input['user'], 'password' => $input['password']])){
$data = ["response"=>true,"access_token"=>"test"];
}else{
$data = ["response"=>false,"access_token"=>"none"];
}
return response()->json($data);
}
}
I have userd Hash::make to encrypt the password on the user creation.
My model is:
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
protected $table = "usuarios";
protected $username = 'username';
protected $fillable = [
'name', 'username', 'password'
];
protected $hidden = [
//'password', 'remember_token',
];
public $timestamps = false;
public function access_token(){
return $this->hasOne('App\AccessToken');
}
}
What am I doing wrong?
EDIT
$user = new User();
$user->username = "myFreshUsername";
$user->password = Hash::make('userPwd');
$user->save();
Thats my user creation. If this helps I didn't launch `php artisan make:auth', may this order be necessary?
of course it always false because you did not use correct way to get the json in your request using laravel
the correct way is
$input = $request->json()->all();
not
$input = $request->all();
so your controller would be like this
class LoginCtrl extends Controller
{
public function checkLogin(Request $request){
$input = $request->json()->all();
if(Auth::attempt(['username' => $input['user'], 'password' => $input['password']])){
$data = ["response"=>true,"access_token"=>"test"];
}else{
$data = ["response"=>false,"access_token"=>"none"];
}
return response()->json($data);
}
}

Laravel : How to update data in one to one Eloquent relationship

I have two tables:
1. User.
2. Post.
In post table i have saved the user information. So when I click on update, it should load the particular user data. It's get loaded but when i click on the save button to update save.It's showing the following Error.
FatalErrorException in PostController.php line 78: Call to undefined
function App\Http\Controllers\fill()
I think i have problem with my postUpdate controller. But I couldn't find the problem.
Here is my User model:
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
public function post()
{
return $this->hasOne('App\Post'); //Profile is your profile model
}
}
Here is my Post Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = [
'first_name', 'middle_name', 'last_name','gender', 'dob','nationality','nid','email','phone_no','about_me'
];
public function user()
{
return $this->belongsTo('App\User'); //Profile is your profile model
}
}
And here is my post Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Requests;
use App\Post;
use App\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;
class PostController extends Controller
{
public function getDashboard()
{
$posts = Post::all();
return view('dashboard',['posts'=>$posts]);
}
public function postCreate(Request $request){
$this->validate($request,[
'first_name'=> 'required|max:120',
'middle_name'=> 'required|max:120',
'last_name' => 'required|max:120',
'gender'=> 'required',
'dob'=>'required',
'nationality'=>'required',
'nid'=>'required',
'email' => 'required|email|unique:users',
'phone_no'=>'required',
'about_me'=>'required',
]);
$post = new Post();
$post->first_name = $request['first_name'];
$post->middle_name = $request['middle_name'];
$post->last_name = $request['last_name'];
$post->gender = $request['gender'];
$post->dob = $request['dob'];
$post->nationality = $request['nationality'];
$post->nid = $request['nid'];
$post->email = $request['email'];
$post->phone_no = $request['phone_no'];
$post->about_me = $request['about_me'];
$message='There was an Error';
if( $request->user()->post()->save($post)){
$message = "Profile Created successfully";
}
return redirect()->route('dashboard')->with(['message' => $message]);
}
public function postUpdate(Request $request)
{
$this->validate($request,[
'first_name'=> 'required|max:120',
'middle_name'=> 'required|max:120',
'last_name' => 'required|max:120',
'gender'=> 'required',
'dob'=>'required',
'nationality'=>'required',
'nid'=>'required',
'email' => 'required|email|unique:users',
'phone_no'=>'required',
'about_me'=>'required',
]);
$request->user()->post()->update(fill($request->all())) ;
return redirect()->route('dashboard');
}
}
Here, you're getting a collection of posts:
$data=Post::all();
But you need to pass an array. Try to replace it with:
$data = $request->only('first_name', 'middle_name', 'last_name', 'gender', 'dob', 'nationality', 'nid', 'email', 'phone_no', 'about_me');

Categories