Laravel - Trying to get property 'is_approved' of non-object - laravel

In my Laravel-5.8 project I have this code
Controller
public function index()
{
$userCompany = Auth::user()->company_id;
$userEmployee = Auth::user()->employee_id;
$identities = DB::table('appraisal_identity')->select('id')->where('company_id', $userCompany)->where('is_current', 1)->first();
$currentstatus = AppraisalGoal::select('is_approved')->where('employee_id', $userEmployee)->where('appraisal_identity_id', $identities->id)->first();
$goals = AppraisalGoal::where('employee_id', $userEmployee)->where('appraisal_identity_id', $identities->id)->get();
$incompleteCount = $goals->filter(function($item) {
return ($item->is_approved == 0 || $item->is_approved == 2);
})->count();
return view('appraisal.appraisal_goals.index')->with(['goals' => $goals, 'incompleteCount' => $incompleteCount])->with('currentstatus', $currentstatus);
}
View
#foreach($goals as $key => $goal)
#if(in_array($goal->is_approved, [0, 2]))
<a class="btn btn-xs btn-info" href="{{ route('appraisal.appraisal_goals.edit', ['id'=>$goal->id]) }}">
Edit
</a>
#endif
#endforeach
<div class="row no-print">
<div class="col-12">
#if ($incompleteCount)
<i class="fas fa-arrow-right"></i> Publish
#endif
</div>
</div>
What I want to achieve is that when the page is loaded Edit and Publish buttons should only be visible when is_approved is 0 or 2.
Instead of seeing this I got this error:
Trying to get property 'is_approved' of non-object
How do I resolve it?
Thank you.

it looks like your query is not returning any result.
$goals = AppraisalGoal::where('employee_id', $userEmployee)->where('appraisal_identity_id', $identities->id)->get();
You can put an extra check to avoid this error
if(count($goals)){
$incompleteCount = $goals->filter(function($item) {
return ($item->is_approved == 0 || $item->is_approved == 2);
})->count();
}
else {
$incompleteCount = 0;
}
return view('appraisal.appraisal_goals.index')->with(['goals' =>
$goals, 'incompleteCount' => $incompleteCount])->with('currentstatus', $currentstatus);

Related

problem with livewire and arrays when trying to print to pdf

I'm having a problem with Livewire passing an array to a route so I can print it to pdf. I've got:
public $selectedProducts = [];
public $selectedAlm = [];
public $nombreComponente, $data, $categoriaId;
public function mount()
{
$this->categoriaId = "0";
$this->nombreComponente = 'Reportes';
$this->data = [];
$this->artcero = 'si';
}
where $selectedProducts and $selectedAlm are arrays and my intention is to pass them to another controller to be able to print them to pdf, but I can't seem to find a way
here is my controller:
public function reportearticuloPDF($categoriaId, $artcero, $selectedAlm, $selectedProducts)
{
if ($selectedProducts > 0) {
$data = $selectedProducts;
} else {
if ($categoriaId == null) {
$data = Articulo::join('categorias as c', 'c.id', 'articulos.categoria_id')
->select('articulos.*', 'c.nombre as catnom')
->whereHas('detallearticulos', function($q) {
$q->whereIn('almacen_id', $selectedAlm);
})
->when($artcero == 'no', function($query){
return $query->where('stock', '>', 0);
})
->OrderBy('id', 'ASC')
->get();
} elseif ($categoriaId !== null) {
$data = Articulo::join('categorias as c', 'c.id', 'articulos.categoria_id')
->select('articulos.*', 'c.nombre as catnom')
->whereHas('detallearticulos', function($q) {
$q->whereIn('almacen_id', $selectedAlm);
})->with('detallearticulos')
->when($artcero == 'no', function($query){
return $query->where('stock', '>', 0);
})
->where('categoria_id', $categoriaId)
->OrderBy('id', 'ASC')
->get();
}
}
$pdf = PDF::loadView('admin.report.articulopdf', compact('data'));
return $pdf->stream('Reporte_de_articulo.pdf');
}
my routes in web.php:
Route::get('report/articulopdf/{categoriaId}/{artcero}/{selectedAlm}/{selectedProducts}', [ReportController::class, 'reportearticuloPDF'])->name('reportearticulo.pdf');
Route::get('report/articulopdf/{categoriaId}/{artcero}/{selectedAlm}', [ReportController::class, 'reportearticuloPDF'])->name('reportearticulo.pdf');
my button:
<a href="{{ url('report/articulopdf' . '/' . $categoriaId . '/' . $artcero . '/' . $selectedAlm . '/' . $selectedProducts) }}"
class="btn btn-danger btn-sm btn-block {{ count($data) < 1 ? 'disabled' : '' }}" target="_blank">
Exportar reporte a PDF <i class="fas fa-file-pdf"></i></a>
that's the one that gives me the Array to string conversion error. I also tried it this way:
<a href="{{ route('reportearticuloPDF', $categoriaId, $artcero, $selectedAlm, $selectedProducts) }}"
class="btn btn-danger btn-sm btn-block {{ count($data) < 1 ? 'disabled' : '' }}" target="_blank">
Exportar reporte a PDF <i class="fas fa-file-pdf"></i></a>
but it gives me the error Too few arguments to function App\Http\Controllers\ReportController::reportearticuloPDF(), 0 passed in C:\xampp\htdocs\sistemainventarioGDS\vendor\laravel\framework\src\Illuminate\Routing\Controller.php on line 54 and exactly 4 expected
In your routes you create two routes with the same method and same function reportearticuloPDF in the controller with different params !!

