I'm currently learning Laravel 5.6. So my problem is this, I have the following Model:
class Tour extends Model
{
//
protected $fillable = [
'name',
'price',
'category',
'overview',
'activity',
'exclusion',
'inclusion',
'policies',
'guide_id',
'province_id'
];
public function tourImages(){
return $this -> hasMany('App\TourImage');
}
}
class TourImage extends Model
{
//
protected $fillable = [
'name',
'path',
'tour_id'
];
public function tour(){
return $this -> belongsTo('App\Tour');
}
}
So 1 Tour can have multiple TourImages. What i want to do is that i want to print out all the tours on the index page. But i only want to take one TourImage file to display for each tour. I return only array of all tours from controller. Is there a way that i can retrieve image directly on the blade view without returning more variable from the controller?
Here's what I write for my index method:
public function index($province_id = null)
{
$tours = Tour::where('province_id', $province_id)->get();
return view('tours.index', ['tours' => $tours]);
}
Here's my index view:
#extends('layouts.app')
#section('content')
<div class="col-md-8 offset-md-2">
<br/>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Picture</th>
<th scope="col">Price</th>
</tr>
</thead>
<tbody>
#foreach($tours as $tour)
<tr>
<th scope="row">{{ $tour->id }}</th>
<td>{{ $tour->name }}</td>
<td><img src="/storage/{{ $tour->tourImages->path }}" width="200px"/></td>
<td>{{ $tour->price }}</td>
</tr>
#endforeach
</tbody>
</table>
</div>
#endsection
you can pass one image of each tour by this code :
$tours=Tour::with(['tourImages'=>function($query){
$query->first();
}])->get();
and in view:
#foreach($tours as $tour)
#if ($tour->tourImages->count())
<img src="/storage/{{ $tour->tourImages[0]->path }}" width="200px"/>
#endif
#endforeach
you need to use with() to get records.like this.
$tours = Tour::with('tourImages')->where('province_id', $province_id)->get();
You can add new relation in your Tour model like
public function latestTourImage() {
return $this->hasOne('App\TourImage')->latest();
}
Then you can fetch it using this in your controller file
$tours = Tour::with('latestTourImage')->where('province_id', $province_id)->get();
and then you can print it in your blade file like
$tour->latestTourImage->path
Related
im using Laravel 6.2
I want to make a inventory database system. i have 2 modals Produk and Stock.
in that case, i want to input data p_name and sku from ProdukTable and place it into StockTable using Eloquent ORM.
I tried using belongsTo(),
Here's my modal Produk code
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Produk extends Model
{
public $table = 'produk';
protected $primaryKey = 'pid';
protected $fillable = [
'pid',
'p_nama',
'sku',
'p_harga',
'status'
];
}
Here's my modal Stock code
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Stock extends Model
{
public $table = 'stock';
protected $primaryKey = 'sid';
protected $fillable = [
'sid',
'p_nama',
'sku',
'p_stock_min',
'p_stock',
'status'
];
public function produk()
{
return $this->belongsTo('App\Produk', 'pid');
}
}
My StockController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Stock;
use App\Produk;
use RealRashid\SweetAlert\Facades\Alert;
class StockController extends Controller
{
public function index()
{
$datas = Stock::paginate(5); // 5 record per pages
return view('stock.list', compact('datas'));
// $datas = Stock::all();
// return $datas;
}
. . . .
}
My View stock.blade
<div class="body">
<div>
<i class="zmdi zmdi-account-add"></i> Tambah Stock
<a style="margin: 2px;" href="{{ route('stock.index')}}" class="btn btn-primary btn-sm"><i class="zmdi zmdi-refresh"></i></a>
</div>
<div class="col-sm-12">
#if(session()->get('success'))
<div class="alert alert-success">
{{ session()->get('success') }}
</div>
#endif
</div>
<table class="table table-bordered table-striped table-hover dataTable js-exportable">
<thead>
<tr>
<th class="text-center" style="width:5%">#</th>
<th class="text-center" style="width:25%">Nama Produk</th>
<th class="text-center" style="width:10%">SKU Produk</th>
<th class="text-center" style="width:8%">Min. Stock</th>
<th class="text-center" style="width:8%">Stock</th>
<th class="text-center" style="width:10%">Status</th>
<th class="text-center" style="width:10%">Aksi</th>
</tr>
</thead>
<tbody>
#if(!empty($datas) && $datas->count())
#foreach($datas as $data)
<tr>
<th class="text-center">{{ $loop->iteration }}</th>
<td>{{ $data->produk }}</td>
<td>{{ $data->p_nama }}</td>
<td>{{ $data->p_stock_min }}<code> pcs</code></td>
<td>{{ $data->p_stock }}<code> pcs</code></td>
<td class="text-center">{{ $data->status }}</td>
<td class="text-center">
<i class="zmdi zmdi-edit"></i></span>
<i class="zmdi zmdi-delete"></i></span>
</td>
</tr>
#endforeach
#else
<tr>
<td colspan="8">Data tidak ditemukan! Silahkan buat data Stock terlebih dahulu.</td>
</tr>
#endif
</tbody>
</table>
{!! $datas->links() !!}
</div>
Migration Stock
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateStocksTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('stock', function (Blueprint $table) {
$table->bigIncrements('sid');
$table->bigInteger('produk_id')->unsigned();
$table->string('p_nama');
$table->string('sku');
$table->integer('p_stock_min');
$table->integer('p_stock')->nullable();
$table->string('status');
$table->timestamps();
});
Schema::table('stock', function (Blueprint $table) {
$table->foreign('produk_id')->references('pid')->on('produk')
->onDelete('cascade')->onUpdate('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('stock');
}
}
Response when i add data direct from PMA
[{"sid":1,"produk_id":6,"p_nama":"kopi1","sku":"12345678","p_stock_min":20,"p_stock":800,"status":"Aktif","created_at":"2020-11-24 16:37:16","updated_at":"2020-11-24 16:37:16"},
{"sid":2,"produk_id":7,"p_nama":"kopi2","sku":"87654321","p_stock_min":20,"p_stock":600,"status":"Aktif","created_at":"2020-11-24 16:37:16","updated_at":"2020-11-24 16:37:16"}]
i dunno where's my mistake ?
just want to add data p_produk into stock table using select form, and when i select it sku data will be generate as same as data on table Produk.
In your Stock model you should put the foreign key in the belongsTo relation. Edit the method like so:
public function produk()
{
return $this->belongsTo('App\Produk', 'produk_id');
}
Using Laravel conventions the relationship produk should be defined as
public function produk()
{
return $this->belongsTo(Produk::class, 'produk_id', 'pid');
}
To dynamically change the value of sky in the readonly input on create.blade.php based on the option selected by the user in select control showing $produk->p_nama:
Give an id to the readonly input for sku
<div class="form-group">
<label for="sku">SKU:</label>
<input type="text" class="form-control form-control-lg" name="sku" id="skuSelected" readonly/>
</div>
Track the option selected in select control
<select class="form-control select2" name="p_name" onChange="setSku(this);">
#foreach($produks as $produk)
<option value="{{ $produk->pid }}">{{ $produk->p_nama }}</option>
#endforeach
</select>
Handle the change in selection via javascript
<script>
function setSku(sel) {
const sku = sel.options[sel.selectedIndex].text;
document.getElementById('skuSelected').value = sku;
}
</script>
because you are not naming your columns on the laravel naming conventions
you have to define it all by yourself if you want to use this naming like this :
public function produk()
{
return $this->belongsTo('App\Produk', 'pid' , 'id');
}
as belongsTo takes $relatedModel , $foreignKey , $ownerKey in a row
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.
So I have a table on blade view file, I have successfully exported it into the excel file. Now I want to export without exporting the 'Actions" column. How can I do that?
I have attached my code and blade file below, it works perfectly. I just want to export everything except the Actions Column as it contains Buttons for Database Operations
THIS IS MY EXPORT CLASS CODE:
public function view(): View
{
return view ('ims.view_inventory_history_table', [
'data' => inbound_history::all()
]);
}
public function headings(): array
{
return [
'ID',
'Warehouse',
'SKU',
'Child SKU',
'Units',
'Invoice No.',
'Container No.',
'Entry Date'
];}
/**
* #return array
*/
public function registerEvents(): array
{
return [
AfterSheet::class => function(AfterSheet $event) {
$cellRange = 'A1:W1'; // All headers
$event->sheet->getDelegate()->getStyle($cellRange)->getFont()->setSize(14);
},
];
}}
THIS IS MY CONTROLLER FUNCTION:
public function export_view()
{
return Excel::download(new inboundHistory(), 'inboundHistory.xlsx');
}
THIS IS MY ROUTE:
Route::Get('inbound_history/export_view' ,'imsController#export_view')->name('inbound_history.export_view');
THIS IS MY BLADE TABLE VIEW:
<table id="datatables" class="table table-striped table-no-bordered table-hover" cellspacing="0" width="100%" style="width:100%">
<thead>
<tr>
<th style="width:5%">ID</th>
<th>Warehouse</th>
<th>SKU</th>
<th>Child SKU</th>
<th>Cases</th>
<th>Units</th>
<th>Invoice No.</th>
<th>Container No.</th>
<th>Entry Date</th>
<th class="disabled-sorting text-right" style="width:12%">Actions</th>
</tr>
</thead>
<tbody>
#foreach ($data as $row)
<tr>
<td>{{$row['id']}}</td>
<td>{{$row['warehouse']}}</td>
<td>{{$row['sku_parent']}}</td>
<td>{{$row['sku_child']}}</td>
<td>{{$row['total_cases']}}</td>
<td>{{$row['total_units']}}</td>
<td>{{$row['invoice_no']}}</td>
<td>{{$row['container_no']}}</td>
<td>{{$row['date_rec']}}</td>
<td class="td-actions text-right">
{{-- <a rel="tooltip" class="btn btn-success btn-link" href="{{action('imsController#edit',$row['id'])}}">
<i class="material-icons">edit</i></a> --}}
<a rel="tooltip" class="btn btn-danger btn-link" href="{{action('imsController#destroy',$row['id'])}}" onclick = "if (! confirm('Confirm: Press OK to delete the Entry.')) { return false; }"style="color: red;">
<i class="material-icons">close</i></a>
</td>
</tr>
#endforeach
</tbody>
I don't know if I got everything correctly, but why don't you do something like this:
Pass an additional variable to your blade template like $isView, when you want to create a view for the user.
And in your blade.php template you do something like this:
#isset($isView)
<th class="disabled-sorting text-right" style="width:12%">Actions</th>
#endisset
// do the same #isset test for the corresponding <td> element
When you want to render it to excel you just don't pass this variable and the column is not rendered.
I'm trying to set pagination in a Laravel blade/view but it's showing an error with this message below:
BadMethodCallException
Method Illuminate\Database\Eloquent\Collection::paginate does not exist.
Controller
public function view()
{
$user = Auth::user();
$basic_info = User::find($user->id)->basic_info;
$category = Category::all()->paginate(10);
return view('admin.article.category-view')->with(['user' => $user, 'basic_info' => $basic_info, 'category' => $category]);
}
View Blade (admin.article.category-view)
<div class="panel-body">
<table class="table table-hover">
<thead>
<tr>
<th>Category Name</th>
</tr>
</thead>
<tbody>
#foreach($category as $cat)
<tr>
<td>{{ $cat->name }}</td>
</tr>
#endforeach
</tbody>
</table>
{{ $category->links() }}
</div>
Using paginate method on the query builder or an Eloquent query only, not on collection, like so:
public function view()
{
$user = Auth::user();
$basic_info = User::find($user->id)->basic_info;
$category = Category::paginate(10);
return view('admin.article.category-view')->with(['user' => $user, 'basic_info' => $basic_info, 'category' => $category]);
}
You need to remove all():
$category = Category::paginate(10);
When you're using all() you get all the rows from the table and get a collection
You can only invoke "paginate" on a Query, not on a Collection.
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)!!}