Undefined property: App\Cart::$totalPrice - laravel

Hello I am making a cart but when I click on add to cart link then it says:
Undefined property: App\Cart::$totalPrice
Error: https://ibb.co/ysB5CfG
model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Cart
{
private $contents;
private $totalQty;
private $contentsPrice;
public function __construct($oldCart){
if ($oldCart) {
$this->contents = $oldCart->contents;
$this->totalQty = $oldCart->totalQty;
$this->totalPrice = $oldCart->totalPrice;
}
}
public function addProduct($product, $qty){
$products = ['qty' => 0, 'price' => $product->price, 'product' => $product];
if ($this->contents) {
if (array_key_exists($product->slug, $this->contents)) {
$product = $this->contents[$product->slug];
}
}
$products['qty'] +=$qty;
$products['price'] +=$product->price * $product['qty'];
$this->contents[$product->slug] = $product;
$this->totalQty+=$qty;
$this->totalPrice += $product->price;
}
public function getContents()
{
return $this->contents;
}
public function getTotalQty()
{
return $this->totalQty;
}
public function getTotalPrice()
{
return $this->totalPrice;
}
}
controller:
public function cart()
{
if (!Session::has('cart')) {
return view('products.cart');
}
$cart = Session::has('cart');
return view('product.cart', compact('cart'));
}
public function addToCart(Product $product, Request $request, $qty= null)
{
if(empty(Auth::user()->email)){
$data['email'] = '';
}else{
$data['email'] = Auth::user()->email;
}
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$qty = $request->qty ? $request->qty : 1;
$cart = new Cart($oldCart);
$cart->addProduct($product, $qty);
Session::put('cart', $cart);
return redirect()->back()->with('flash_message_success', 'Product $product->title has been successfully added to Cart');
}
routes:
Route::get('cart', 'Admin\ProductController#cart')->name('product.cart');
// Add to cart
Route::get('/addToCart/{product}/{qty?}', 'Admin\ProductController#addToCart')->name('addToCart');

You should use get() methods in cart() function in controller file.
public function cart()
{
if (!Session::has('cart')) {
return view('products.cart');
}
$cart = Session::get('cart');
return view('product.cart', compact('cart'));
}

Related

Laravel: Pagination error when clicking category page

I'm successfully making pagination, but when I click a category I got an error message:
BadMethodCallException Method
Illuminate\Database\Eloquent\Collection::currentPage does not exist.
This is my view:
Halaman: {{$gmproducts->currentPage()}}<br/>
Jumlah data: {{$gmproducts->total()}}<br/>
Data perhalaman: {{$gmproducts->perPage()}}<br/>
{{$gmproducts->links()}}
This is my controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Gmproducts;
use App\Gmcategories;
class GoldmartController extends Controller
{
public function index()
{
$gmproducts = Gmproducts::orderBy('id', 'desc')->paginate(10);
$gmcategories = Gmcategories::all();
return view('frontend.pages.goldmart', compact('gmproducts', 'gmcategories'));
}
public function readCategory($slug)
{
$category = Gmcategories::where('slug', $slug)->first();
$gmcategories = Gmcategories::all();
if($gmcategories)
{
$gmproducts = Gmproducts::where('category_id', $category->id)->get();
return view('frontend.pages.goldmart', compact('gmproducts', 'category', 'gmcategories'));
}
else
{
return redirect('/');
}
}
}
In your readCategory function $gmproducts is not paginated:
public function readCategory($slug)
{
$category = Gmcategories::where('slug', $slug)->first();
$gmcategories = Gmcategories::all();
if($gmcategories)
{
$gmproducts = Gmproducts::where('category_id', $category->id)->paginate(10);
return view('frontend.pages.goldmart', compact('gmproducts', 'category', 'gmcategories'));
}
else
{
return redirect('/');
}
}

Laravel method in getCustomAttribute returning cullection null

