I am going to view My users table data (username,email) in index.blade.php file. I have UsersController.php like this
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Auth;
use App\User;
use App\Http\Requests;
class UserController extends Controller
{
public function index()
{
$users = User::userr()->get();
return view('users.index')->withUser($users);
}
}
My User Model is
<?php
namespace App;
use Auth;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* 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',
];
public function getAvatarUrl()
{
return "http://www.gravatar.com/avatar/" . md5(strtolower(trim($this->email))) . "?d=mm&s=40";
}
public function scopeUserr($query)
{
return $query->where('username',Auth::user()->id);
}
}
and index.blade.php is
#if(isset($user))
#foreach($user as $use)
<h1>{ !! $use->username !! }</h1>
#endforeach
#endif
#endsection
routes is
Route::get('/index', function(){
return view('users.index');
});
but when I visit index view is it display empty page (no error) and did not show name and email
how can fix this prob?
Use User::all(); instead to get all datas from users table rather than User::userr()->get();
Also you have sent variable $users to your view and using $user in #foreach loop of blade.
Change #if(isset($user))
#foreach($user as $use)
to
#if(isset($user))
#foreach($user as $use)
on your blade file.Then it should work.
Check if your route has any action at the index (/). If not, set the route for the index to your desired view or controller. Then, from the controller, return the correct view along with the data you wish to send.
In the blade template, use the exact variable name you passed from the controller.
E.g. ,
Route::get('/', function(){
//variable here
return view('view')->with('var', $var);
});
In your blade,
#if(isset($var))
#foreach($var as $use)
//action here
#endforeach
#endif
Hope this helps.
Update your model and give a propper (meaningful) name to your scope
<?php
namespace App;
use Auth;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* 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',
];
public function getAvatarUrl()
{
return "http://www.gravatar.com/avatar/" . md5(strtolower(trim($this->email))) . "?d=mm&s=40";
}
public function scopeUsernameEmail($query)
{
return $query->select('username', 'email');
}
}
Your controller gonna look like something like this
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Auth;
use App\User;
use App\Http\Requests;
class UserController extends Controller
{
public function index()
{
return view('users.index', ['users' => User::query()->usernameEmail()->get()]);
}
}
Then update your routes to use the controller method
Route::get('/index', 'UserController#index')->name('users.index');
And finally in your blade file loop over users like this
<table>
<thead>
<tr>
<td>Username</td>
<td>Email</td>
</tr>
</thead>
<tbody>
#if(isset($users))
#foreach($users as $user)
<tr>
<td>{{ $user->username }}</td>
<td>{{ $user->email }}</td>
</tr>
#endforeach
#endif
<tbody>
<table>
Related
I have two tables 'teams' and 'users'. in users I have a foreign key("current_team_ID) for 'ID' field in 'teams' table.
Now I want to see in our view the name of a team of users.
This is my controller code:
public function index() {
$user = User::orderby('id', 'desc')->paginate(20);
$current_team_id = Teams::pluck('title', 'id');
return view('admin.users.index')->with(compact('user', 'current_team_id'));
}
And the index code :
#foreach ($user as $item )
<tr class="tableRows">
<td>{{ $item->id }}</td>
<td>{{ $item->name }}</td>
<td>{{ $item->email }}</td>
<td>{{ $item->stateID }}</td>
<td>{{ $item->current_team_id }}</td>
</tr>
#endforeach
It just shows the 'ID' of the team but I want to show the title of that. what should I do?
thanks
usersModel
<?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\Fortify\TwoFactorAuthenticatable;
use Laravel\Jetstream\HasProfilePhoto;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable {
use HasApiTokens;
use HasFactory;
use HasProfilePhoto;
use Notifiable;
use TwoFactorAuthenticatable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name',
'username',
'mobile',
'personalCode' ,
'email',
'password',
'stateID',
'lastLoginDateTime',
'token'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
'two_factor_recovery_codes',
'two_factor_secret',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* The accessors to append to the model's array form.
*
* #var array
*/
protected $appends = [
'profile_photo_url',
];
}
teamsModel
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Teams extends Model {
use HasFactory;
protected $table = 'teams';
public $primaryKey = 'id';
public $timestamps = false ;
}
if the user-team has relation defined you can do this in User model
public function team()
{
return $this->belongsTo(Team::class);
}
public function get_team_name()
{
if($this->team()->exists()) { // check if the user have a related team
return $this->team->title;
}
}
then in the blade loop you can
<td>{{ $item->get_team_name() }}</td>
First let's create the relatations
Add this to the User class
public function team(){
return $this->belongsTo(Team::class);
}
Add this to Teams class
public function users(){
return $this->hasMany(User::class);
}
And if you want to access a user
$users = Teams::find(1)->with('users')->get();
return view('admin.users.index')->with(compact('users');
And if you want to display a team with users
#foreach($users as $user)
<td>$user->team->title </td>
#endforeach
=>add on your users table.
$table->foreign('current_team_id')->references('id')->on('teams')->onDelete('cascade');
=>add relationship on Users Model
public function team()
{
return $this->hasOne(Teams::class, 'id', 'current_team_id');
}
=>you can access directly use team relationship in the user index file.
<td>{{$item->team->title}}</td>
App\Profile::jenis must return a relationship instance, but "null" was
returned. Was the "return" keyword used? (View:
C:\xampp\htdocs\user_manage\resources\views\profile\profile.blade.php)
(View:
C:\xampp\htdocs\user_manage\resources\views\profile\profile.blade.php)
Model Jenis.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Profile;
class Jenis extends Model
{
public $timestamps = false;
protected $table="tbl_jenis_penyedia";
protected $primaryKey="id_jenis_penyedia";
protected $fillable=['jenis_penyedia'];
public function profile(){
return $this->belongsTo(Profile::class);
}
}
Model Profile.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
public $timestamps = false;
protected $table="tbl_profil_penyedia";
protected $primaryKey="id_profil_penyedia";
protected $fillable=['id_jenis_penyedia','nama', 'no_ktp', 'file', 'npwp', 'bank', 'no_rek', 'email', 'no_telp', 'keahlian', 'pengalaman', 'alamat', 'pendidikan'];
public function jenis(){
$this->hasMany(Jenis::class, 'id_jenis_penyedia', 'id_profil_penyedia');
}
}
Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Profile;
use App\Jenis;
class ProfileController extends Controller
{
public function index()
{
$profile = Profile::all();
return view('profile/homeprofile',['profile' => $profile]);
}
}
view
#foreach($profile as $p)
<tr>
<td>{{ $no++ }}</td>
<td>
{{ $p->jenis->jenis_penyedia }}</td>
</tr>
#endforeach
please help me
You have forgotten to put return in jenis method.
Profile.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
public $timestamps = false;
protected $table="tbl_profil_penyedia";
protected $primaryKey="id_profil_penyedia";
protected $fillable=['id_jenis_penyedia','nama', 'no_ktp', 'file', 'npwp', 'bank', 'no_rek', 'email', 'no_telp', 'keahlian', 'pengalaman', 'alamat', 'pendidikan'];
public function jenis(){
return $this->hasMany(Jenis::class, 'id_jenis_penyedia', 'id_profil_penyedia'); // PUT A `return` HERE
}
}
Try this
public function profile(){
return $this->belongsTo(Profile::class,'id_jenis_penyedia', 'id_profil_penyedia');
}
So I have this relationship defined in the holiday model to access the holiday_type model.
MHoliday model:
use Arkitecht\Attributions\Traits\Attributions;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class MHoliday extends Model
{
use Attributions;
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $table = 'm_holiday';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'holiday_name',
'holiday_date',
'holiday_type_id',
'office_id',
'public_holiday_flag'
];
public function holidayType()
{
return $this->belongsTo('App\MHolidayType', 'holiday_type_id');
}
public function officeName()
{
return $this->belongsTo('App\MOffice', 'office_id');
}
}
MHolidayType model:
namespace App;
use Arkitecht\Attributions\Traits\Attributions;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class MHolidayType extends Model
{
use Attributions;
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $table = 'm_holiday_type';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'holiday_type_name'
];
}
MOffice model:
namespace App;
use Arkitecht\Attributions\Traits\Attributions;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class MOffice extends Model
{
use Attributions;
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $table = 'm_office';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'office_name',
'office_authority_id',
'note',
'first_name',
'employee_authority_id',
'note',
];
}
Then, I try show the result like:
<tr>
<td>{{ $item->officeName->office_name }}</td>
<td>{{ $item->holidayType->holiday_type_name}}</td>
</tr>
The Office name gives me result, but the holiday type throws me error "Trying to get property of non-object". What could be lacking?
Update
In my view, it is partly like this:
#foreach($holiday as $item)
<tr>
<td><input type="checkbox" class="items-selected" value="{{ $item->id }}"></td>
<td>{{ $item->id }}</td>
<td>{{ $item->holiday_name }}</td>
<td>{{ $item->holidayType->holiday_type_name }}</td>
<td>{{ $item->officeName->office_name }}</td>
<td>{{ $item->public_holiday_flag }}</td>
#endforeach
In the Holiday controller:
namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\MHoliday;
use App\MOffice;
use App\MHolidayType;
use Illuminate\Http\Request;
use Carbon\Carbon;
class HolidayController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\View\View
*/
public function index(Request $request)
{
$keyword = $request->get('holiday');
$getSearchby = $request->searchby;
$perPage = 25;
if ($keyword) {
$holiday = MHoliday::join('m_office', 'm_office.id', '=', 'm_holiday.office_id')
->where('m_office.office_name', 'like', '%'.$keyword.'%')
->paginate($perPage);
} else {
$holiday = MHoliday::paginate($perPage);
}
return view('holiday.index', compact('holiday','searchby','getSearchby'));
}
}
You should try to debug the result for your collection first because this exception mines that your table
m_holiday_type
have no records who match the relation.
do this in your controller before the return view :
dd($holidays);
and tell display me the result please.
I try to print on my view all the atleti associated with a squadra x but the method $squadra->atleti() always returns me ant empty array.
Have you got some ideas to get this working?
Down below you can find my code and my db structure.
Squadra is team in english. One team can be associated to many atleti (it stands for players).
I think there is some problems with the foreign key.
Thank you for your help.
<?php
//Squadra Model
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Squadra extends Model
{
protected $connection = 'custom_mysql';
protected $table = 'squadra';
/**
* Get the Allenatore for the Squadra.
*/
public function allenatore()
{
return $this->belongsTo('App\Models\Allenatore');
}
/**
* Get the Atleta for the Squadra.
*/
public function atleti()
{
return $this->hasMany('App\Models\Atleta');
}
}
<?php
//Atleta Model
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Atleta extends Model
{
protected $table = 'atleta';
protected $connection = 'custom_mysql';
/**
* Get the Atleta for the Squadra.
*/
public function squadra() {
return $this->belongsTo( 'App\Models\Squadra' );
}
}
<?php
//Controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
class AtletaController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function getSquadra($id)
{
$squadra = Squadra::find($id);
return view('custom.squadra.dettaglio', compact('squadra'));
}
//View
#foreach( $squadra->atleti() as $atleta )
<tr class="success">
<td>{{ $atleta->id }}</td>
<td>{{ $atleta->nome}}</td>
<td>{{ $atleta->cognome}}</td>
</tr>
#endforeach
Here it is the output of dd($squadra)
Your are sending the atleti to the view, instead of the squadra. Try to change your controller function to this:
public function index()
{
$squadra = Squadra::firstOrFail(); // You need a paremeter in a route that defines which squadra to show. This will show the first one.
return view('custom.atleta.index', compact('squadra'));
}
I need to display my users table data in the index.blade.php file, but when I visit the index view it displays an empty page, it does not display the variables data, which I need. (No errors are displayed.)
index.blade.php
#if(isset($users))
#foreach($users as $use)
<h1>{{$use->username}}</h1>
#endforeach
#endif
UsersController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Auth;
use App\User;
use App\Http\Requests;
class UserController extends Controller
{
public function index()
{
$users = User::userr()->get();
// $users = User::all();
return view('users.index')->withUser($users);
//dd($users);
}
}
User.php Model
<?php
namespace App;
use Auth;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* 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',
];
public function getAvatarUrl()
{
return "http://www.gravatar.com/avatar/" . md5(strtolower(trim($this->email))) . "?d=mm&s=40";
}
public function scopeUserr($query)
{
return $query->where('username',Auth::user()->id);
}
}
Can You give me some solutions?
May be you have to check if the data passed to your blade,
and try to use
$model = App\Flight::findOrFail(1);
return view('page',compact('var'));
check this
http://www.snippetcase.com/snippet/27/Bind+and+Display+data+in+blade+page+for+laravel