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;
}
}
Related
This is my post page:
<template>
<br/>
<pagination
#pageClicked="getPage($event)"
v-if="this.getdArray.data != null"
:links="this.getdArray.links"
/>
<a
:href="route('create',{region1:this.region})"
class="list-group-item list-group-item-action w-25 float-right text-gray-200 align-text-bottom"
style="background-color: rgb(00, 00, 00)"
>
글작성
<!-- {{ this.getdArray }} -->
</a>
<div v-for="post in this.getdArray.data" :key="post.id">
<a
:href="route('show',{'id': post.id},{region1:this.region})"
class="list-group-item list-group-item-action w-100 float-right text-gray-200 "
style="background-color: rgb(50, 60, 60)"
>
{{post.title}}
</a>
</div>
</template>
<script>
import {InertiaLink} from "#inertiajs/inertia-vue3";
import Pagination from "./Pagination.vue";
export default {
data(){
return{
postdata: []
}
},
methods: {
check(){
console.log(this.postRegion);
},
getPage(url) {
axios
.get(url)
.then((res) => {
this.getdArray = res.data;
console.log(res.data);
})
.catch((err) => {
console.log(err);
});
},
},
props: [
'regionN', 'posts','dArray'
],
data() {
return {region: "", getposts: [],getdArray:[]}
},
beforeMount() {
this.region = this.regionN;
this.getposts = this.posts;
this.getdArray=this.dArray;
// console.log(this.getposts);
console.log(this.region);
console.log(this.getposts);
console.log(this.getdArray);
},
components: {
InertiaLink,
Pagination
},
computed: {
postRegion: function () {
return this
.getposts
.filter((post) => {
if (post.region == this.region) {
return post
}
});
}
//computed 로 필요한 데이터만 반환
//.filter 함수는 배열에 적용가능하며 배열내 각 원소에 적용
}
}
</script>
And this is my pagination page:
<template>
<div v-if="links.length > 3">
<div class="flex flex-wrap -mb-1">
<template v-for="(link, key) in links">
<div
v-if="link.url === null"
:key="key"
class="px-4 py-3 mb-1 mr-1 text-sm leading-4 text-gray-400 border rounded"
v-html="link.label"
/>
<div
v-else
#click="pageClicked(link.url)"
:key="link.url"
class="px-4 py-3 mb-1 mr-1 text-sm leading-4 border rounded hover:bg-white focus:border-indigo-500 focus:text-indigo-500"
:class="{ 'bg-white': link.active }"
:href="link.url"
v-html="link.label"
></div>
</template>
</div>
</div>
</template>
<script>
export default {
props: {
links: Array,
},
methods: {
pageClicked(url) {
this.$emit("pageClicked", url);
},
},
};
</script>
When I push list button,
something like
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title inertia>Laravel</title>
This kind of thing send by res.data
How can I fix it? On other people's code, res.data has data and link,
but on my res.data, HTML code send back.
this is my controller
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Storage;
use Inertia\Inertia;
use Symfony\Component\Console\Input\Input;
class PostController extends Controller
{
// public function index()
// {
// //
// }
public function create(Request $request)
{
$region1 = $request->region1;
return Inertia::render('Create', ["region1" => $region1]);
}
public function store(Request $request)
{
$request->validate([
'title' => 'required|min:3',
'content' => 'required|min:3',
'image' => 'image',
// 'region1' => 'required'
]);
// $user_id = Auth::user()->id;
// $region =
// $request->region1;
$post = new Post();
$post->user_id = Auth::user()->id;
$post->title = $request->title;
$post->content = $request->content;
//inertia 에서의 post요청
//function storePost() {
//form.post('/post/store')
//}
//와 같이.
$path = $request->file('image')->store('image', 'public');
$imgpath = "/storage/" . $path;
$post->image = $imgpath;
$post->region = $request->region;
$post->save();
// $validated = array_merge($validated, ['image' => $imgpath]);
// $validated = array_merge($validated, ['user_id' => $user_id]);
// $validated = array_merge($validated, ['region' => $region]);
// Post::create($validated);
// if ($request->hasFile('image')) {
// $image_path = $request->file('image')->store('image', 'public');
// }
// $post = new Post();
// $post->title = $request->title;
// $post->content = $request->content;
// $post->user_id = Auth::user()->id;
// $post->region = $request->region;
// $post->image = "/storage/" . $image_path;
// $posts = Post::all();
// $b2018 = DB::table('crimes')->get();
// $t2018 = json_decode(json_encode($b2018), true);
// $region1 = $request->region1;
// $posts = Post::find($post->id);
return Redirect::route('main');
}
public function show($id)
{
$posts = Post::find($id);
return Inertia::render('Show', ["posts" => $posts]);
}
public function edit($id)
{
$post = Post::find($id);
return Inertia::render('Edit', ["post" => $post]);
}
public function update(Request $request, $id)
{
$post = Post::find($id);
$post->title = $request->title;
$post->content = $request->content;
$post->user_id = Auth::user()->id;
if ($request->hasFile('image')) {
$fileName = time() . '_' . $request->file('image')->getClientOriginalName();
$request->file('image')->storeAs('public/images', $fileName);
if ($fileName) {
$input = array_merge($input, ['image' => $fileName]);
}
}
$post->save();
$posts = Post::find($id);
return Inertia::render('Show', ["posts" => $posts]);
}
public function destroy($id)
{
$post = Post::find($id);
$post->delete();
if ($post->image) {
Storage::delete('public/images/' . $post->image);
}
return Inertia::render('question');
}
}
i added my controller, and i tried to fix it but it still sent request twice...
I think problem is in your Laravel back-end or bad request in front-end side, sometime laravel return error in HTML format, if you not defined accept application/json in your request headers.
Try to resolve that problem first, and edit your question.
I try for a todo-list to be able to order the list via a filter so that can i have the list for today the list for tomorrow or the list of the week so i made my task controller able to take request et via the design pattern reposiory i take the request to do the eloquent request :
controller tasks :
class TaskController extends Controller
{
private $taskRepository;
public function __construct(TaskRepository $taskRepository)
{
$this->taskRepository = $taskRepository;
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(Request $request)
{
if(!empty($request)){
// dd($request);
$tasks = $this->taskRepository->all($request);
}else{
$tasks = $this->taskRepository->all();
}
return view('tasks.index', compact('tasks'));
}
}
taskrepository :
class TaskRepository implements RepositoryInterface
{
// model property on class instances
protected $task;
// Constructor to bind model to repo
public function __construct(Task $task)
{
$this->task = $task;
}
public function all(Request $request)
{
$sortBy = 'expired_at';
$order = Carbon::now();
$finish = null;
if($request)
{
if($request->has('today'))
{
$order = Carbon::today();
return Task::where($sortBy, $order)->get();
}
if($request->has('tomorow')){
$order = Carbon::tomorrow();
return Task::where($sortBy, $order)->get();
}
if($request->has('week'))
{
$order = Carbon::now()->startOfWeek();
$finish = Carbon::now()->endOfWeek();
return Task::whereBetween($sortBy, [$order, $finish])->get();
}
}else{
return Task::orderBy('order')->get();
}
}
to finish in my index i have form using the "get" method :
div>
<form action="{{ route('tasks.index') }}" class="flex justify-between items-center p-2">
<div>
<select name="orderByDate" id="">
#foreach(['today','tomorow', 'week'] as $orderDate)
<option value="{{ $orderDate }}">{{ ucfirst($orderDate) }}</option>
#endforeach
</select>
</div>
<div>
<button type="submit">Filter</button>
</div>
</form>
</div>
<ul class="my-5">
#foreach ($tasks as $task)
#if($task->order == 0)
<li class="flex text-red-600 justify-between p-2">
// task->name
// task-> date
// task-> edit
// task->delete
</li>
#else
<li class="flex justify-between items-center p-2">
// task->name
// task-> date
// task-> edit
// task->delete
</li>
#endif
#empty
<p>Pas de tâches aujourd'hui crée en une</p>
#endforelse
</ul>
#endsection
aparrently my foreach doesn't work with an array so if anyone have some lead to how should i approch this issue will be a live saver ?
Try this code for the repository function
public function all(Request $request)
{
$sortBy = 'expired_at';
$order = Carbon::now();
$finish = null;
if($request)
{
if($request->has('today'))
{
$order = Carbon::today();
return Task::query()->where($sortBy, $order)->orderBy($sortBy)->get();
}
if($request->has('tomorow')){
$order = Carbon::tomorrow();
return Task::query()->where($sortBy, $order)->orderBy($sortBy)->get();
}
if($request->has('week'))
{
$order = Carbon::now()->startOfWeek();
$finish = Carbon::now()->endOfWeek();
return Task::query()->whereBetween($sortBy, [$order, $finish])->orderBy($sortBy)->get();
}
}else{
return Task::query()->orderBy($sortBy)->get();
}
}
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);
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'
]);
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.