I am trying to modify $category->slug by getSlugAttribute(). My Category class like this,
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Collection;
class Category extends Model
{
public function getSlugAttribute(){
return $this->getRoute($this);
}
//Testing _____________________________________________________
private $routes = [];
public function getRoute(Category $category)
{
$this->determineCategoriesRoutes();
return $this->routes[$category->id];
}
private function determineCategoriesRoutes()
{
$categories = $this->all()->keyBy('id');
foreach ($categories as $id => $category) {
$slugs = $this->determineCategorySlugs($category, $categories);
if (count($slugs) === 1) {
$this->routes[$id] = '/' . $slugs[0];
}
else {
$this->routes[$id] = '/' . implode('/', $slugs);
}
}
}
private function determineCategorySlugs(Category $category, Collection $categories, array $slugs = [])
{
array_unshift($slugs, $category->slug);
if ($category->parent_id != 0) {
$slugs = $this->determineCategorySlugs($categories[$category->parent_id], $categories, $slugs);
}
return $slugs;
}
//End Testing__________________________________________________
//end of this class
}
Now when I request for categories it's just loading and giving me a blank page.
Route::get('/test', function(App\Category $category){
$categories = $category->all();
return $categories;
});
This is my test route, also there is no error.

Inserting Data in Pivot Table

The two tables tbl_product_manager and tbl_tags with many to many relations. I used eloquent to to make a relations between the corresponding models. I am able to to insert the data in these two table but the problem is the pivot table is not updated correspondingly.
Controller.php:
public function addProduct()
{
$rules = array('product_name' => 'required',
'product_url' => 'required');
$validator = Validator::make(Input::all(), $rules);
if($validator->fails()){
Session::flash('class', 'alert alert-error');
Session::flash('message', 'Some fields are missing');
return View::make('admin.product.add');
}
else {
$productName = Input::get('product_name');
$productUrl = Input::get('product_url');
$productUrl = preg_replace('/[^A-Za-z0-9\-]/', '', $productUrl);
$productExist = ProductManagementModel::checkExist($productUrl);
if( count($productExist)!=0) {
$message = 'product <b>'.$productName.'</b> with url <b>'.$productUrl.'</b> is already exist';
Session::flash('class', 'alert alert-error');
Session::flash('message', $message);
return View::make('admin.product.add');
}
else {
$imageFile = Input::file('userfile');
$destinationPath = 'uploads/products/';
$rEFileTypes = "/^\.(jpg|jpeg|gif|png){1}$/i";
$maximum_filesize = 1 * 1024 * 1024;
if($imageFile) {
$filename = $imageFile->getClientOriginalName();
$extension = strrchr($filename, '.');
$size = $imageFile->getSize();
$new_image_name = "products" . "_" . time();
if ($size <= $maximum_filesize && preg_match($rEFileTypes, $extension)) {
$attachment = $imageFile->move($destinationPath, $new_image_name.$extension);
} else if (preg_match($rEFileTypes, $extension) == false) {
Session::flash('class', 'alert alert-error');
Session::flash('message', 'Warning : Invalid Image File!');
return View::make('admin.product_management.add');
} else if ($size > $maximum_filesize) {
Session::flash('class', 'alert alert-error');
Session::flash('message', "Warning : The size of the image shouldn't be more than 1MB!");
return View::make('admin.product_management.add');
}
}
$logo = isset($attachment) ? $new_image_name . $extension : NULL;
$objectProduct = new ProductManagementModel;
$objectProduct->product_name = Input::get('product_name');
$objectProduct->product_url = $productUrl;
$objectProduct->category_id = Input::get('category_id');
$objectProduct->product_cost = Input::get('product_cost');
$objectProduct->product_short_description = Input::get('product_short_description');
$objectProduct->product_description = Input::get('product_description');
$objectProduct->is_active = Input::get('is_active');
$objectProduct->created_at = Auth::user()->id;
$objectProduct->updated_at = Auth::user()->id;
if($logo != '')
{
$objectProduct->product_attachment = $logo;
}
$objectTags = new TagModel;
$objectTags->size_id = Input::get('size_id');
$objectTags->brand_id = Input::get('brand_id');
$objectTags->color_id = Input::get('color_id');
$objectTags->food_id = Input::get('food_id');
$objectTags->save();
//$tag = new TagModel::all();
$objectProduct->save();
if(isset($request->tags)) {
$post->Tags()->sync($request->tags, false);
}
if($objectProduct->id) {
Session::flash('class', 'alert alert-success');
Session::flash('message', 'Product successfully added');
return View::make('admin.product_management.add');
} else {
Session::flash('class', 'alert alert-error');
Session::flash('message', 'Something error');
return View::make('admin.product_management.add');
}
}
}
}
ProductManagementModel.php
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class ProductManagementModel extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $table = 'product_manager';
public function Tags(){
return $this->belongsToMany('TagModel', 'product_tag', 'product_id', 'tag_id');
}
public function Categories(){
return $this->hasOne('CategoriesModel', 'id');
}
public static function getAllProducts(){
return $products = ProductManagementModel::with('categories','tags')->get();
}
public static function checkExist($url)
{
return $products = DB::table('product_manager')
->where('is_deleted', 0)
->where('product_url', $url)
->first();
}
}
TagModel.php
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class TagModel extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $table = 'tag';
public function ProductManagents() {
return $this->belongsToMany('ProductManagentModel');
}
public function Color(){
return $this->hasOne('ColorModel', 'color_id');
}
public function Brand() {
return $this->hasOne('BrandproModel','brand_id');
}
public function size() {
return $this->hasOne('SizeModel','size_id');
}
public function food() {
return $this->hasOne('FoodModel','food_id');
}
}
During my research i found that using sync function will be appropriate to updated the pivot table. But I failed to use it.
I am expecting to resolve this problem or something new way to find out the solution.
Thanks in advance.
Look at attach, detach or synch method :
https://laravel.com/docs/5.5/eloquent-relationships#updating-many-to-many-relationships
Note it's more easily if you respect the eloquent naming convention
http://www.rappasoft.com/articles/laravel-eloquent-naming-convention-guide/

