Laravel 5.2 - Getting a pivot table additional attribute - php

I'm using Laravel to track Gear in Wearhouses. For that I have 2 tables: gears and wearhouses, and another pivot table: gear_wearhouse.
The relationship between the two tables is a many-to-many relationship, and in my pivot table, in addition to the gear_id and wearhouse_id columns, I have a qty (quantity) column.
Now I loaded all the wearhouses that store a certain gear item ($whs = $gear->wearhouses), and I want to get the quantity (qty field) from the pivot table.
Here is my code:
#foreach ($gear->wearhouses as $wh)
<tr>
<td>
{{ $wh->title }}
</td>
<td>
{{ $wh->manager->name }}
</td>
<td>
{{ $wh->pivot->qty }}
</td>
<td>
<a href="{{ url('/admin/organization/gear/edit/' . $wh->id) }}" class="btn btn-warning btn-xs">
<i class="fa fa-pencil-square-o"></i> עריכה
</a>
<a data-toggle="modal" href="#delete-{{ $wh->id }}" class="btn btn-danger btn-xs">
<i class="fa fa-trash-o"></i> מחיקה
</a>
</td>
</tr>
#endforeach
$wh->pivot->qty returns nothing.
How can I do that the easiest way?

$warehouse = Warehouse::find(1);
$gears = $warehouse->gears;
foreach($gears as $gear)
{
$qty = $gear->pivot->qty;
}
or
$warehouse = Warehouse::find(1);
$gear = $warehouse->gears()->first();
$qty = $gear->pivot->qty;

Related

Laravel orderBy working while doing dd but not in table while fetching

Into my laravel application while I am fetching data by eager loading order by showing me the correct format of data in dd i.e. the data in DESC format, but while i am compacting data and trying to show it in blade it shows the data in ASC format...
My controller
public function index(Request $request)
{
$data = Rate::with('hospital')->orderBy('id','DESC')->get();
// dd($data );
return view('admin.rates.index',compact('data'));
}
My blade file
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
{{-- <th>No</th> --}}
<th>Hospital</th>
<th>Contract Date</th>
<th class="text-center">Contract Length (weeks)</th>
<th>Weekly</th>
<th>Hourly</th>
<th>Others</th>
{{-- <th>Status</th> --}}
<th>Action</th>
</tr>
</thead>
<tbody>
<?php $i=0; ?>
#foreach ($data as $key => $rate)
<tr>
{{-- <td>{{++$i}}</td> --}}
<td>
{{ ucwords($rate->hospital->short_name) }}
</td>
<td>
{{date('m/d/Y',strtotime($rate->contract_date))}}
</td>
<td class="text-center">
{{ $rate->contract_duration}}
</td>
<td class="text-right">
{{ ($rate->weekly_rate != '') ? $rate->weekly_rate : '' }}
</td>
<td class="text-right">
{{ ($rate->hourly_rate != '') ? $rate->hourly_rate : '' }}
</td>
<td class="text-right">
{{ ($rate->others_rate != '') ? $rate->others_rate : '' }}
</td>
{{-- <td>
</td> --}}
<td>
#if ($rate->status=='inactive')
<i class="fas fa-times"></i>
#else
<i class="fas fa-check"></i>
#endif
<a class="btn btn-sm btn-info" href="{{ route('rate.edit',$rate->id) }}"><i class="fas fa-edit"></i></a>
<a class="btn btn-sm btn-danger" onclick="return confirm('Are you sure you want to delete')" href="{{ route('rate.destroy',$rate->id) }}"><i class="fas fa-trash"></i></a>
</td>
</tr>
#endforeach
</tbody>
</table>
There is nothing much more in it but why the data are not showing in DESC format is my question??? I am also pasting my dd image below where you can see the first data has the id 8 and the second one id 7 which is totally correct but while fetching id 7 comes first why??
When you are using datatable it tries to filter or sort the data in nearest alphabetical order if serial number is not in use I saw that you have closed tag for serial no try to open it and check the result. I am quite sure it is due to that... Just try to use "ordering": false into your datatable function..

Make bootstrap modal create an object to be added to list