Conditional Component variable value increment Vue/Laravel

[1]so i have a laravel project going on, and i want to increment the value of the variable deliver_later_num, depending on the "deliver_today" present in the same component in the items[] array, which i am outputting in the template file, i cannot figure how to do it, i do not know if i can increment the value on the template side or on the component side. here is the component code:
cartContent = new Vue({
el: '#cartList',
data: {
items: [], //array containing all the items
deliver_later_num: 0, //value to increment
},
methods: {
remove: function (product_id) {
removeProductIfFromCart(product_id);
},
incQuantity: function (product_id){
incCart(product_id)
},
decQuantity: function (product_id){
decCart(product_id)
},
}
})
here is the template file :
<div id="cartList">
<div v-for="item in items" class="items col-xs-12 col-sm-12 col-md-12 col-lg-12 clearfix">
<div class="info-block block-info clearfix" v-cloak>
<div class="square-box pull-left">
<img :src="item.attributes.image" class="productImage" width="100" height="105" alt="">
</div>
<h6 class="product-item_title">#{{ item.name }}</h6>
<p class="product-item_quantity">#{{ item.quantity }} x #{{ item.attributes.friendly_price }}</p>
<ul class="pagination">
<li class="page-item">
<button v-on:click="decQuantity(item.id)" :value="item.id" class="page-link" tabindex="-1">
<i class="fa fa-minus"></i>
</button>
</li>
<li class="page-item">
<button v-on:click="incQuantity(item.id)" :value="item.id" class="page-link" >
<i class="fa fa-plus"></i>
</button>
</li>
<li class="page-item">
<button v-on:click="remove(item.id)" :value="item.id" class="page-link" >
<i class="fa fa-trash"></i>
</button>
</li>
<input hidden class="delivers_today_state" type="text" :value=" item.attributes.delivers_today "> // if this equals 0 i want to increment the deliver_later_num value
</ul>
</div>
</div>
</div>
laravel controller code :
public function add(Request $request){
$item = Items::find($request->id);
$restID=$item->category->restorant->id;
//Check if added item is from the same restorant as previus items in cart
$canAdd = false;
if(Cart::getContent()->isEmpty()){
$canAdd = true;
}else{
$canAdd = true;
foreach (Cart::getContent() as $key => $cartItem) {
if($cartItem->attributes->restorant_id."" != $restID.""){
$canAdd = false;
break;
}
}
}
//TODO - check if cart contains, if so, check if restorant is same as pervious one
// Cart::clear();
if($item && $canAdd){
//are there any extras
$cartItemPrice=$item->price;
$cartItemName=$item->name;
$theElement="";
//Is there a varaint
//variantID
if($request->variantID){
//Get the variant
$variant=Variants::findOrFail($request->variantID);
$cartItemPrice=$variant->price;
$cartItemName=$item->name." ".$variant->optionsList;
//$theElement.=$value." -- ".$item->extras()->findOrFail($value)->name." --> ". $cartItemPrice." ->- ";
}
foreach ($request->extras as $key => $value) {
$cartItemName.="\n+ ".$item->extras()->findOrFail($value)->name;
$cartItemPrice+=$item->extras()->findOrFail($value)->price;
$theElement.=$value." -- ".$item->extras()->findOrFail($value)->name." --> ". $cartItemPrice." ->- ";
}
Cart::add((new \DateTime())->getTimestamp(), $cartItemName, $cartItemPrice, $request->quantity, array('id'=>$item->id,'variant'=>$request->variantID, 'extras'=>$request->extras,'restorant_id'=>$restID,'image'=>$item->icon,'friendly_price'=> Money($cartItemPrice, env('CASHIER_CURRENCY','usd'),true)->format(),'delivers_today' => $item->deliverstoday ));
return response()->json([
'status' => true,
'errMsg' => $theElement
]);
}else{
return response()->json([
'status' => false,
'errMsg' => __("You can't add items from other restaurant!")
]);
//], 401);
}
}
public function getContent(){
//Cart::clear();
return response()->json([
'data' => Cart::getContent(),
'total' => Cart::getSubTotal(),
'status' => true,
'errMsg' => ''
]);
}
link to the items array vue dev tools screenshot
[1]: https://i.stack.imgur.com/smLRV.png
thanks for your precious help and time.
A computed property can be used if the deliver_later_num is only dependent on the presence/absence of deliver_today on elements of items array
cartContent = new Vue({
el: '#cartList',
data: {
items: {}
},
computed: {
deliver_later_num() {
let num = 0;
Object.keys(this.items).forEach(key => {
let item = this.items[key];
Object.keys(item).forEach(k => {
if(k === 'deliver_today' && item[k]) {
num++;
}
});
});
return num;
},
}

Laravel: ErrorException Undefined variable: items

So i want to be able to view my cart on one of my pages. I can simply 'add to cart' and the value of the number of items in my cart will show on the top right corner of my page. When i go to click on the cart i receive this error:
ErrorException
Undefined variable: items.
I have the following code:
Cart.php:
class Cart {
public $items = null;
public $totalQty = 0;
public $totalPrice = 0;
public function __Construct($oldCart)
{
if ($oldCart) {
$this->$items = $oldCart->$items;
$this->$totalQty = $oldCart->$totalQty;
$this->$totalPrice = $oldCart->$totalPrice;
}
}
public function add($item, $id){
$storedItem = ['qty' => 0, 'price' => $item->price, 'item' => $item];
if($this->items) {
if (array_key_exists($id, $this->items)){
$storedItem = $this->items[$id];
}
}
$storedItem['qty'] ++;
$storedItem['price'] = $item->price * $storedItem['qty'];
$this->items[$id] = $storedItem;
$this->totalQty++;
$this->totalPrice += $item->price;
}
PostsController.php:
public function getCart() {
if (!Session::has('cart')) {
return view('posts.shopping-cart', ['post' => null]);
}
$oldCart = Session::get('cart');
$cart = new Cart($oldCart);
return view('posts.shopping-cart', ['post' => $cart->items, 'totalPrice'=> $cart->totalPrice]);
}
Payment.blade:
#if(Session::has('cart'))
<div class="row">
<div class="col-sm-6 col-md-6 col-md-offset-3 col-sm-0ffset-3">
<ul class="list-group">
#foreach($posts as $post)
<li class="list-group-item">
<span class="badge">{{ $post['qty']}}</span>
<strong>{{ $post['item']['title']}}</strong>
<span class="label label-success">{{$post['price']}}</span>
<div class="btn-group">
Web.api
Route::get('/shopping-cart', [ 'uses' => 'PostsController#getCart', 'as' => 'product.shoppingCart' ]);
But when i click on the my cart link that is in navbar.php:
<a class="nav-link " href="{{ route('product.shoppingCart')}}">Cart
Cart {{ Session::has('cart') ? Session::get('cart')->totalQty : ''}}
I then get the error undefined items variable
The error is on the constructor of the Cart class. You have put the dollar sign on the property names.
Just remove the dollar signs.
public function __Construct($oldCart)
{
if ($oldCart) {
$this->items = $oldCart->items;
$this->totalQty = $oldCart->totalQty;
$this->totalPrice = $oldCart->totalPrice;
}
}

Laravel clicking on link adds to url

Okay I have a small problem.
When user clicks on a link it goes to website/create/business which is fine however if nothing is done but the link is clicked again, it goes to website/create/business/create/business for whatever reason.
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
{{ Auth::user()->name }} <span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
Profile
Add Business
<a href="{{ url('/logout') }}" onclick="event.preventDefault(); document.getElementById('logout-form').submit();">
Logout
</a>
<form id="logout-form" <a href="{{ url('home') }}" action="{{ url('/logout') }}" method="POST" style="display: none;">
{{ csrf_field() }}
</form>
</li>
</ul>
</li>
Routes:
Route::get('profile/{user_id}', 'ProfileController#checkid');
Route::post('update', 'ProfileController#updateProfile');
Route::get('create/business', 'BusinessController#addBusiness');
Route::post('create', 'BusinessController#createBusiness');
ProfileController:
public function checkid($user_id) {
if (Auth::check())
{
$user_id = Auth::id();
return view('profile', [
'id' => $user_id
]);
}
}
function updateProfile(Request $request) {
$user = $request->user();
$twitter = $request->input('twitter');
$facebook = $request->input('facebook');
$instagram = $request->input('instagram');
$telephone = $request->input('telephone');
$user->twitter_personal = $twitter;
$user->facebook_personal = $facebook;
$user->instagram_personal = $instagram;
$user->telephone = $telephone;
$result = $user->save();
if($result) {
$message = 'success';
}else{
$message = 'error';
}
return redirect()->back()->withInput()->with('message', $message);
}
BusinessController:
function addBusiness() {
return view('addBusiness');
}
function createBusiness(Request $request) {
$name = $request->input('name');
$type = $request->input('type');
$email = $request->input('email');
$user_id = Auth::id();
$business = new Business();
$business->name = $name;
$business->type = $type;
$business->email = $email;
$business->user_id = $user_id;
$business->save();
$address1 = $request->input('address1');
$address2 = $request->input('address2');
$town = $request->input('town');
$city = $request->input('city');
$postcode = $request->input('postcode');
$telephone = $request->input('telephone');
$address = new Address();
$address->firstline_address = $address1;
$address->secondline_address = $address2;
$address->town = $town;
$address->city = $city;
$address->postcode = $postcode;
$address->telephone = $telephone;
$address->save();
$result = $business->save();
$result2 = $address->save();
$business_id = $business->id;
$address_id = $address->id;
DB::table('business_address')->insert(array('business_id' => $business_id, 'address_id' => $address_id));
DB::table('user_business')->insert(array('user_id' => $user_id, 'business_id' => $business_id));
if($result && $result2) {
$message = 'success';
}else{
$message = 'error';
}
return redirect()->back()->withInput()->with('message', $message);
}
<a href="create/business/"> must be <a href="/create/business/"> to solve this, because your current link is relative, not absolute, so when you click it again, the same reference is added at the end of your current URL.
Anyway, you should generate links in the Laravel way to avoid other issues in the future:
Route::get('create/business', 'BusinessController#addBusiness');
<a href="{{ url('create/business') }}">
or
Route::get('create/business', 'BusinessController#addBusiness')->name('createBusiness');
<a href="{{ route('createBusiness') }}">
Personally I prefer the second one, so if I change the route URL the links will still work, but it requires to add name('yourRoute') on your route definition.
Try to use the route() function. For this example: Add Business. When your route changes it is automatically changed throughout the application.
You can name your routes like this:
Route::get('create/bussiness', [
'as' => 'my_route_name',
'uses' => 'BusinessController#createBusiness'
]);

Property of non-object in laravel 4

I'm using laravel 4 and I'm getting this error when I attempt to create a menu with a dropdown
Trying to get property of non-object (View: /Applications/MAMP/htdocs/test/app/views/layouts/master.blade.php) (View: /Applications/MAMP/htdocs/test/app/views/layouts/master.blade.php)
I can't see where I'm going wrong
My master.blade.php
<li class="dropdown">
work<span class="caret"></span>
<ul class="dropdown-menu" role="menu">
#foreach($dropdowns as $dropdown)
<li>
{{ $dropdown->title }}
</li>
#endforeach
</ul>
</li>
My PageController
$currentPage = new Page($pages[0]->id);
$dropdowns = $currentPage->getPagesSelectList("parent", "", "");
return View::make('index', compact('dropdowns'));
My Page model
public function getPagesSelectList($name, $default = "", $js = "", $flag = true)
{
$list = array(
'name' => $name,
'default' => $default,
'js' => $js,
'pages' => $this->getSubPages($flag, $default)
);
return (object)$list;
}
public function getSubPages($flag, $default, $parent = 0, $num = 1)
{
$pages = array();
$pageSql = \Page::where('parent', '=', $parent)->orderBy('num', 'ASC')->get();
foreach ($pageSql as $result)
{
$page = new Page($result->id);
$page->setFromDatabase();
$page->default = $default;
$page->select = '';
if( $page->id == $default )
$page->select = $default;
$page->space = $num;
if(!empty($page))
$pages[] = $page;
$children = $page->getSubPages($flag, $default, $page->id, $num + 1);
if(!empty($children))
$pages[] = $children;
}
return array_flatten($pages);
}
Assuming that the other code works fine, in Blade instead of:
#foreach($dropdowns as $dropdown)
<li>
{{ $dropdown->title }}
</li>
#endforeach
you should use:
#foreach($dropdowns->pages as $dropdown)
<li>
{{ $dropdown->title }}
</li>
#endforeach
This is because in getPagesSelectList you assign result of getSubPages to pages index of array and then you convert array to object.

Resources