Laravel 5 controller returns controller

i have a controller function that needs to be redirected to a route with a different function to avoid redundancy of codes. is it possible to put a redirect to a different function?
Here is the code:
public function index()
{
$x = Auth::user()->id;
$id = DB::table('requests')->where('id', $x)->lists('userid');
if (!is_null($id)) {
$frnd = DB::table('users')->whereIn('id', $id)->get();
if (!is_null($frnd)) {
return view('friendlist', compact('frnd'));
} else {
$frnd = null;
return view('friendlist', compact('frnd'));
}
} else {
$frnd = null;
return view('friendlist', compact('frnd'));
}
}
public function respond()
{
$frnds = new Friend;
$id = Auth::user()->id;
$friendid = Request::input('friendid');
$frnds->id = $id;
$frnds->friendid = $friendid;
if (Input::get('accept')) {
$frnds->save();
}
DB::table('requests')->where('id', $id)->where('userid', $friendid)
return // this is where i should redirect to page with function index()
}
Name the index route in routes definition like this
Route::get('home', ['uses' => 'YourController#index', 'as' => 'home']);
Then use redirect method to redirect to this route:
return redirect()->route('home');
For more info on redirects use official docs
http://laravel.com/docs/5.1/responses#redirects
I don't think is a perfect, but someone prefer this way:
private function _index()
{
$x = Auth::user()->id;
$id = DB::table('requests')->where('id', $x)->lists('userid');
if (!is_null($id)) {
$frnd = DB::table('users')->whereIn('id', $id)->get();
if (!is_null($frnd)) {
return view('friendlist', compact('frnd'));
} else {
$frnd = null;
return view('friendlist', compact('frnd'));
}
} else {
$frnd = null;
return view('friendlist', compact('frnd'));
}
}
public function index()
{
$this->_index();
}
public function respond()
{
$frnds = new Friend;
$id = Auth::user()->id;
$friendid = Request::input('friendid');
$frnds->id = $id;
$frnds->friendid = $friendid;
if (Input::get('accept')) {
$frnds->save();
}
DB::table('requests')->where('id', $id)->where('userid', $friendid)
$this->_index();
}
private function for repeated code.

custom codeigniter library not returning data