In my Laravel project, I have the following models:
Product ('name' string, 'amount' integer and 'price' decimal)
Cart ('cost' decimal)
CartProd ('unit_price' decimal, 'amount' integer, 'discount' decimal, 'total_cost' decimal and foreign keys to a product and a cart)
The idea is that, when you want to create a new cart, the CartController method creates a list of all the products, a brand new cart and an empty list in which the selected products for the cart will be added, and sends them all through the view's compact.
public function create(Request $request)
{
$product_list = Product::all();
$empty_cart = new Cart();
$selected_products = array();
return view('models.carts.create', compact('product_list','empty_cart','selected_products'));
}
public function store(Request $request){}
The view where this happens has the list where the selected products will be shown and a button to add a product to the list.
create.blade.php:
#extends('adminlte::page')
#section('content')
<div class="container"><div class="row justify-content-center"><div class="col-md-8"><div class="card">
<div class="card-header">
<h3 class="card-title"> New Cart </h3>
<div class="card-tools">
<a class="btn btn-success btn-tool" href="#" data-toggle="modal" data-target="#add">
<i class="fas fa-plus"></i> Add Product
</a>
</div>
</div><div class="card-body">
<table class="table table-striped projects table-sm">
<thead><tr><th>#</th><th>Name</th><th>Unit Cost</th><th>Amount</th><th>Discount</th><th>Final Cost</th><th></th></tr></thead>
<tbody>
#forelse($selected_products as $prodCart)
<tr>
<td>{{ $loop->iteration }}</td>
<td>{{ $prodCart->product->name }}</td>
<td>{{ $prodCart->product->price }}</td>
<td>{{ $prodCart->amount }}</td>
<td>{{ $prodCart->discount }}</td>
<td>{{ $prodCart->cost }}</td>
<td>
<a class="btn btn-danger btn-circle btn-sm" href="#" data-target="#delete">
<i class="fa fa-trash"></i>
</a>
</td>
</tr>
#empty
<tr><td colspan="7">Empty Cart</td></tr>
#endforelse
</tbody></table></div>
<div class="card-footer">
#if(!empty($selected_products))
<button class="btn btn-success" href="send $selected_products to CartController's store method" > Buy Cart </button>
#endif
</div></div></div></div></div>
#include('models.carts.add')
#endsection
#section('scripts')
#stop
The 'Add Product' button toggles a modal which has the displayed list of products, plus the 'amount' and 'discount' number inputs to create a CartProd with, and the button to actually add them to the list.
add.blade.php:
<!--Modal add -->
<div class="modal fade" id="add" tabindex="-1" role="dialog" aria-hidden="true"><div class="modal-dialog modal-lg"><div class="modal-content">
<div class="modal-header bg-dark">
<h5 class="modal-title" id="exampleModalLabel">Add Product to Cart</h5>
<span class="badge badge-danger" class="close" data-dismiss="modal" aria-label="Close">
<i class="fas fa-times fa-lg" style="color:#fff"></i>
</span>
</div>
<div class="modal-body">
<table class="table table-striped projects table-sm">
<thead><tr><th>#</th><th>Name</th><th>Amount</th><th>Price</th><th>Added</th><th>Discount</th><th>Amount</th><th>Add</th></tr></thead>
<tbody>
#forelse($product_list as $product)
<tr>
<td>{{ $loop->iteration }}</td>
<td>{{ $product->name }}</td>
<td>{{ $product->amount }}</td>
<td>{{ $product->price }}</td>
<td>{{ $product->created_at }}</td>
<td><input type="number" name="discount" id="discount" min="0" max="100" size="3" value="0"></td>
<td><input type="number" name="amount" id="amount" min="1" max="{{$product->amount}}" size="3" value="1"></td>
<td>
<a class="btn btn-info btn-circle btn-sm" data-datos="{{$product}}">
<i class="fa fa-plus"></i>
</a>
</td>
</tr>
#empty
<tr>
<td>No Products Available.</td>
</tr>
#endforelse
</tbody>
</table>
</div></div></div></div>
Here are the issues:
I haven't found the way to create this new CartProd instance within the modal, and send it back to the list of selected products.
How to delete said CartProd if adding it was a mistake.
How to update the selected product list every time a new product is added/deleted.
The 'Buy Cart' button to send me to the store method of the controller (where all the fancy stuff will be done to save the list of products.)
Thank you so much for your help!
You can create this model with livewire if you are familiar which has all the answers to your issues
First, wrap the modal fields with a form element
//Your modal
<form action="{{route('your_route'}}" method="post">
#csrf
<input type="number" name="discount" id="discount" min="0" max="100" size="3" value="0">
<input type="number" name="amount" id="amount" min="1" max="{{$product->amount}}" size="3" value="1">
<a class="btn btn-info btn-circle btn-sm" data-datos="{{$product}}" type="submit">
<i class="fa fa-plus"></i>
</a>
</form>
In the controller method you can redirect back to your create.blade.php with a message and the list will refresh.
public function store(Request $request)
{
// your saving logic
return redirect()->route('your_create_route')
->with('success', 'Added successfully');
}
As your question is too broad you can trigger a delete action with actioning a button by passing the product ID to delete. This is a custom approach from this. Normally you delete with the laravel's delete method #method('delete') and a POST method.
// delete link
<a href="{{route('delete_route', $product->id)}}">
Delete
</a>
// web.php
Route::get('delete/{id}','YourController#destroy')->name('delete_route');

load colors from the database and list with color in the background

