send some variable to the blade view laravel in an addColumn () function of datatable - laravel

Its possibility of sending a variable to the blade view through the addColumn() function of datatable jquery?
I want to pass another variable to compare values ​​of the result of the query.
this is the code:
if ($request->ajax()) {
$products = Product::with('categories', 'featureds')->orderBy('name', 'ASC');
$selecteds = [];
$products_selecteds = Product::all();
foreach($products_selecteds as $products_selected){
foreach($products_selected->featureds as $featured){
array_push($selecteds, $products_selected->id);
}
}
return Datatables::of($products)->addColumn('format_price', function($product) {
return $product->format_price;
})->addColumn('checkbox', function ($product, $selecteds) {
return view('pages.products.components.table.checkbox', ['product' => $product, 'selecteds' => $selecteds]);
});
}
the array $selecteds its i want to pass to the view checkbox:
<td>
<label>
<input type="checkbox" class="checkbox-item" {{ in_array($product->id, $selecteds) ? 'checked' : "" }} value=""/>
<span></span>
</label>
</td>

Yes, it's possible to render view on additional columns. But to achieve that, you have to make the column as a Raw Column like this:
Datatable::of($products)
->addColumn('selected', function($product) use($selecteds) {
return view('product.selected', compact('product', 'selecteds'));
})
->rawColumns(['selected'])
note:
you also need to declare use keyword since $selecteds is outside the closure

Related

Why does the old() method not work in Laravel Blade?

My environment is Laravel 6.0 with PHP 7.3. I want to show the old search value in the text field. However, the old() method is not working. After searching, the old value of the search disappeared. Why isn't the old value displayed? I researched that in most cases, you can use redirect()->withInput() but I don't want to use redirect(). I would prefer to use the view(). method
Controller
class ClientController extends Controller
{
public function index()
{
$clients = Client::orderBy('id', 'asc')->paginate(Client::PAGINATE_NUMBER);
return view('auth.client.index', compact('clients'));
}
public function search()
{
$clientID = $request->input('clientID');
$status = $request->input('status');
$nameKana = $request->input('nameKana');
$registerStartDate = $request->input('registerStartDate');
$registerEndDate = $request->input('registerEndDate');
$query = Client::query();
if (isset($clientID)) {
$query->where('id', $clientID);
}
if ($status != "default") {
$query->where('status', (int) $status);
}
if (isset($nameKana)) {
$query->where('nameKana', 'LIKE', '%'.$nameKana.'%');
}
if (isset($registerStartDate)) {
$query->whereDate('registerDate', '>=', $registerStartDate);
}
if (isset($registerEndDate)) {
$query->whereDate('registerDate', '<=', $registerEndDate);
}
$clients = $query->paginate(Client::PAGINATE_NUMBER);
return view('auth.client.index', compact('clients'));
}
}
Routes
Route::get('/', 'ClientController#index')->name('client.index');
Route::get('/search', 'ClientController#search')->name('client.search');
You just need to pass the variables back to the view:
In Controller:
public function search(Request $request){
$clientID = $request->input('clientID');
$status = $request->input('status');
$nameKana = $request->input('nameKana');
$registerStartDate = $request->input('registerStartDate');
$registerEndDate = $request->input('registerEndDate');
...
return view('auth.client.index', compact('clients', 'clientID', 'status', 'nameKana', 'registerStartDate', 'registerEndDate'));
}
Then, in your index, just do an isset() check on the variables:
In index.blade.php:
<input name="clientID" value="{{ isset($clientID) ? $clientID : '' }}"/>
<input name="status" value="{{ isset($status) ? $status : '' }}"/>
<input name="nameKana" value="{{ isset($nameKana) ? $nameKana : '' }}"/>
...
Since you're returning the same view in both functions, but only passing the variables on one of them, you need to use isset() to ensure the variables exist before trying to use them as the value() attribute on your inputs.
Also, make sure you have Request $request in your method, public function search(Request $request){ ... } (see above) so that $request->input() is accessible.
Change the way you load your view and pass in the array as argument.
// Example:
// Create a newarray with new and old data
$dataSet = array (
'clients' => $query->paginate(Client::PAGINATE_NUMBER),
// OLD DATA
'clientID' => $clientID,
'status' => $status,
'nameKana' => $nameKana,
'registerStartDate' => $registerStartDate,
'registerEndDate' => $registerEndDate
);
// sent dataset
return view('auth.client.index', $dataSet);
Then you can access them in your view as variables $registerStartDate but better to check if it exists first using the isset() method.
example <input type='text' value='#if(isset($registerStartDate)) {{registerStartDate}} #endif />

how do i pass data value to another page via link in laravel?

