Laravel 5.2: Can variable be classified in view? - php

I am using Laravel 5.2.
My question is:
Can variable be classified in view?
For example:
There is a controller ,it can get all of the articles belonging to the current user, like this:
public function index()
{
$user=\Auth::user();
$articles = $user->articles;
return view('user.dashboard.index', compact('articles'));
}
In view,these codes below can show the articles,like this:
<div class="card">
<div class="card-header">
Articles
</div>
#if ($articles!=null)
<table class="table table-sm">
<thead>
<tr>
<th>title</th>
<th>created time</th>
<th>status</th>
</tr>
</thead>
<tbody>
#foreach ($articles as $article)
<tr>
<td>{{$article->title}}</td>
<td>{{$article->created_at}}</td>
<td>{{$article->status}}</td>
</tr>
#endforeach
</tbody>
</table>
#else
<p>Nothing</p>
#endif
</div>
These articles can be classified into two types:
1、“published”,status is 1.
2、“unpublished”,status is 0.
Question:
I would want the published articles to be shown in a card(div class="card"), and, the unpublished articles to be shown in another card.
Can they be classified in view? Thus,it doesn't need to query twice.

Try to use collection method where()
#foreach ($articles->where('published', 1)->all() as $article)
Just change published and 1 to real ones.

Related

display the authenticated user in laravel

Hello i'm trying to display the authenticated user but i'm getting this error :
Undefined variable: users (View:
C:\wamp64\www\Blan\resources\views\users\index.blade.php)
this is my code :
usercontroller :
public function index()
{
return view('users.index')->with('user', Auth::user());
}
the view :
#extends('layouts.app')
#section('content')
<div class="card">
<div class="card-header">
Update Your Profile
</div>
<div class="card-body">
<table class="table table-hover">
<thead>
<th>Image</th>
<th>Name</th>
<th>Update</th>
</thead>
<tbody>
#if( $users -> count() > 0 )
#foreach ($users as $user)
<tr>
<td>
#if(isset($user->profile->avatar))
<img src="{{ asset($user->profile->avatar)}}" width="60px" height="60px" style="border-radius: 50%" alt="">
#else
No image
#endif
</td>
<td>
{{$user->name}}
</td>
<td>
Update
</td>
</tr>
#endforeach
#else
<tr>
<th colspan="5" class="text-center">No Users </th>
</tr>
#endif
</tbody>
</table>
</div>
</div>
#stop
But if i return all the users using this code in the controller :
return view('users.index')->with('users', User::all());
its work fine.
so how i can return only the current authenticated user ?
You don't need to send the auth user via your controller.Auth is the global facade in laravel.Also you don't need foreach because there is only 1 authenticated user. Just type Auth::user()->name in the blade
where you want to display the user
Yea and btw the error ur getting is because you are doing foreach for $users but sending $user to blade but im pretty sure it wont work even if you correct that typo
In your example
public function index()
{
return view('users.index')->with('user', Auth::user());
}
You have used "user"
But tried to access variable as "users"
Unless you just made a typo in your example?

Laravel get All with Relationships and Paginate relationship data

I am trying to get all users and their associated (1:n) journals. However I want to add pagination to the associated journals, not the users
My Controller:
public function index()
{
$users = User::with(['journal'])->orderBy('name', 'asc')->get();
return view('journals/journals', ['users' => $users]);
}
My Blade:
#foreach($users as $user)
<a class="list-group-item list-group-item-action" data-toggle="collapse" href="#collapse{{$user->id}}" role="button" aria-expanded="false" aria-controls="collapse{{$user->id}}">
{{$user->name}}
</a>
<div class="collapse mt-1" id="collapse{{$user->id}}">
<div class="card card-body">
<div class="list-group">
<table class="table table-sm table-hover">
<thead>
<tr>
<th scope="col">Kunde</th>
<th scope="col">Betreff</th>
<th scope="col">Leistungsart</th>
<th scope="col">Beginn</th>
<th scope="col">Ende</th>
<th scope="col">Dauer</th>
<th scope="col">Arbeitszeit</th>
</tr>
</thead>
<tbody>
#foreach($user->journal as $journal)
<tr onclick="window.location='{{route('journal.show', [$journal->id])}}'">
<th scope="row">{{$journal->customer->name}}</th>
<td>{{$journal->title}}</td>
<td>{{$journal->type}}</td>
<td>{{$journal->started}}</td>
<td>{{$journal->ended}}</td>
<td>{{$journal->duration}}</td>
<td>{{$journal->worked}}</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
#endforeach
My Journal Model:
public function user(){
return $this->belongsTo('App\User', 'user_id', 'id');
}
My User Model:
public function journal(){
return $this->hasMany('App\Journal', 'user_id', 'id');
}
Again, what I am trying to achieve is that I can print out every user and paginate their journals, not paginate the users
I really hope someone can help me there
Render in blade
Above your journals for-each loop in your blade, try and put something like this:
#php
$paginated_journals = $user->journal()->paginate(10);
#endphp
And then, your for-each loop should look like this:
#foreach($paginated_journals as $journal)
...
#endforeach
After the for-each loop you can just put:
$paginated_journals->links()
to get the links for pagination
Pre-load data in controller
You can do the same thing server-side. Create a custom array that is empty, go through each user, and add sub array to that custom array:
array_push($custom_array, ['user' => $user, 'journals' => $user->journal()->paginate(10)])
This way you can send the custom array to your blade, loop through it, and render user data and paginated journals.

