Laravel getting information from other table - laravel

I have the following tables user table, post table and profile table. the post belongs to a user and the profile belongs to a user. I also have a forum were people can post I want the users username to show instead of their name. But The username is in the profiles table and I don't know how to get it.
here is my code
class Post extends Model
{
//
public function users(){
return $this->belongsToMany('App\User','posted_by');
}
class Profile extends Model
{
//
public function users(){
return $this->belongsTo('App\User','whos_profile');
}
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'firstname','lastname', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function profile(){
return $this->hasOne('App\Profile');
}
public function post(){
return $this->hasMany('App\Post');
}
}`enter code here`

You can get it as follows
$user = User::find($id);
if($user->profile){
echo $user->profile->username;
}

You should try this:
$rsltUsers = User::with(['profile','post'])->where('id',$id)->get();
foreach($rsltUsers as $rsltUsers){
dd($user->profile->username);
}

Related

Attempt to read property "name" on null (View: C:\xampp\htdocs\Moja_OTT\resources\views\premium\profile.blade.php)

I want a simple program that shows the user profile after login. I used session and middleware. But it is saying that the name property is null. Please help me solve this error. I have used User model. The value of the properties are not retrieving from the database.
Blade code:
<h1>Profile</h1>
<h2>Welcome Mr/Ms {{$user->name}}</h2>
Logout
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 App\Models\PremiumModel;
class User extends Authenticatable implements MustVerifyEmail
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $table = 'users';
protected $primaryKey = 'user_id';
protected $timestamp = false;
protected $fillable = [
'name',
'email',
'password',
'type',
'email_verified_at',
'pro_pic',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
function admin()
{
return $this->hasOne('App\Models\admin', 'user_id', 'admin_id');
}
function premium()
{
return $this->hasMany(PremiumModel::class, 'user_id', 'user_id');
}
}
Controller code:
function profile()
{
$user = User::where('user_id',session()->get('logged'))->first();
return view('premium.profile')->with('user',$user);
}
Here, logged is the middleware.
You can try hasOne in the User model:
public function premium()
{
return $this->hasOne(PremiumModel::class, 'user_id', 'user_id');
}
Because hasMany returned an array, but hasOne returned just a single Object

eloquent one-To-Many-To-Many

Hi everyone I start with Laravel and eloquent and already I have a problem.
I have users, each user can have multiple vehicles and a vehicle can have multiple rentals. I want to list all rentals of each vehicle belonging to the current user.
User model:
class User extends Authenticatable
{
use Notifiable;
/**
* 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 vehicule()
{
return $this->hasMany('App\Models\Vehicule');
}
Vehicule model:
use Illuminate\Database\Eloquent\Model;
class Vehicule extends Model
{
protected $fillable = [
'user_id',
'published',
'rented'
];
public function user()
{
return $this->belongsTo('App\User');
}
public function rental()
{
return $this->hasMany('App\Models\Rental');
}
Rental model:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Rental extends Model
{
protected $fillable = [
'from_date',
'to_date',
'amount_total',
'vehicule_id'
];
public function vehicule()
{
return $this->belongsTo('App\Models\Vehicule');
}
}
You can use your existing relationships:
$rentals = $user->load('vehicule.rental')->pluck('vehicule.rental')->collapse();
Or add a HasManyThrough relationship to User:
public function rental()
{
return $this->hasManyThrough(Rental::class, Vehicule::class);
}
$rentals = $user->rental;

Laravel Relationship Issues : Laravel 5.4

I have 2 tables in my application... Users Conventioners
I have users id in the conventioners table and i want to access their genders from the Users table....
I have like 10 user ids in the conventioners table and 20 users in the users table...
Please how do I access all their genders in the users table...
$conventioners->users()->gender
Conventioners is an instance of the Conventioner Model which contains a relationship **belongsToMany
Thanks alot guys
Here is my Conventioner Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Conventioner extends Model
{
/**
* #var string
*/
protected $table = 'conventioners';
/**
* #var array
*/
protected $fillable = [
'user_id','year','church_id','convention_id'
];
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function user()
{
return $this->belongsTo('App\User');
}
/**
* #return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function users()
{
return $this->hasMany('App\User');
}
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function convention()
{
return $this->belongsTo('App\Convention');
}
}
Here is my ConventionController method called Convention...
It retrieves the details for the current convention
public function convention($slug)
{
if(!$this->admin()) return redirect()->back();
$convention = Convention::where('slug', $slug)->first();
$participants = Conventioner::where('convention_id', $convention->id)->get();
$conventioner = [];
foreach($participants as $participant)
{
$thisUser = [];
$thisUser['data'] = User::withTrashed()->where('id', $participant->user_id)->first();
$thisUser['convention'] = $participant;
array_push($conventioner, $thisUser);
}
var_dump($participants->users()->pluck('gender')->all());
return view('dashboard/conventions/convention', [
'convention' => $convention,
'user' => Auth::user(),
'conventioners' => $convention->conventioners(),
'participants' => $conventioner
]);
}
The problem is that users is a collection not an individual that you can call gender on. If you want a list of all the genders you can use the following:
Conventioner::where('convention_id', $convention->id)->with('users')->get()
$conventioners->pluck('users')->pluck('gender')->all();
This will return an array of the genders. You can read more about pluck here.
The pluck method retrieves all of the values for a given key

Implemented a sidebar based on user with most posts and comments

i want to implement a sidebar based on user with most posts and comments in laravel 5.2 app,
i want to show the top 5 users with most posts and comment.
Exemple Like this:
User Name: "Mohcin", Post:30, answer:20
Thanks in advance
User model:
use Authenticatable, CanResetPassword;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['name', 'email', 'password'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token'];
public function questions(){
return $this->hasMany('\App\Question');
}
public function answers(){
return $this->hasMany('\App\Answer');
}
Question model: (posts model)
public function User(){
return $this->belongsTo('\App\User');
}
public function answers(){
return $this->hasMany('\App\Answer');
}
public static function your_questions(){
return static::where ('user_id','=',Auth::user()->id)->paginate(50);
}
public static function unsolved(){
return static::where ('solved','=',0)->orderby('id','DESC')->latest()->paginate(50);
}
public static function unsolvedbar(){
return static::where ('solved','=',0)->orderby('id','DESC')->latest()->take(3)->get();;
}
public function category()
{
return $this->belongsTo('App\Category');
}
public function tags()
{
return $this->belongsToMany('App\Tag');
}
Steps:
Open app/Providers/AppServiceProvider.php
In this file you have an empty (probably) boot method.
Inside this method, you can create a view composer to pass data for a specific view.
Like this:
//Assuming you want to pass the var to the view: sidebar.blade.php inside resources/views/layout
view()->composer('layout.sidebar', function($view){
$topUsers = User::topUsers(); //Create a query or scope to do this...
//After populate topUsers, you have to pass it to the view using:
$view->with('topUsers', $topUsers);
});
In your view: `resources/views/layout/sidebar.blade.php, you can access the users with a simple $topUsers like this:
foreach($topUsers as $user) {
var_dump($user);
}

Laravel Eloquent Create

Hello so I've started using Laravel and it is useful and easy. For now I have a CRUD in which is working. In my AccountController#store the code is:
public function store(Request $request)
{
$input = $request->all();
Accounts::create($un);
Session::flash('flash_message', 'Account successfully added!');
return redirect()->route('accounts.index');
}
This basically adds a new account in my table. My problem is, I have a password textbox and I can't hash it since this code automatically gets every input in the form. How can I get it one by one? Like username, email and password only so I can hash the password.
You could get the input one by one and then hash the password and save it to the database. But that would require extra code.
You could also add an extra function to your Account model that will take care of this automatically.
Take a look at the example I use to create my management users.
<?php namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Hash;
class Management extends Model implements AuthenticatableContract {
use Authenticatable;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'Management';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['name', 'email', 'password'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token'];
/**
* Automatic hash function for the password.
*
* #var array
*/
public function setPasswordAttribute($value)
{
$this->attributes['password'] = Hash::make($value);
}
}
Regarding your code, you could do this:
public function store(Request $request)
{
Accounts::create($request->all());
Session::flash('flash_message', 'Account successfully added!');
return redirect()->route('accounts.index');
}
Make sure to modify the example model above to your own needs!
You can also do:
public function store(Request $request)
{
$input = $request->all();
Accounts::create([
'username' => $input['username'],
'password' => bcrypt($input['password']),
]);
Session::flash('flash_message', 'Account successfully added!');
return redirect()->route('accounts.index');
}
You call Input::all() to get all the attributes passed in, and Input:get('key') to get a specific key.
So you should call:
$account = new Accounts;
$account->username = Input::get('username');
$account->password = Hash::make(Input::get('password'));
//key with a default
$account->password = Input::get('age', 20);
//optional field
if (Input::has('optional')) {
$account->optional = Input::get('optional');
}
//any other fields that account needs
$account->save()

Resources