I have an asset_category table(columns 'asset_category_id', 'category') and an asset table(columns 'asset_id', 'asset_category_id') and want display the (columns 'asset_id', 'asset_category_id.category,') from the asset table instead of just the 'asset_id' n 'asset_category_id' columns.
Asset_CatoriesController
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Asset_category;
class Asset_CategoriesController extends Controller
{
public function asset_category(){
$asset_categories = Asset_category::all();
return view('category', ['asset_categories' => $asset_categories]);
}
public function add(Request $request){
$this->validate($request, [
'asset_category_id' => '',
'category' => 'required'
]);
$asset_categories = new Asset_category;
$asset_categories ->asset_category_id = $request->input('asset_category_id');
$asset_categories ->category = $request->input('category');
$asset_categories ->save();
return redirect('/category') ->with('info', 'New Category Saved Successfully!');
}
public function update($id){
$asset_categories = Asset_category::find($id);
return view('update', ['asset_categories' => $asset_categories]);
}
public function edit(Request $request, $id){
$this->validate($request, [
'asset_category_id' => '',
'category' => 'required'
]);
$data = array(
'category' => $request ->input('category')
);
Asset_category::where('asset_category_id', $id)->update($data);
return redirect('/category') ->with('info', 'Category Updated Successfully!');
}
public function delete($id){
Asset_category::where('asset_category_id', $id)
->delete();
return redirect('/category') ->with('info', 'Category Deleted Successfully!');
}
}
AssetController
<?php
namespace App\Http\Controllers;
use App\Asset;
use App\Asset_category;
use App\Manufacturer;
use App\Department;
use Illuminate\Http\Request;
class AssetController extends Controller
{
public function asset(){
$assets = Asset::all();
// return view::make('viewAsset')->with('assets', $assets);
return view('viewAsset', ['assets' => $assets]);
}
public function manufacturer(){
$manufacturers = Manufacturer::all();
return view('asset', ['manufacturers' => $manufacturers]);
}
public function add(Request $request){
$this->validate($request, [
'asset_id' => '',
'asset_category_id' => 'required',
'manufacturer_id' => 'required',
'department_id' => 'required',
]);
$assets = new Asset;
$assets ->asset_id = $request->input('asset_id');
$assets ->asset_category_id = $request->input('asset_category_id');
$assets ->manufacturer_id = $request->input('manufacturer_id');
$assets ->department_id = $request->input('department_id');
$assets ->save();
return redirect('/viewAsset') ->with('info', 'New Asset Saved Successfully!');
}
public function update($id){
$assets = Asset::find($id);
return view('updateAsset', ['assets' => $assets]);
}
public function edit(Request $request, $id){
$this->validate($request, [
'asset_id' => '',
'asset_category_id' => 'required',
'manufacturer_id'=> 'required',
'department_id' => 'required'
]);
$data = array(
'asset_category_id' => $request ->input('asset_category_id'),
'manufacturer_id' => $request ->input('manufacturer_id'),
'department_id' => $request ->input('department_id')
);
Asset::where('asset_id', $id)->update($data);
return redirect('/viewAsset') ->with('info', 'Asset Updated Successfully!');
}
public function delete($id){
Asset::where('asset_id', $id)
->delete();
return redirect('/viewAsset') ->with('info', 'Asset Deleted Successfully!');
}
}
Asset.php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Asset_category;
class Asset extends Model
{
protected $primaryKey = 'asset_id';
public function category(){
return $this->belongsTo('Asset_category');
//$this->belongsTo('Asset_category');
//Asset_category::where('asset_category_id', $this->asset_category_id)->first()->category;
}
}
Asset_category.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Asset;
class Asset_category extends Model
{
protected $primaryKey = 'asset_category_id';
public function asset() {
return $this->hasMany('Asset', 'asset_category_id');
}
}
viewAsset.php
#foreach($assets->all() as $asset)
<tr>
<td>{{ $asset->asset_id}}</td>
<td>{{ $asset->category->category}}</td>
when i run the project i get a FatalErrorExeception which says
Class 'Asset_category' not found in HasRelationships.php
You have Asset_category in a namespace. Try changing this:
return $this->belongsTo('Asset_category');
to this:
return $this->belongsTo(Asset_category::class);
You must end #foreach with #endforeach
You must declare protected $table = 'table_name'; in model because in default laravel generate table name to plural form of model's class name
Try to return this:
return $this->belongsTo('Asset_category');
return $this->hasMany('Asset', 'asset_category_id');
to this:
return $this->belongsTo(Asset_category::class);
return $this->hasMany(Asset::class, 'asset_category_id');
Related
I'm in dire need of your assistance. I'm following a Laravel 8 Ecommerce tutorial and Im at the checkout stage.
After following all the steps and reconfirming the code a couple of times I get the error subject every time while the tutorial proceeds to success and its driving me nuts!! Pls someone help me understand where I'm going wrong. Thank you. Below is the code. All solutions will be appreciated.
Livewire relationship models
Order Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
use HasFactory;
protected $table = "orders";
public function user()
{
return $this->belongsTo(User::class);
}
public function orderItems()
{
return $this->hasMany(OrderItem::class);
}
public function shipping()
{
return $this->hasOne(Shipping::class);
}
public function transaction()
{
return $this->hasOne(Transaction::class);
}
}
OrderItem
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class OrderItem extends Model
{
use HasFactory;
protected $table = "order_items";
public function order()
{
return $this->belongsTo(Order::class);
}
}
Shipping Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Shipping extends Model
{
use HasFactory;
protected $table = "shippings";
public function order()
{
return $this->belongsTo(Order::class);
}
}
Transaction Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Transaction extends Model
{
use HasFactory;
protected $table = "transactions";
public function order()
{
return $this->belongsTo(Order::class);
}
}
Checkout Component
<?php
namespace App\Http\Livewire;
use Cart;
use App\Models\Order;
use Livewire\Component;
use App\Models\Shipping;
use App\Models\OrderItem;
use App\Models\Transaction;
use Illuminate\Support\Facades\Auth;
class CheckoutComponent extends Component
{
public $ship_to_different;
public $firstname;
public $lastname;
public $mobile;
public $email;
public $line1;
public $line2;
public $city;
public $address;
public $country;
public $zipcode;
public $s_firstname;
public $s_lastname;
public $s_mobile;
public $s_email;
public $s_line1;
public $s_line2;
public $s_city;
public $s_address;
public $s_country;
public $s_zipcode;
public $paymentmode;
public $thankyou;
public function updated($fields)
{
$this->validateOnly($fields, [
'firstname' => 'required',
'lastname' => 'required',
'mobile' => 'required|numeric',
'email' => 'required|email',
'line1' => 'required',
'city' => 'required',
'address' => 'required',
'country' => 'required',
'zipcode' => 'required'
]);
if ($this->ship_to_different) {
$this->validateOnly($fields, [
's_firstname' => 'required',
's_lastname' => 'required',
's_mobile' => 'required|numeric',
's_email' => 'required|email',
's_line1' => 'required',
's_city' => 'required',
's_address' => 'required',
's_country' => 'required',
's_zipcode' => 'required',
]);
}
}
public function placeOrder()
{
$this->validate([
'firstname' => 'required',
'lastname' => 'required',
'mobile' => 'required|numeric',
'email' => 'required|email',
'line1' => 'required',
'city' => 'required',
'address' => 'required',
'country' => 'required',
'zipcode' => 'required'
]);
$order = new Order();
$order->user_id = Auth::user()->id;
$order->subtotal = session()->get('checkout', ['subtotal']);
$order->discount = session()->get('checkout', ['discount']);
$order->tax = session()->get('checkout', ['tax']);
$order->total = session()->get('checkout', ['total']);
$order->firstname = $this->firstname;
$order->lastname = $this->lastname;
$order->mobile = $this->mobile;
$order->email = $this->email;
$order->line1 = $this->line1;
$order->line2 = $this->line2;
$order->city = $this->city;
$order->address = $this->address;
$order->country = $this->country;
$order->zipcode = $this->zipcode;
$order->status = 'ordered';
$order->is_shipping_different = $this->ship_to_different ? 1 : 0;
$order->save();
foreach ((Cart::instance('cart'))->content() as $item) {
$orderItem = new OrderItem();
$orderItem->product_id = $item->id;
$orderItem->order_id = $order->id;
$orderItem->price = $item->price;
$orderItem->quantity = $item->qty;
$orderItem->save();
}
if ($this->ship_to_different) {
$this->validate([
's_firstname' => 'required',
's_lastname' => 'required',
's_mobile' => 'required|numeric',
's_email' => 'required|email',
's_line1' => 'required',
's_city' => 'required',
's_address' => 'required',
's_country' => 'required',
's_zipcode' => 'required'
]);
$shipping = new Shipping();
$shipping->order_id = $order->id;
$shipping->firstname = $this->s_firstname;
$shipping->lastname = $this->s_lastname;
$shipping->mobile = $this->s_mobile;
$shipping->email = $this->email;
$shipping->line1 = $this->s_line1;
$shipping->line2 = $this->s_line2;
$shipping->city = $this->s_city;
$shipping->address = $this->s_address;
$shipping->country = $this->s_country;
$shipping->zipcode = $this->s_zipcode;
$shipping->save();
}
if ($this->paymentmode == 'cod') {
$transaction = new Transaction();
$transaction->user_id = Auth::user()->id;
$transaction->order_id = $order->id;
$transaction->mode = 'cod';
$transaction->status = 'pending';
$transaction->save();
}
$this->thankyou = 1;
Cart::instance('cart')->destroy();
session()->forget('checkout');
}
public function verifyForCheckout()
{
if (!Auth::check()) {
return redirect()->route('login');
} else if ($this->thankyou) {
return redirect()->route('thankyou');
} else if (!session()->get('checkout')) {
return redirect()->route('product.cart');
}
}
public function render()
{
$this->verifyForCheckout();
return view('livewire.checkout-component')->layout('layouts.base');
}
}
This is my Item model. I have made a function arrayPackageItemSelect that gets the id and equivalent it to the item name.
class Item extends Model
{
use HasFactory;
protected $fillable = [
'user_id',
'name',
'price',
'itemdescription',
'activeInactive'
];
public function packageitems()
{
return $this->hasMany(PackageItem::class);
}
public static function arrayPackageItemSelect()
{
$arr = [];
$items = Item::all();
foreach($items as $item){
$arr[$item->id] = $item->name;
}
return $arr;
}
}
my PackageItem Model
class PackageItem extends Model
{
protected $fillable = [
'user_id',
'item_id',
'price'
];
protected $table='packageitems';
public static function itemModel()
{
return $this->belongsTo(Item::class);
}
}
my PackageItem Controller (CREATE) and getting the Item ID from another table (Foreign key) so I can put a category for it.
public function addPackageItem(Request $request)
{
$user = Auth::user();
$item = Item::arrayPackageItemSelect();
echo $item; // when I echo this I get Array to Conversion String in POSTMAN
$fields = $request->validate([
'user_id' => 'required',
'item_id' => 'required',
'price' => 'required|numeric'
]);
// // echo $items;
$package = PackageItem::create([
'user_id' => $user->id,
'item_id' => $item,
'price'=> $fields['price']
]);
return response($package, 201);
}
What I get when I echo the Items
The results I get from POSTMAN
My Schema
This is where my reference is https://www.artofcse.com/learning/product-view-insert-update-delete
Can anybody help me what is wrong?
In your controller (addPackageItem method):
$package = PackageItem::create([
'user_id' => $user->id,
'item_id' => $fields['item_id'],
'price'=> $fields['price']
]);
Also, i think there is an error in your PackageItem model. belongsTo should not be called in a static method :
public function itemModel()
{
return $this->belongsTo(Item::class);
}
I am sending two different emails. One from VerifyMail and other from ForgetEmail but laravel throws error that VerifyMail does not exits. It was working just fine when i had not added the ForgetMail class.
This is my code where i am using VerifyMail
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use App\User;
use App\VerifyUser;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Carbon;
use App\Mail\VerifyMail;
class UserRegisterController extends Controller
{
public function __construct()
{
$this->middleware('guest:user');
}
public function showRegisterForm() {
return view('user.registerForm');
}
public function register(Request $request) {
$userValidated = $this->validate($request, [
'name' => 'required|string',
'email' => 'required|string|unique:users',
'password' => 'required|string|min:6|confirmed'
]);
$register = [
'name' => $userValidated['name'],
'email' => $userValidated['email'],
'password' => Hash::make($userValidated['password']),
];
$user =User::create($register);
VerifyUser::create([
'token' => str::random(60),
'user_id' => $user->id,
]);
Mail::to($user->email)->send(new VerifyMail($user));
return redirect('user/login')->with('email', 'An email was sent to you for verification');
}
public function verifyEmail($token, $date) {
$dates = date(strtotime($date));
if(time() - $dates > 60 * 60) {
return redirect('/user/login')->with('failed' , 'Oops! Something went wrong');
}
$verifiedUser = VerifyUser::where('token', $token)->first();
if(isset($verifiedUser)) {
$user = $verifiedUser->user;
if($user->email_verified_at == '') {
$user->email_verified_at = carbon::now();
$user->save();
return redirect('/user/login')->with('success', 'Your email was successfully verified');
} else {
return redirect('/user/login')->with('failed' , 'Oops! Something went wrong');
}
}
}
}
This is the code where i am using ForgetEmail
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
// use Symfony\Component\HttpFoundation\Session\Session;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Session;
use App\ForgetPassword;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Mail;
use App\Mail\ForgetEmail;
use App\User;
use Illuminate\Support\Facades\Hash;
class UserLoginController extends Controller
{
protected $guard;
use AuthenticatesUsers;
public function __construct()
{
$this->middleware('guest:user')->except('logout');
$this->guard = Auth::guard('user');
}
public function showLoginForm()
{
return view('user.login');
}
public function forgetPasswordForm() {
return view('user.forget');
}
public function passwordResetForm($id) {
$user = User::where('id', $id)->first();
return view('user.resetForm', ['id' => $id]);
}
public function userLogin(Request $request) {
$validated = $this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6',
]);
if(Auth::guard('user')->attempt(['email' => $validated['email'], 'password' => $validated['password']], $request->remember)) {
$user = Auth::guard('user')->user();
if($user->email_verified_at != null) {
return redirect()->route('user.dashboard');
} else {
$this->logout($msg = 1);
}
}
return redirect()->back();
}
public function forgetPassword(Request $request) {
$email = $this->validate($request, [
'email' => 'required|email|exists:users',
]);
$forgetPass = User::where('email', $email['email'])->first();
$forgetArray = array(
'user_id' => $forgetPass->id,
'token' => str::random(60),
);
$forgetPassword = ForgetPassword::create($forgetArray);
Mail::to($email['email'])->send(new ForgetEmail($forgetPassword->user));
return redirect('user/forgetPassword')->with('email', 'We have sent you an email to reset your password');
}
public function passwordReset($token, $date) {
$checkTime = strtotime($date);
if(time() - $checkTime > 20 * 60) {
return redirect('user/login/')->with('passes', 'Looks like the link has expired');
}
$passReset = ForgetPassword::where('token', $token)->first();
if(isset($passReset)) {
$user = $passReset->user;
if($user->password) {
return redirect('/user/passwordReset'. '/'. $user->id);
}
}
}
public function passwordUpdate(Request $request, $id) {
$validatePass = $this->validate($request, [
'password' => 'required|string|min:6|confirmed',
]);
$pass = User::where('id', $id)->first();
$pass->password = Hash::make($validatePass['password']);
$pass->save();
return redirect('/user/login')->with('reset', 'Your password has been reset');
}
public function logout($msg = 0) {
$cookieName = $this->guard->getRecallerName();
$cookie = Cookie::forget($cookieName);
Auth::logout();
Session::flush();
if($msg == 0) {
return redirect()->route('user.login')->withCookie($cookie);
} else {
return redirect()->route('user.login')->withCookie($cookie)->with('verify', 'Your email is not verified');
}
}
}
All of my code was working fine before when i had not added that ForgetEmail class in Mail. I don't know what's the problem here. Will be glad if you can find it for me.
I am fetching products along with its relationship. I have done this:
$data = $this->products->with('images')->with('colors')->where('slug', $slug)->first();
And in the Product model, I have written:
public function images(){
return $this->hasMany('App\Models\ProductImages', 'product_id');
}
public function colors(){
return $this->hasMany('App\Models\ProductSizes', 'color_id');
}
I am storing color_id in the product_sizes table so now when I do dd($data). It gives me 5 data inside the object where the size_id are different but the color_id are same. Is it possible to group the data coming in colors relationship?
I tried using array_unique in the blade but that did not gave me to use the following function:
public function colorInfo(){
return $this->belongsTo('App\Models\Color', 'color_id');
}
I want to group the color_id coming in the colors relationship to display available colors of the product.
Code as per request:
Product Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $fillable = ['name','slug','sku','category_id','brand_id','video','status', 'specification', 'description','warranty', 'vendor_id'];
public function getRules(){
$rules = [
'name' => 'bail|required|string|unique:products,name',
'slug' => 'bail|required|string|unique:products,slug',
'sku' => 'bail|required|string|unique:products,sku',
'specification' => 'bail|required|string',
'description' => 'bail|required|string',
'category_id' => 'required|exists:product_categories,id',
'brand_id' => 'nullable|exists:brands,id',
'vendor_id' => 'nullable|exists:vendors,id',
'video' => 'nullable|string',
'warranty' => 'nullable|string',
'status' => 'nullable|in:active,inactive',
];
if($rules != 'add'){
$rules['name'] = "required|string";
$rules['slug'] = "required|string";
$rules['sku'] = "required|string";
}
return $rules;
}
public function category(){
return $this->belongsTo('App\Models\ProductCategory');
}
public function brand(){
return $this->belongsTo('App\Models\Brand');
}
public function VendorName(){
return $this->belongsTo('App\Models\Vendor', 'vendor_id');
}
public function images(){
return $this->hasMany('App\Models\ProductImages', 'product_id');
}
public function sizes(){
return $this->hasMany('App\Models\ProductSize', 'product_id');
}
public function colors(){
return $this->hasMany('App\Models\ProductSize', 'product_id');
}
public function finalCategory(){
return $this->belongsTo('App\Models\SecondaryCategory', 'category_id');
}
}
PRoduct Sizes Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class ProductSize extends Model
{
protected $fillable = ['product_id','size_id', 'selling_price', 'purchase_price', 'discount','stock', 'color_id', 'quantity','total_price'];
public function getRules(){
$rules = [
'product_id' => 'required|exists:products,id',
'size_id' => 'required|exists:sizes,id',
'color_id' => 'required|exists:colors,id',
'selling_price' => 'required|string',
'purchase_price' => 'required|string',
'quantity' => 'required|string',
'total_price' => 'required|string',
'discount' => 'nullable|string',
'stock' => 'required|string',
];
return $rules;
}
public function colorInfo(){
return $this->belongsTo('App\Models\Color', 'color_id');
}
}
Get the product first.
$data = $this->products->with(['images', 'colors'])->where('slug', $slug)->first();
To get the distinct colors for that product.
$unique_product_colors = $data->colors->unique('color_id');
unique('color_id') method can be applied on a collection instance to get a new collection in which all the items will have unique color_id
Try This
$data = $this->products->with('images')->with('colors')->where('slug', $slug)->groupBy('product_sizes.color_id')->first();
I have a small forum, im trying to create topic and replies for the store method.
routes.php
Route::get('board/{id}/create', 'TopicsController#create');
Route::post('board/{id}/create', 'TopicsController#store');
TopicsController.php
public function store()
{
$this->request->user()->topics()->create([
'board_id' => $this->request->id,
'title' => $this->request->title,
'body' => $this->request->body
]);
return redirect(url('/board/' . $this->request->id));
}
I am receiving this error.
Call to a member function topics() on null
Also note, i am using Sentinel https://github.com/rydurham/Sentinel from this repo.
<?php namespace App\Models;
class User extends \Sentinel\Models\User
{
protected $fillable = ['email', 'first_name', 'last_name'];
protected $hidden = ['password'];
public function topics()
{
return $this->hasMany(Topic::class);
}
public function replies()
{
return $this->hasMany(Reply::class);
}
public function getGravatarAttribute()
{
$hash = md5(strtolower(trim($this->attributes['email'])));
return "https://www.gravatar.com/avatar/$hash";
}
}
Updated Model
public function store($id)
{
$user = Sentry::getUser($id);
$user->topics()->create([
'board_id' => $this->request->id,
'title' => $this->request->title,
'body' => $this->request->body
]);
return redirect(url('/board/' . $this->request->id));
}
It seems that your user object is null. Properly retrieve the user using the id
public function store($id)
{
$user = \App\Models\User::find(\Sentinel::getUser()->id);
$user->topics()->create([
'board_id' => $this->request->id,
'title' => $this->request->title,
'body' => $this->request->body
]);
return redirect(url('/board/' . $this->request->id));
}