I got HTTP ERROR 500 after putting using models in the routes file.
Here is the routes file code:
use App\User;
use App\Address;
Route::get('/hesham', function () {
return view('welcome');
});
Route::get('/insert', function(){
$user = User::findOrFail(1);
$address = Address::create([
'name'=>'1234 Housten av New York',
'user_id' => $user->id
])
$user->address()->save($address);
});
Home Route is working fine, but /insert is giving 500 ERROR
Here is the user model
User.php
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
public function address(){
return $this->hasOne('App\Address');
}
Here is the Address model
Address.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Address extends Model
{
//
}
public function user(){
return $this->belongsTo('App\User');
}
public function address(){
return $this->hasOne('App\Address');
}
and conversely:
public function user(){
return $this->belongsTo('App\User');
}
To associate an address with a user, do this:
Address::create([
'name'=>'1234 Housten av New York',
'user_id' => $user->id
])
edit
try this:
$address = new Address();
$address->user_id = $user_id;
$address->name = '1234 Housten av New York'
$address->save();
Related
User Model:
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function venues()
{
return $this->hasMany(Venue::class);
}
public function profile()
{
return $this->hasOne(Profile::class);
}
}
Venue Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Venue extends Model
{
use HasFactory;
protected $fillable = ['user_id', 'city_id', 'category_id', 'title', 'address', 'phone', 'email', 'website', 'facebook', 'instagram', 'content_bg', 'content_en', 'cover_image', 'lat', 'lng'];
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
public function category()
{
return $this->belongsTo(Category::class, 'category_id');
}
public function city()
{
return $this->belongsTo(City::class, 'city_id');
}
public function features()
{
return $this->belongsToMany(Feature::class, 'venue_feature');
}
public function images()
{
return $this->hasMany(VenueImage::class);
}
public function reviews()
{
return $this->hasMany(Review::class);
}
}
Everything is fine, but now I want to have two methods where to call active / inactive venues of the user and I'm not sure where to place them in User Model or in Venue Model, generally which is better?
If I put them in Venue model (getUserActiveVenues and getUserInactiveVenues) and pass authenticated user to these methods, or to put them in User model (getActiveVenues and getInactiveVenues).
add relations to the user model
public function venues()
{
return $this->hasMany(Venue::class);
}
public function activeVenues()
{
return $this->hasMany(Venue::class)->where('active',true);
}
public function inActiveVenues()
{
return $this->hasMany(Venue::class)->where('active',false);
}
then you can eager load the relevant type of venue. I had to guess at what you mean be 'active'
I'm trying to see username and email columns that of which are SQL db columns in my payload but for some reason it doesn't show up. I'm using React as frontend and Laravel as backend and for some reason, I'm not seeing them.
What could I be doing wrong?
Here's User.php model:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'username', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function posts() {
return $this->hasMany(Post::class);
}
}
Here's Posts.php model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = ['body'];
public function user() {
$this->belongsTo(User::class);
}
}
Here's PostController.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
class PostController extends Controller
{
public function create(Request $request, Post $post) {
// create post
$createdPost = $request->user()->posts()->create([
'body' => $request->body
]);
// return response
return response()->json($createdPost);
}
}
Here's web.php:
Auth::routes();
Route::group(['middleware' => ['auth']], function () {
Route::post('/posts', 'PostController#create');
});
Here's my post request:
constructor(props) {
super(props);
this.state = {
body: '',
posts: []
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleSubmit(e) {
e.preventDefault();
// this.postData();
axios.post('/posts', {
body: this.state.body
}).then(response => {
console.log(response);
this.setState({
posts: [...this.state.posts, response.data]
});
});
this.setState({
body: ''
});
}
You missed the return key :).
public function user()
{
return $this->belongsTo('App\User');
^^^^^^
}
I believe you are not passing the foreign key correctly,
protected $fillable = ['body', 'user_id'];
public function user()
{
$this->belongsTo('App\User', 'user_id');
}
I'm having some problems trying to return a view with the user address.
I don't know if the real problem is in my controller or in my models. I'd like to know the correct way to return a user with his address creating a relationship with the models.
Address Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Address extends Model {
protected $fillable = ['name','last_name','street_address','street_address2', 'country', 'city', 'state-province', 'phone-number', 'phone-number2', 'address-type'];
public function user() {
return $this->hasOne('App\User');
}
}
User Model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'first_name', 'last_name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function address() {
return $this->belongsTo('App\Address');
}
}
In the UserController, I'm using the method getAddress, but I really don't know how to get the user address and how to create a user with that relation.
UserController
namespace App\Http\Controllers;
use App\User;
use App\Address;
use Illuminate\Http\Request;
use App\Http\Requests;
use Auth;
class UserController extends Controller
{
public function userProfile() {
$user = Auth::user();
return view('user.profile', ['user' => $user]);
}
public function userAccount(User $user) {
$user = Auth::user();
return view('user.account', compact('user'));
}
public function nameUpdate(User $user)
{
$this->validate(request(), [
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255'
]);
$user->first_name = request('first_name');
$user->last_name = request('last_name');
$user->save();
return redirect()->back();
}
public function emailUpdate(User $user)
{
$this->validate(request(), [
'email' => 'required|string|email|max:255|unique:users',
]);
$user->email = request('email');
$user->save();
return redirect()->back();
}
public function passwordUpdate(User $user) {
$this->validate(request(), [
'password' => 'required|min:8|confirmed',
]);
$user->password = bcrypt(request('password'));
$user->save();
return redirect()->back();
}
public function getAddress() {
$user=Auth::user();
$adress = $user->adress;
}
}
First of all you must reverse the relationship so that the address belongs to the user. If a user can have multiple addresses then a user cannot belong to each of those addresses. The addresses must belong to the user.
In the address table you will need a user_id column to start with.
User.php
public function addresses()
{
return $this->hasMany(Address::class);
}
Address.php
public function user()
{
return $this->belongsTo(User::class);
}
Then you can simply get all the addresses like so:
foreach(Auth::user()->addresses as $address){
//You can now access your address here
}
Your current controller:
public function getAddresses() {
$user = Auth::user();
$addresses = $user->addresses;
return $addresses;
}
In a blade file you could do something like:
#foreach(Auth::user()->addresses as $address){
<li>{{ $address->column_name }}</li>
}
Following are my relations in laravel , I am unable to access company using User's Object, but i am getting null when i try to access it, please see my code below to get the picture
following are my models
<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Zizaco\Entrust\Traits\EntrustUserTrait;
use Session;
use Illuminate\Support\Facades\DB;
class User extends Authenticatable
{
use Notifiable;
use EntrustUserTrait;
protected $table = 'tbl_users';
protected $primaryKey = 'id';
protected $guarded = ['id'];
const API = 'api';
const WEB = 'web';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'last_login', 'Address', 'Age', 'DateOfBirth', 'created_by', 'deleted_by'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'is_admin' => 'boolean',
];
public function isAdmin()
{
return $this->is_admin;
}
static function GetUserNamebyID($id)
{
$name = User::select("name")->where(["id" => $id])->pluck('name');
if (isset($name[0])) {
return $name[0];
} else {
return '';
}
}
public function loginlogout()
{
$this->hasMany("App\Models\LoginLogoutLogs", 'userID');
}
public function company()
{
$this->hasMany("App\Models\Company", "company_id");
}
}
And following is my companies Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use DB;
use App\Models\CarePlanData;
use Session;
class Company extends Model
{
protected $table = 'companies';
protected $primaryKey = 'id';
protected $guarded = ['id'];
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'phone_no', 'address', 'password', 'description', 'city', 'company_logo', 'country', 'email'
];
static public function fetchAllActiveCompanies()
{
return DB::table("companies")->where(['is_active' => 1])->pluck('name', 'id');
}
// change company to hasmany
public function users()
{
return $this->hasmany('App\Models\User');
}
}
and this is how i am trying to access the Company , but i am getting null.
public function fetchCompany(){
$User = User::find($user->id);
dd($User->company());
}
First of all if a user belongs to 1 company then it should be:
public function company()
{
$this->belongsTo("App\Models\Company", "company_id");
}
then fetchCompany() should be
public function fetchCompany(){
$User = User::with('company')->find($user->id);
dd($User->company);
}
You need to use with to load the relations. You pass the name of the function which defines the relation in your User model to with like this with('function_name').
Your actual question is:
You have belongTo Relation between User and Company but when you trying to access the Company via user object, you get null
In your User.php Model put the following function but if you already have then leave it:
public function company()
{
$this->belongsTo("App\Models\Company", "company_id");
}
Then
Replace this function:
public function fetchCompany(){
$User = User::find($user->id);
dd($User->company());
}
To is one:
public function fetchCompany(){
$User = User::find($user->id);
if($User){
dd($User->company()->get());
}
}
or to this one:
public function fetchCompany(){
$User = User::find($user->id);
if($User){
dd($User->company);
}
}
actually if your company_id field is on user model, then your relation should be
public function company()
{
$this->belongsTo("App\Models\Company", "company_id");
}
unless a user can have many companies ?
Hi following are my relations
User Model
public function loginlogout()
{
$this->HasMany("App\Models\LoginLogoutLogs");
}
and this is my LoginLogoutLogs Model
public function users()
{
return $this->belongsTo('App\Models\User');
}
I am trying to access name from Users like this
$loginLogoutLogs = LoginLogoutLogs::all();
foreach($loginLogoutLogs as $loginLogoutLog){
dd($loginLogoutLog->users()->name);
}
but i am getting this error
Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$name
EDIT Adding Models
<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Zizaco\Entrust\Traits\EntrustUserTrait;
use Session;
use Illuminate\Support\Facades\DB;
class User extends Authenticatable
{
use Notifiable;
use EntrustUserTrait;
protected $table = 'tbl_users';
protected $primaryKey = 'id';
protected $guarded = ['id'];
const API = 'api';
const WEB = 'web';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'last_login', 'Address', 'Age', 'DateOfBirth', 'created_by', 'deleted_by'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'is_admin' => 'boolean',
];
public function isAdmin()
{
return $this->is_admin;
}
static function GetUserNamebyID($id)
{
$name = User::select("name")->where(["id" => $id])->pluck('name');
if (isset($name[0])) {
return $name[0];
} else {
return '';
}
}
public function loginlogout()
{
$this->HasMany("App\Models\LoginLogoutLogs", 'userID');
}
public function company()
{
$this->HasMany("App\Models\Company");
}
}
And now LoginLogouts Model
<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Zizaco\Entrust\Traits\EntrustUserTrait;
use Illuminate\Database\Eloquent\Model;
use Session;
use Illuminate\Support\Facades\DB;
class LoginLogoutLogs extends Model
{
use Notifiable;
use EntrustUserTrait;
protected $table = 'tbl_users_logs';
protected $primaryKey = 'id';
protected $guarded = ['id'];
const API = 'api';
const WEB = 'web';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'userID','is_accpeted','type','addedFrom'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'is_admin' => 'boolean',
];
public function isAdmin()
{
return $this->is_admin;
}
// change company to hasmany
public function user()
{
return $this->belongsTo('App\Models\User');
}
}
simply change your part of
dd($loginLogoutLog->users()->name);
into
dd($loginLogoutLog->users->name);
remove the bracket on users, its the easy fix.
here we obtain a property, not a function.... (although in the model its defined as function)
Easy fix:
$loginLogoutLogs = LoginLogoutLogs::all();
foreach($loginLogoutLogs as $loginLogoutLog){
dd($loginLogoutLog->users->name);
}
You want to access the relationship entities, as opposed to the relationship model.
By using users(), your code thinks you are trying to call a name() method on the users model, as opposed to your users method on the LoginLogoutLogs class.
You need to change your relationship with user adding the foreign key in LoginLogoutLogs:
public function user()
{
return $this->belongsTo('App\Models\User', 'userID');
}
Also ensure that you call user insted of users
$loginLogoutLogs = LoginLogoutLogs::all();
foreach($loginLogoutLogs as $loginLogoutLog){
dd($loginLogoutLog->user->name);
}
And if you want to perform use eager loading:
$loginLogoutLogs = LoginLogoutLogs::with('user')->get();
foreach($loginLogoutLogs as $loginLogoutLog){
dd($loginLogoutLog->user->name);
}
Remove () when you are getting the child model and add a second parameter to belongsTo.
Here you are:
Migrations:
// Parent migration (create_clients_table):
Schema::create('clients', function (Blueprint $table) {
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
});
// Child migration (create_payments_table):
Schema::create('payments', function (Blueprint $table) {
$table->unsignedBigInteger('client_id');
$table->foreign('client_id')
->references('id')
->on('clients')
->onDelete('cascade');
});
Models relationship:
// Child (Client Model)
public function owner()
{
return $this->belongsTo(User::class, 'user_id');
}
// Parent (User Model)
public function clients()
{
return $this->hasMany(Client::class);
}
Data output:
// Route:
Route::get('/client/{id}/payments', [PaymentController::class, 'paymentsOfClient']);
// In controller (PaymentController):
/**
* Display a listing of the payments of specified Client.
*
* #param string $id
* #return \Illuminate\Http\Response
*/
public function paymentsOfClient($id)
{
$client = Client::find($id);
// check permissions
if (auth()->user()->id !== $client->owner->id) {
return;
}
$payments = $client->payments()->paginate(20);
return response()->json($payments);
}