I have made a codeigniter user login library but have run into a small issue. When I login it is not returning any of the functions in the library like $this->get_user_username();
On my dashboard I should be able to do this echo $this->user->get_user_username();
I think I know problem is because the if ($this->validate_password($password)) { is around the query. And stops
me returning any data.
Note: I only would like to be able to set the user_id in session which is working. And just return the others as variables etc.
Question Because I am using if ($this->validate_password($password)) { in my login and once logged in it blocks me from retrieving any data what would be best solution so can still use it and retrieve my data
With out setting it all in sessions as I said I only want user id set
in sessions.
Dashboard Controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Dashboard extends MX_Controller {
public function __construct() {
parent::__construct();
$this->load->library('admin/user');
}
public function index()
{
echo $this->user->get_user_username();
print_r($_SESSION);
$data['top_navbar'] = Modules::run('admin/common/top_navbar/index');
$data['column_left'] = Modules::run('admin/common/column_left/index');
$data['header'] = Modules::run('admin/common/header/index');
$data['footer'] = Modules::run('admin/common/footer/index');
$this->load->view('common/dashboard_view', $data);
}
}
User Library
<?php
class User {
private $user_id;
private $username;
public function __construct() {
$this->CI =& get_instance();
}
public function login($username, $password) {
if ($this->validate_password($password)) {
$this->CI->db->where('username', $username);
$user_query = $this->CI->db->get($this->CI->db->dbprefix . 'user');
if ($user_query->num_rows() > 0) {
$row = $user_query->row();
$this->CI->session->set_userdata(array('user_id' => $row->user_id)); // Working
$this->user_id = $row->user_id;
$this->user_group_id = $row->user_group_id;
$this->username = $row->username;
$this->firstname = $row->firstname;
$this->lastname = $row->lastname;
$this->email = $row->email;
return true;
} else {
return false;
}
} else {
return false;
}
}
public function logout() {
$this->CI->session->unset_userdata('user_id');
$this->user_id = '';
$this->username = '';
}
public function get_user_id() {
return $this->user_id;
}
public function get_user_group_id() {
return $this->user_group_id;
}
public function get_user_username() {
return $this->username;
}
public function get_user_firstname() {
return $this->firstname;
}
public function get_user_lastname() {
return $this->lastname;
}
public function get_user_email() {
return $this->email;
}
public function validate_password($password) {
if (password_verify($password, $this->stored_hash())) {
return $password;
} else {
return false;
}
}
public function stored_hash() {
$this->CI->db->where('username', $this->CI->input->post('username'));
$query = $this->CI->db->get($this->CI->db->dbprefix . 'user');
if ($query->num_rows() > 0) {
$row = $query->row();
return $row->password;
} else {
return false;
}
}
}
Problem Solved I thought post my own answer, I had to add another section in the construct area of user library to make it work
And then use session userdata for where check.
public function __construct() {
$this->CI =& get_instance();
if ($this->CI->session->userdata('user_id') == TRUE) {
$this->CI->db->where('user_id', $this->CI->session->userdata('user_id'));
$user_query = $this->CI->db->get($this->CI->db->dbprefix . 'user');
if ($user_query->num_rows() > 0) {
$row = $user_query->row();
$this->user_id = $row->user_id;
$this->user_group_id = $row->user_group_id;
$this->username = $row->username;
$this->firstname = $row->firstname;
$this->lastname = $row->lastname;
$this->email = $row->email;
return true;
} else {
return false;
}
}
}
Library
<?php
class User {
private $user_id;
private $username;
public function __construct() {
$this->CI =& get_instance();
if ($this->CI->session->userdata('user_id') == TRUE) {
$this->CI->db->where('user_id', $this->CI->session->userdata('user_id'));
$user_query = $this->CI->db->get($this->CI->db->dbprefix . 'user');
if ($user_query->num_rows() > 0) {
$row = $user_query->row();
$this->user_id = $row->user_id;
$this->user_group_id = $row->user_group_id;
$this->username = $row->username;
$this->firstname = $row->firstname;
$this->lastname = $row->lastname;
$this->email = $row->email;
return true;
} else {
return false;
}
} else {
$this->logout();
}
}
public function login($username, $password) {
if ($this->validate_password($password)) {
$this->CI->db->where('username', $username);
$user_query = $this->CI->db->get($this->CI->db->dbprefix . 'user');
if ($user_query->num_rows() > 0) {
$row = $user_query->row();
$this->CI->session->set_userdata(array('user_id' => $row->user_id));
$this->user_id = $row->user_id;
$this->user_group_id = $row->user_group_id;
$this->username = $row->username;
$this->firstname = $row->firstname;
$this->lastname = $row->lastname;
$this->email = $row->email;
return true;
} else {
return false;
}
} else {
return false;
}
}
public function logout() {
$this->CI->session->unset_userdata('user_id');
$this->user_id = '';
$this->username = '';
}
public function get_user_id() {
return $this->user_id;
}
public function get_user_group_id() {
return $this->user_group_id;
}
public function get_user_username() {
return $this->username;
}
public function get_user_firstname() {
return $this->firstname;
}
public function get_user_lastname() {
return $this->lastname;
}
public function get_user_email() {
return $this->email;
}
public function validate_password($password) {
if (password_verify($password, $this->stored_hash())) {
return $password;
} else {
return false;
}
}
public function stored_hash() {
$this->CI->db->where('username', $this->CI->input->post('username'));
$query = $this->CI->db->get($this->CI->db->dbprefix . 'user');
if ($query->num_rows() > 0) {
$row = $query->row();
return $row->password;
} else {
return false;
}
}
}

Resources