I have my users table with a column named status. In this column I just store a number, based off their status, 1 - admin, 2 - owner, etc. I know that I can display these values with {{ users->status }}, but only shows the stored number. How can I show the actual name instead of the stored number?
Use Eloquent Accessors & Mutators.
Define an array of statuses and use the status number from your database as a key to change the value in the model so that in the view {{ $users->status }} equals admin
class User extends Eloquent {
protected $statuses = array(
'1' => 'admin',
'2' => 'owner'
);
public function getStatusAttribute($value)
{
return $this->statuses[$value];
}
}
getStatusAttribute converts 1 to admin when retrieving a record.
You could also have a set method for when records are stored in the model.
In View {{ $user->status }} // echos 'admin'
Related
I have two related tables and I want to return all fields including the ID (key) field. My query below returns all fields except the ID. how do I return the ID field from one of the tables?
'programmes' => ProgrammeInstances::with('programmes')->get(),
the query below returns Unknown column 'programmes.programme_title' as it is looking for it in the table 'programme_instances'
'programmes' => ProgrammeInstances::with('programmes')->select('programmes.programme_title', 'programmeInstances.id', 'programmeInstances.name', 'programmeInstances.year')->get(),
Laravel provides multiple relationships, one of these is the hasMany() relationship which should return a collection where a User hasMany rows inside of your database
For example, inside your User model :
public function programmes() {
return $this->hasMany(Program::class);
}
Now in your controller, you can do :
public function edit($id) {
$programmes = User::find($id)->with('programmes')->get();
return view('user.edit')->with('programmes', $programmes);
}
And then you can loop over it inside your view
#forelse($programmes->programmes as $program)
// provide the data
#empty
// the user doesn’t have any programmes
#endforelse
a solution i found below - still not sure why ID isnt automatically returned when i get all fields, but works when i specify individual fields:
'programmes' => ProgrammeInstances::with('programmes')
->get()
->transform(fn ($prog) => [
'programme_title' => $prog->programmes->programme_title,
'id' => $prog->id,
'name' => $prog->name,
'year' => $prog->year,
]),
this is my function in Invoice Controller
public function edit(invoice $invoice, $id)
{
$invoice = Invoice::with('users', 'items.products')->findOrFail($id);
return view(compact('invoice'));
}
in my View I did
{{ $invoice->user_id->email }}
The relationship you are loading is named users so that is the name of the dynamic property for that relationship. user_id is the User's id, not the relationship.
{{ $invoice->users->email }}
This is also assuming there is always a User for the invoice.
Laravel 6.x Docs - Eloquent - Relationships - Relationship Methods vs Dynamic Properties
Side Note:
The naming could use some work since there should only be one user for an invoice I would assume, so singular. Use plural when something can have many, singular when it has one or none. The relationship should be named user.
You are using the wrong property, $invoice->user_id is probably is the raw integer value coming from the database. You need to call the relation like so:
{{ $invoice->user->email }}
$invoice->user will return the user object that is related to the $invoice->user_id id.
you forgot view name to return
public function edit(invoice $invoice, $id)
{
$invoice = Invoice::with('users', 'items.products')->findOrFail($id);
return view('invoice.edit',compact('invoice'));
}
and access with relationship name
{{ $invoice->users->email }}
I have three columns in my table School:
id->int,
name->string,
status->int
I have been using the value from dropdown to fill in the value in status, the array is static and it is only used on view:
{!! Form::select('status', ['1' => 'Active', '2' => 'In Active'], '1', ['class' => 'form-control','placeholder' => 'Please Select Dean']); !!}
Now i wanted to list the value from School on table.
I have been using:
public function index()
{
$title = 'School Info';
$schoolList = School::all();
return view('school.index',compact('schoolList','title'));
}
Index View
<td></td>
<td>{!!$school->name!!}</td>
<td>{!!$school->status!!}</td>
This will return status=1 or 2 on view. However, in table i want to use status=Active or In Active, by querying with the static variable array.
There is no relation between school and status currently.
How can i query for Status and Display the actual status value on table but not the integer value?
Since you're getting (int) in the blade, you can do something like this in the blade
// In Blade.....
<td>{!! $school->status == "1" ? "Active" : "In Active" !!)</td>
You can use Accessors if you are saving the status value as 1 or 0 like integer:
In your case write the codes in School model,
public function getStatusAttribute($value)
{
if($value == 1){return 'Active';}
if($value == 0){return 'InActive';}
return $value; //if your status value is not 1 or 0 it will return the exact value of status
}
Now, If you use,
<td>{!!$school->status!!}</td>
in blade file it will display like Active or InActive
I am working on one to many relationship between tasks and Projects, i.e. a task can only belong to a single project, and I have used laravel's Accessor to get the selected project in my view in drop down:
my code is as follow:
public function getAssignUserAttribute($value)
{
dd($value); // gives me null
// if $value have id of user I want to get that user from db
}
and my view contains the drop down is:
{!! Form::select('assign_user', $assign_user, null, ['class' => 'form-control select2', 'id' => 'assign_user']) !!}
I have accessed all the users from database into TasksController to the view as:
$assign_user = User::pluck('title', 'id');
return view('tasks.edit', compact('task', 'assign_user'));
But I get all users selected, while I only want to have the selected user in my drop down.
Can someone guide me to the right path.
Thank you
finally I solved the issue by myself I have edit the Accessor as follow:
public function getAssignUserAttribute()
{
return [0 => $this->attributes['assign_user'] ];
}
Since I required an array so I assigned the current user to the array index 0 and return, in that case the view selected the returned user in drop down :)
This may help someone :)
I'm just starting to learn laravel and its orm system, Eloquent. I'm not sure how to correctly join tables with it though. I have 3 models: User, Account, AccountType and I don't know how to join Account with Accounttype.
Account Model Class:
public function accounttype(){
return $this->hasOne('AccountType');
}
This is to pass accounts information to view:
$accounts = User::find(Auth::user()->id)->accounts;
$accounts->load('accounttype');
return View::make('accounts.accounts')->with('accounts', $accounts);
That will give the following error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'accounttypes.account_id' in 'where clause' (SQL: select * from accounttypes where accounttypes.account_id in (1, 2, 3))
It should be pulling by id in the accounttypes table not account_id. I can list the user accounts just fine, I just don't know how to join the accounttypes table to the account table.
Database Tables:
Users
id
username
password
timestamps(updated_at / created_at)
Accounts
id
name
user_id
accounttype_id
timestamps
AccountTypes
id
name
Each user can have more than one account and each account will have an account type.
In User model:
public function accounts()
{
return $this->hasMany('Account');
}
In Account model:
public function user()
{
return $this->belongsTo('User');
}
public function accountType()
{
return $this->belongsTo('AccountType', 'accounttype_id', 'id');
}
In AccountType model:
public function accounts()
{
return $this->hasMany('Account', 'accounttype_id', 'id');
}
Then in your Controller:
// This will return a user with all accounts ($user->accounts will be collection)
$user = User::with('accounts')->find(Auth::user()->id);
Or:
$user = User::with('accounts.accountType')->find(Auth::user()->id);
// You may pass the $user as well and then loop the $user->accounts in view
return View::make('accounts.accounts')->with('accounts', $user->accounts);
In your view you may loop to get all accounts like:
#foreach($accounts as $account)
{{ $account->name }}
{{ $account->accountType->name }}
#endforeach
Since $user->accounts is a collection so you may either run a loop or specifically get an account using something like this:
{{ $accounts->first()->name }}; // Get first one's name
{{ $accounts->get(0)->name }}; // Get first one's name
{{ $accounts->get(1)->name }}; // Get second one's name
{{ $accounts->last()->name }}; // Get last one's name
if you pass the $user instead of $accounts like this:
return View::make('accounts.accounts')->with('user', $user);
Then change the loop as well, like this:
#foreach($user->accounts as $account)
{{ $account->name }}
{{ $account->accountType->name }}
#endforeach
You can make sure if that user has accounts in the view before you start the loop, like:
#if($user->accounts->count())
// Loop Here
#endif