How to get data from database to view page in laravel?

I am using Laravel 5.4 and I want to view my data in database from my view page (listpetani.blade.php).
Here is the code of my project:
HTML:
<div class="table-responsive">
<table class="table table-striped table-hover table-condensed">
<thead>
<tr>
<th><strong>No</strong></th>
<th><strong>Nama Petani</strong></th>
<th><strong>Alamat</strong></th>
<th><strong>No. Handphone</strong></th>
<th><strong>Lokasi</strong></th>
</tr>
</thead>
<tbody>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</tbody>
</table>
</div>
PHP:
In my listpetani.blade.php I have an empty table and I want to show data from database tbl_user:
Route::get('listpetani', function () {
$petani = DB::table('tbl_user')->pluck('id_user', 'username', 'alamat', 'no_telp', 'id_lokasi');
return view('listpetani', ['petani' => $petani]);
});
And the table in my page: view in browser
I want to show all the data from database into my view in laravel 5.4. Can anybody help me?
[SOLVE]
Thank you guys, I already solve this problem
This is the solved code
web.php (routes)
Route::get('listpetani', function () {
$petani = DB::table('tbl_user')->get();
return view('listpetani', ['petani' => $petani]);
});
and in my listpetani.blade.php
#foreach($petani as $key => $data)
<tr>
<th>{{$data->id_user}}</th>
<th>{{$data->nama_user}}</th>
<th>{{$data->alamat}}</th>
<th>{{$data->no_telp}}</th>
<th>{{$data->id_lokasi}}</th>
</tr>
#endforeach
You can get data from database in view also
#php( $contacts = \App\Contact::all() )
#php( $owners = \App\User::all())
<select class="form-control" name="owner_name" id="owner_name">
#foreach($contacts as $contact)
<option value="{{ $contact->contact_owner_id }}">{{ $contact->contact_owner }}</option>
#endforeach
</select>
It would be better if you pass data from controller to view.
return view('greetings', ['name' => 'Victoria']);
Checkout the docs:
https://laravel.com/docs/8.x/views#passing-data-to-views
Alternatively you can use #forelse loop inside laravel blade
#forelse($name as $data)
<tr>
<th>{{ $data->id}}</th>
<th>{{ $data->name}}</th>
<th>{{ $data->age}}</th>
<th>{{ $data->address}}</th>
</tr>
#empty
<tr><td colspan="4">No record found</td></tr>
#endforelse
In your controller:
$select = DB::select('select * from student');
return view ('index')->with('name',$select);
In Your view:
#foreach($name as $data)
<tr>
<th>{{ $data->id}}</th> <br>
<th>{{ $data->name}}</th> <br>
<th>{{ $data->age}}</th> <br>
<th>{{ $data->address}}</th>
</tr>
#endforeach
I hope this can help you.
#foreach($petani as $p)
<tr>
<td>{{ $p['id_user'] }}</td>
<td>{{ $p['username'] }}</td>
<td>{{ $p['alamat'] }}</td>
<td>{{ $p['no_telp'] }}</td>
<td>{{ $p['id_lokasi'] }}</td>
</tr>
#endforeach
**In side controller you pass this **:
$petanidetail = DB::table('tb1_user')->get()->toArray();
return view('listpetani', compact('petanidetail'));
and Inside view you use petanidetail variable as follow:
foreach($petanidetail as $data)
{
echo $data;
}
I hope you already know this, but try use Model and Controller as well,
Let the route take the request, and pass it to controller
and use Eloquent so your code can be this short:
$petani = PetaniModel::all();
return view('listpetani', compact('petani));
and instead using foreach, use forelse with #empty statement incase your 'listpetani' is empty and give some information to the view like 'The List is Empty'.
Try this:
$petani = DB::table('tbl_user')->pluck('id_user', 'username', 'alamat', 'no_telp', 'id_lokasi');
return view('listpetani', ['petani' => $petani]);
on your view iterate $petani using foreach() like:
foreach($petani as $data)
{
echo $data->id_user; // $petani is a Std Class Object here
echo $data->username;
}
Other answers are correct, I just want to add one more thing, if your database field has html tags then system will print html tags like < p > for paragraph tag. To remove this issue you can use below solution:
You may need to apply html_entity_decode to your data.
This works fine for Laravel 4
{{html_entity_decode($post->body)}}
For Laravel 5 you may need to use this instead
{!!html_entity_decode($post->body)!!}

i want to display all the player of the respective club and have some issue in table in laravel

I have a clubs table having field:
id,name,est_date,CEO ....
i have players table having field:
id, name,DOB,height,weight, .....
player_histories table:
id,player_id,previous_club_id,current_club_id,position, ......
club_histories table:
club_id, championship_id,status, ...
In view page of club_histories, i can show:
club name,championship name and status...
but i want to show the respective player of club too in club_histories table... how is it posssible???
please reply...
Edited Portion: added code
Routes.php:
Route::resource('clubhistories','ClubHistoryController');
ClubHistoryController.php:
public function show($id,ClubHistory $clubhistories)
{
$club=$clubhistories->find($id);
$clubhistories=$clubhistories->getPlayerByCLub();
return view('pages.singleClub',compact('club','clubhistories'));
}
ClubHistoryRepository.php
public function getPlayerByCLub(){
return $this->makeModel() ->join('clubs', 'clubs.id', '=', 'club_histories.club_id')
->join('player_histories','player_histories.current_club_id', '=', 'clubs.id')
->join('players', 'players.id', '=', 'player_histories.player_id')
->get([
'clubs.name',
'player_histories.player_id',
'players.name',
]);
}
SingleClub.blade.php:
<div class="tab-content">
<div class="tab-pane in active" id="basic">
<table class="table table-condensed">
<thead>
<tr>
<th>Name</th>
<th>contact</th>
</tr>
</thead>
<tbody>
<tr>
<td>Name:</td>
<td>{!!$club->club->name!!}</td>
</tr>
<tr>
<td>Contact:</td>
<td>{!!$club->club->contact_no!!}</td>
</tr>
</tbody>
</table>
</div>
<div class="tab-pane fade" id="players">
<table class="table table-condensed">
<thead>
<tr>
<th>Player name</th>
<th>Position</th>
</tr>
</thead>
<tbody>
#foreach($clubhistories as $clubhistories)
<tr>
<td> {!! $clubhistories->name!!} </td>
<td> {!! $clubhistories->position!!} </td>
</tr>
#endforeach
</tbody>
</table>
</div>
above join used and solution you have given give a same solution..i want to pass the same id find by clubhistories in club object to clubhistories object so that all the player of club will be shown ..
can you please help me..
You can see the players in club_histories either through joins (less queries) or Eloquent relationships (simpler looking code).
Using Eloquent Relationships (assuming you've set them up):
$histories = ClubHistory::with('players', 'club')->get();
// In your blade view
#foreach ($histories as $history)
<p>{{ $history->club->name }} won {{ $history->championship_name }}</p>
<p>Status: {{ $history->status }}
<div>Player list:
<ul>
foreach ($history->players as $player)
<li>{{ $player->name }}</li>
#endforeach
</ul>
</div>
#endforeach
Joins with the query builder:
DB::table('club_histories')
->join('player_histories',
'player_histories.current_club_id', '=', 'club_histories.club_id')
->join('players', 'players.id', '=', 'player_histories.player_id')
->join('club', 'club.id', '=', 'club_histories.club_id')
->get([
'club.name AS clubName',
'club_histories.championship_name',
'club_histories.status',
'player_histories.player_id',
'players.name AS playerName',
]);
Note that the above will return one row per player per club_history
EDIT:
After seeing your code, here's a version of the above that should work with your non-standard codebase. Be sure to pass the ID to getPlayerByClub($id).
ClubHistoryRepository.php
public function getPlayerByCLub($clubHistoryId) {
return $this->makeModel()
->join('clubs', 'clubs.id', '=', 'club_histories.club_id')
->join('player_histories', 'player_histories.current_club_id', '=', 'clubs.id')
->join('players', 'players.id', '=', 'player_histories.player_id')
->where('club_histories.id', '=', $clubHistoryId)
->get([
'clubs.id',
'club_histories.championship_name',
'club_histories.status',
'player_histories.player_id',
'clubs.name',
'players.name',
]);
}

Server side pagination of laravel 5

I am having some trouble implementing server side pagination in Laravel 5.
Do you have any idea please tell
try with this one
//in controller
$users = \App\User::paginate(15)
return view('your desired view file name', compact('users'));
// in view
<div class="text-center text-muted" role="status" aria-live="polite">Showing {{$users->firstItem()}} to {{$users->lastItem()}} of {{$users->total()}} entries</div>
<div style="display:flex;justify-content:center;align-items:center;" >
<p></p>
{!! with(new Illuminate\Pagination\BootstrapThreePresenter($users))->render()!!}
</div>
In controller you do somrthing like following
$users = \App\User::paginate(15)
return view('template.file', compact('users'));
and in View file you put following
<table>
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody>
#foreach ($users as $user)
<tr>
<td> {{ $user->name }} </td>
</tr>
#endforeach
</tbody>
</table>
{!! $users->appends(\Input::except('page'))->render() !!}
Last line renders pagination links.

Categories