i am trying to make a list of locations that you can rent. but to rent the place you need to fill in some information. to fill in this information you excess another page. how do i make it so laravel knows the page belongs to a certain location
this is what ive done now but i keep getting the error:
Call to undefined method App\Reservation::location()
as soon as i have filled in the fields of information
this is the blade file that links to the the create reservation file
#foreach
($locations as $location => $data)
<tr>
<th>{{$data->id}}</th>
<th>{{$data->name}}</th>
<th>{{$data->type}}</th>
<th><a class="btn" href="{{route('Reservation.index', $data->id)}}">rent</a></th>
</tr>
#endforeach
this is the create reservations blade
<form action="{{ route('location.store') }}" method="post">
#csrf
<label>title</label>
<input type="text" class="form-control" name="name"/>
<label>type</label>
<select>
<option value="0">klein</option>
<option value="1">groot</option>
</select>
<button type="submit" class="btn">inschrijven</button>
</form>
this is what the location controller looks like
public function store(Request $request)
{
$location = new Reservation;
$location->name = $request->get('name');
$location->type = $request->get('type');
$location->location()->associate($request->location());
$location->save();
return redirect('/location');
}
and the relationships in my models should also work
class Reservation extends Model
{
public function locations()
{
return $this->belongsTo('Location::class');
}
}
class Location extends Model
{
public function reservations()
{
return $this->hasMany('Registration::class');
}
}
ive been stuck at this all day and i really dont know where to look anymore
The error you are getting is because of the wrong function name, you are calling location, while it is locations.
public function locations(){}
&
$location->location()->associate($request->location());
and you can pass the variable as a query parameter, you'll need to pass this data as an array in your blade file.
Web.php
Route::get('/somewhere/{id?}, function(){
//do something
})->name('test');
Blade
route('test', ['id' => $id]);
Controller Method
public function store(Request $request, $id) //Adding the query parameter for id passed in Route.
{
$location = new Reservation;
$location->name = $request->get('name');
$location->type = $request->get('type');
$location->location()->associate($id);
$location->save();
return redirect('/location');
}

Trying to get property 'id' of non-object laravel

can someone to help me ? i have an error Trying to get property 'id' of non-object laravel while try to show my edit form
this is my controller
public function edit($id)
{
$produk = produk::where('id',$id)->first();
return view('produk.edit',compact('produk'));
}
public function update(Request $request, $id)
{
produk::where('id',$id)
->update([
'nama' => $request->nama,
'id_kategori' => $request->kategori,
'qty' => $request->qty,
'harga_beli' => $request->beli,
'harga_jual' => $request->jual,
]);
return redirect()->route('produk.index');
}
this is my model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class produk extends Model
{
protected $guarded = ['id','created_at','updated_at'];
public function kategoris()
{
return $this->hasOne('App\kategori', 'id', 'id_kategori');
}
}
and this is my view
<select class="form-control" name="kategori">
<option value="Pilih Kategori"></option>
#foreach ($produk as $k)
<option value="{{ $k->id }}" #if($produk->id_kategori == $k->id) selected #endif>{{$k->nama}}</option>
#endforeach
</select>
Its because of this
$produk = produk::where('id',$id)->first();
this returns an object not an array of object. thats why your getting an error on your view. Instead use:
$produk = produk::where('id',$id)->get();
to return an array of object.
You are trying to foreach trough product properties, but looks like you need to foreach trough collection of categories.
Add categories to view in controller:
public function edit($id)
{
$produk = produk::find($id);
$kategoris = kategori::all();
return view('produk.edit',compact('produk', 'kategoris'));
}
Iterate trough $kategoris (not $produk) in View:
<select class="form-control" name="id_kategori">
<option value="Pilih Kategori"></option>
#foreach ($kategoris as $kategori)
<option value="{{ $kategori->id }}" #if($produk->id_kategori == $kategori->id) selected #endif>{{$kategori->nama}}</option>
#endforeach
</select>
Also, if foreign key is id_kategori, it is better to use name=id_kategori istead of name=kategori
You don't need relation here, because you compare categories ids with id_kategori attribute. But you should replace hasOne to belongsTo in this case.
public function kategoris()
{
return $this->belongsTo('App\kategori', 'id_kategori');
}
The correct way to obtain the value of the arrangement is
$k["id"] and not $k->id
I tried to obtain a field incorrectly with the array, I received the following array
[{"id": 1, "name": "Ivania", "code": 387}, {"id": 2, "name": "Robert", "code": 389}]
Check the array with a foreach
$users = $request->input('users');
foreach($users as $key => $user)
$person = new Person();
//incorrect form
//$person->id = $user->id
//the correct form
$person->id = $user["id"];
$person->name = $user["name"];
$person->code = $user["code"];
$person-> save ();
}

