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.
Related
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']);
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);
}
}
I am working in Laravel, and I have a model Group where I have rules for validation. I am attempting to have a unique name_group but only for the given year. The code below works perfectly if I replace .$this->year_groups with 2016 for example. But when I try to add the actual year of the group to be created by concatenating .this->year_groups, I get a syntax error:
Symfony \ Component \ Debug \ Exception \ FatalErrorException syntax error, unexpected '.', expecting ')'
I have looked at many examples and they (seem) to be written this way, and I just can't find what is wrong. I am thinking perhaps it has something to do that this is in an array...?
Any help would be greatly appreciated!!
Model:
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class Group extends Eloquent implements UserInterface,RemindableInterface
{
use UserTrait, RemindableTrait;
protected $table = 'groups';
protected $primaryKey = "id_groups";
protected $fillable = array('name_groups','year_groups','grados_id_grados');
//The error is in the following $rules
public static $rules = array(
'year_groups'=> 'required',
'name_groups'=> 'required|unique:groups,name_groups,NULL, id_groups,year_groups,' . $this->year_groups,
'grados_id_grados' => 'required'
);
public function grado()
{
return $this->belongsTo('Grado','grados_id_grados');
}
public function students()
{
return $this->belongsToMany('Student','group_student','id_group','id_student')->withTimestamps();
}
public function teachers()
{
return $this->belongsToMany('Teacher','group_subject_teacher','id_group','id_teacher')->withPivot('id_subject','year_groups')->withTimestamps();
}
}
In the Controller I call validation from the store method:
public function store()
{
$input = Input::all();
$validation = Validator::make($input, Group::$rules);
if($validation->passes()){
$group = new Group;
$group->name_groups = Input::get('name_groups');
$group->year_groups = Input::get('year_groups');
$group->grados_id_grados = Input::get('grados_id_grados');
$group->save();
}
}
Looking your code, it seems $rules is variable or property of class. The way you are assigning values to property are wrong, so it is throwing error. Look below code and arrange your code accordingly:-
class anyClass {
private $year_groups = "2016";
public $rules = [];
public function __construct(){
$this->rules = array(
'year_groups'=> 'required',
'name_groups'=> 'required|unique:groups,name_groups,NULL, id_groups,year_groups,'.$this->year_groups,
'grados_id_grados' => 'required'
);
}
}
I changed Model to:
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class Group extends Eloquent implements UserInterface,RemindableInterface
{
use UserTrait, RemindableTrait;
protected $table = 'groups';
protected $primaryKey = "id_groups";
protected $fillable = array('name_groups','year_groups','grados_id_grados');
//This part I changed
public static $rules = [];
public static function _construct($year){
$rules = array(
'year_groups'=> 'required',
'name_groups'=> 'required|unique:groups,name_groups,NULL, id_groups,year_groups,' . $year,
'grados_id_grados' => 'required'
);
return $rules;
}
public function grado()
{
return $this->belongsTo('Grado','grados_id_grados');
}
public function students()
{
return $this->belongsToMany('Student','group_student','id_group','id_student')->withTimestamps();
}
public function teachers()
{
return $this->belongsToMany('Teacher','group_subject_teacher','id_group','id_teacher')->withPivot('id_subject','year_groups')->withTimestamps();
}
}
Then in Controller:
public function store()
{
$input = Input::all();
$validation = Validator::make($input, Group::_construct(Input::get('year_groups')));
if($validation->passes()){
$group = new Group;
$group->name_groups = Input::get('name_groups');
$group->year_groups = Input::get('year_groups');
$group->grados_id_grados = Input::get('grados_id_grados');
$group->save();
}
}
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');
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}",
]);
}