enter #foreach ($colors as $color)
<tr>
<th scope="row">{{ $color->code }}</th>
<td>{{ $color->name }}</td>
<td>
<div class="col-md-6 cor"></div>
<style>
.cor {
background-color: {{ $color->code }};
}
</style>
</td>
<td><span class="badge badge-success">Active</span></td>
<td>
<a href="{{ URL::route('edit.customer', array('customer'=>$color->id_color)) }}" class="text-success mr-2">
<button class="nav-icon i-Pen-2 font-weight-bold btn btn-warning m-0" type="button" data-toggle="tooltip" data-placement="top" title="Editar Cliente"></button>
</a>
<a href="{{ URL::route('delete.customer', array('customer'=>$color->id_color)) }}" class="text-danger mr-2">
<button class="nav-icon i-Close-Window font-weight-bold btn btn-danger m-0" type="button" data-toggle="tooltip" data-placement="top" title="Eliminar Cliente"></button>
</a>
</td>
</tr>
#endforeach here
I want to load color codes from the database, I want the color that is recorded to appear to the user, this foreach loads me the last color in all
You're generating the CSS rule
.cor {
background-color: {{ $color->code }};
}
multiple times, but with a different colour each time. So whatever the last definition is, it just overrides all the previous versions. Think about it - if you declare something with the same name multiple times, how do you expect the browser to tell them apart or know which one to apply to which element? It can't do that. It can only use one version, so it just uses the last one you created.
Since the colour will be unique to each copy of the div, you'd be better off just writing
<div class="col-md-6" style="background-color: {{ $color->code }}"></div>
instead.

I want to disable the delete post button inside in post foreach blade.. Laravel

I want to disable the delete post button inside in post foreach blade laravel . where post has created_at in database , i want the " delete post button" get disable after 15 days
i tried with some javascript tutorials but i couldn't achieve that thing
Can anyone please help me.it would be much appreciated if you could help me
thanks in adavance
<table id="" class="table ">
<thead>
<tr class="data-item master">
<th>Name</th>
<th>post</th>
<th>about</th>
<th>image</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
#foreach($data as $d)
<tr>
<td>{{$d->name}}</td>
<td>{{$d->postbody}}</td>
<td>{{$d->about}}</td>
<td>{{url($d->image)}}</td>;
<td><a href="{{ URL::to('edit/product/'.$d->id) }} "
class="btn btn-sm btn-info" title="edit">
<i class="fa fa-edit">edit post</i></a>
</td>
<td><a href="{{ URL::to('delete/product/'.$d->id) }} "
class="btn btn-sm btn-info" title="delete">
<i class="fa fa-trash"></i>delete post</a>
</td>
</tr>
#endforeach
</tbody>
</table>
You can not disable an anchor tag but you can change the URL to # as dummy url
#if(\Carbon\Carbon::parse($d->created_at)->addDays(15) < \Carbon\Carbon::now())
<a href="#"
class="btn btn-sm btn-info" title="delete">
<i class="fa fa-trash"></i>delete post</a>
#else
<a href="{{ URL::to('delete/product/'.$d->id) }}"
class="btn btn-sm btn-info" title="delete">
<i class="fa fa-trash"></i>delete post</a>
#endif
It's simple use and conditional statement on the disable attribute.
Something like This
<button class="anyClass" {{ Carbon::addDays(15)->greaterThan($post->created_at) ? 'disable' : ' }}>Delete</button>
I think something like this will work

(2/2) ErrorException Trying to get property of non-object

In course table have department field where the value is number and when i get data form this table i don't want to show number.I want to show department name but i can not do it i want expert help.I have attached picture and codethis is course table.
Controller code :
public function index()
{
$allCourse = Course::paginate(10);
return view ('Admin.course.index',['allCourse'=> $allCourse]);
}
index.blade.php
#foreach($allCourse as $course)
<tr class="info">
<td class="success">{{$course->id}}</td>
<td class="success">{{$course->code}}</td>
<td class="success">{{$course->name}}</td>
<td class="success">{{$course->credit}}</td>
<td class="success">{{$course->description}}</td>
<td class="success">{{$course->department->$department}}</td>
<td class="success">{{$course->semester}}</td>
<td class="success">
<div class="btn btn-success">
<i class="fa fa-pencil" aria-hidden="true"></i>
</div>
<div class="btn btn-danger">
<a class="delete_link" href="{{ url('/Admin/course',[$course->id,'delete']) }}"><i class="fa fa-trash" aria-hidden="true"></i></a>
</div>
{{-- {!! Form::open(['url' => 'foo/bar']) !!}
<div>
{{ Form::button('<i class="fa fa-trash"></i>', ['type' => 'submit', 'class' => 'btn btn-danger '] ) }}
</div>
{!! Form::close() !!}--}}
</td>
</tr>
#endforeach
</table>
{{ $allCourse->links() }}
</div>
</div>
</div>
#endsection
error page
Make sure you have Relation between course and department
You can find the documentation here
Secondly, you have a typo in your code. Change this to
<td class="success">{{$course->department->$department}}</td>
this
<td class="success">{{$course->department->department}}</td>
Hope this helps.
Eloquent just fetch everything inside your specified table. If you want department name (i assume you have department table), you need to define the relationship. Eloquent do have method for defining relationship.
For me, just use fluent 'join'.
Course::join('department_table','Course.department','=','department_table.department_id')->paginate(10);
Once you change your query to this, change from
{{$course->department->$department}}
to
{{$course->department_name}}
This is the easier way, but if you are willing to study, have a look here https://laravel.com/docs/5.5/eloquent-relationships

Categories