LARAVEL 5.5: Fetch unique values from database and pass to view as form select options

I'm looking to fetch unique values from a table in my database and pass the company name into my view as options in a drop down list within a form.
The function in my controller looks like this:
public function index()
{
$id = Auth::user()->id;
$admin = Admin::find($id);
$companies = DB::table('vacancies')->distinct()->select('company')->get()->toArray();
return view('admin')->with('admin',$admin)->with('companies',$companies);
}
And my view looks like this:
<div class="form-group">
#foreach ($companies as $company)
{{ Form::label('Select Company')}}
{{ Form::select('companies', $company->company, ['class'=>'form-control', 'placeholder'=>'Please select ...']) }}
#endforeach
</div>
I'm getting the following error:
Invalid argument supplied for foreach()
If I try {{dd($companies}} I can see an array is being passed through to the view OK. This array looks like this:
array:353[
0 => {#274 ▼
+"company": "Example company name"
}......
]
Ditching the loop and reverting back to:
<div class="form-group">
{{ Form::label('Select Company')}}
{{ Form::select('companies', $companies, ['class'=>'form-control', 'placeholder'=>'Please select ...']) }}
</div>
causes another error to be thrown which states:
htmlspecialchars() expects parameter 1 to be string, object given
Where am I going wrong here?
In your controller
public function index()
{
$id = Auth::user()->id;
$admin = Admin::find($id);
$companies = DB::table('vacancies')->distinct()->pluck('company')->toArray();
return view('admin')->with('admin',$admin)->with('companies',$companies);
}
Fllow as per below
your index function must be like below
public function index()
{
$id = Auth::user()->id;
$admin = Admin::find($id);
$companies = DB::table('vacancies')->distinct()->pluck('company')->toArray();
return view('admin')->with('admin',$admin)->with('companies',$companies);
}
your view must me like below
<div class="form-group">
{{ Form::label('Select Company')}}
{{ Form::select('companies', $companies, ['class'=>'form-control', 'placeholder'=>'Please select ...']) }}
</div>
let me know if any

Laravel Resource controller for filtering

I have a resource Controller for an API that I'm developing for displaying records that can be filtered by Type and Customer and I have the following methods that can get this data:
index
show -> requires an parameter (id)
Can I therefore put a request inside the index method for filtering all of the entries back or is it bad practise for doing this? My code looks like the following:
public function index()
{
$entries = \App\Ent::where(function($en) {
$request = app()->make('request');
if($request->has('type')) {
$en->where('type', '=', $request->get('type'));
}
if($request->has('customer')) {
$en->where('customer', '=', $request->get('customer'));
}
})->get();
dd($entries);
}
Filtering in Laravel is very simple and you don't need to do this. In your Ent model, define the following:
public function scopeFilter($query, $filters)
{
if( isset($filters['type']) ){
$query->where('type', '=', $filters['type']);
}
// keep going for all of your filters
}
And on your Controller index method you can:
public function index()
{
$entries = \App\Ent::filter(['type', 'customer'])->get();
dd($entries);
}
EDIT
To help you make more sense of this, let's filter Ent on the type column in the database.
Route:
Route::get('/ent', 'EntController#index');
Ent Model:
class Ent extends Model
{
public function scopeFilter($query, $filters)
{
if( isset($filters['type']) ){
$query->where('type', '=', $filters['type']);
}
}
}
Ent Controller:
class EntController extends Controller {
index()
{
$entries = \App\Ent::filter(['type'])->get();
return view('ent.index', compact('entries'));
}
}
Let's say for the sake of this example we are just going to put a form on the same blade template we are outputting our list:
#foreach( $entries as $entry )
<p>{{ $entry->type }}</p>
#endforeach
<form method="GET" action="/ent">
{{ csrf_field() }}
<input type="text" name="type" />
<input type="submit" value="Filter" />
</form>
So now, if I were to go into that form and type 'Foo Bar' and hit submit, you would get what would look something like this in SQL
SELECT * FROM Ent WHERE type='foo bar'
Or in other words, all Ent with the type column = 'foo bar'.
When I give a user the ability to type raw text in to filter, I like to give them the benefit of the doubt and use LIKE instead of =. So for example we would just change our scopeFilter method:
if( isset($filters['type']) ){
$query->where('type', 'LIKE', '%' . $filters['type'] . '%');
}
Another thing to note here, the filters[name] is the name of the <input> field, NOT the name of the column in your database. You target the column in the $query extension, NOT in the $filters array. See below example:
if( isset($filters["ent_type"] ){
$query->where('type', '=', $filters["ent_type"]);
}
On my form that would be
<input name="ent_type" type="text" />

Resources