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');
Related
While i was working on my laravel project i got this error and i am unable to solve it even after so much changes and effort. I hope i get some solution.
My ERROR:
Symfony\Component\Debug\Exception\FatalThrowableError thrown with
message "Class 'App/Post' not found"
CommentsController.php
<?php
namespace App\Http\Controllers;
use \Auth;
use App\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Http\Requests;
use App\Comment;
use Session;
use DB;
class CommentsController extends Controller
{
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required',
'comment' => 'required'
]);
$post = Post::find('id');
$comments = new Comment();
$comments->name = $request->name;
$comments->email = $request->email;
$comments->comment = $request->comment;
$comments->approved = true;
$comments->post()->associate($post);
$comments->save();
Session::flash('success', 'Comment was added');
return redirect()->route('posts.show', [$post->id]);
//return redirect('/posts')->with('success', 'Comment Created
Successfully');
}
}`
Post.php
`
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
//Table Name
protected $table = 'posts';
//Primary Key
public $primaryKey = 'id';
//Timestamps
public $timestamps = true;
public function user(){
return $this->belongsTo('App\User');
}
public function comment(){
return $this->hasMany('App\Comment');
}
}
`
My Web.php (Route File)
`
Route::get('/', 'PagesController#index');
Route::get('/about', 'PagesController#about');
Route::get('/contact', 'PagesController#contact');
Route::get('/services', 'PagesController#services');
// Post Pages
Route::resource('posts', 'PostsController');
// Login Authorization
Auth::routes();
// Dashboard
Route::get('/dashboard', 'DashboardController#index');
// Comments
Route::post('/posts/{post_id}', ['uses'=>'CommentsController#store' , 'as' => 'comments.store']);
`
Write this code top of the controller....
use App\Post;
or
Change this code...
$post = Post::find('id');
To
$post = \App\Post::find('id');
I think this is solved.
pay attention about file Post.php
use App\Post;
just A is Capital not all APP
Model ListDeals
class ListsDeals extends Model
{
protected $table = "deals";
protected $fillable = ['title', 'slug', 'description', 'price', 'has_discount', 'price_to_discount', 'price_reduced', 'status', 'approved', 'suspended', 'start_date', 'end_date'];
public function lists()
{
return $this->belongsToMany('App\Models\Lists', 'list_has_deals' , 'deal_id', 'list_id')->withPivot('list_id');
}
public function user(){
return $this->belongsTo('App\Models\User');
}
Model Lists
class Lists extends Model
{
protected $table = "lists";
protected $fillable = ['title', 'slug', 'short_description', 'description', 'website', 'email', 'phone', 'lat_map', 'lng_map', 'address_reference', 'video', 'renewal_date', 'status', 'approved', 'suspended'];
public function categories()
{
return $this->belongsToMany('App\Models\ListsCategories', 'list_has_categories' , 'list_id', 'category_id');
}
public function deals()
{
return $this->belongsToMany('App\Models\ListsDeals', 'list_has_deals' , 'list_id', 'deal_id');
}
public function user(){
return $this->belongsTo('App\Models\User');
}
Pivot Table list_has_deals
id
list_id
deal_id
Controller HomePageController
namespace App\Http\Controllers;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth;
use App\Models\User;
use App\Models\Lists;
use App\Models\ListsCategories;
use App\Models\ListsDeals;
use DB;
class HomePageController extends Controller
{
public function homepage(){
$matchThese = [ 'suspended' => 0, 'status' => 1, 'approved' => 1 ];
$deals = ListsDeals::where( $matchThese )->limit( 3 )->offset( 0 )->orderBy( 'start_date' )->get();
return view( "homepage" )
->with( "deals", $deals );
}
}
I want get in the view the same categories of the list for the deal in the HomePageController, but i dont kwno thw way, i try with withPivot('list_id') but i dont get the id of the list, thank for the help.
Check out the section Retrieving Intermediate Table Columns
https://laravel.com/docs/5.4/eloquent-relationships#many-to-many
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.
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 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}",
]);
}