form ajax return nothing - ajax

I try to understand where I made a mistake in my code , it works when I submit without ajax
When I am submitting my form with some empty fields my controller should return me some errors but it is returning nothing
Here is my js
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
});
var form = $('#register-lobby');
form.submit(function(e){
console.log('click');
e.preventDefault();
$.ajax( {
type: "POST",
dataType: 'JSON',
url: form.attr('action'),
data: form.serialize(),
success: function( response ) {
console.log(response);
}
});
});
My controller
<?php
namespace App\Http\Controllers;
use App\Game;
use App\Repository\LobbyRepository;
use Illuminate\Auth\AuthManager;
use Illuminate\Http\Request;
class LobbyController extends Controller
{
//
private $r;
/**
* #var AuthManager
*/
private $auth;
public function __construct(LobbyRepository $r , AuthManager $auth)
{
$this->middleware('auth');
$this->r = $r;
$this->auth = $auth;
}
public function index()
{
$games = Game::orderBy('name', 'asc')->get();
return view('/lobby')->with('games', $games);
}
public function store(Request $request){
$input = $request->all();
$decription = $input['description'];
$nb_player = $input['nb-players'];
$link = $input['support-link'];
$game_id = $input['game-id'];
//return response()->json(['errors'=>'my errors']);
$this->r->createLobby($decription , $nb_player , $link , $game_id ,$this->auth->user()->id);
}
}
Which is weird is if I return an json response in my store method it works but if I do it in my Repository in createLobby I have no response and it should return a message
<?php
namespace App\Repository;
use App\Lobby;
use Carbon\Carbon;
use GuzzleHttp\Psr7\Request;
use Illuminate\Support\Facades\Validator;
class LobbyRepository {
private $lobby;
public function __construct(Lobby $lobby){
$this->lobby = $lobby;
}
private function validator(array $data){
$rules = [
'description' => 'required|max:50',
'link' => 'required|max:255',
];
$messages = [
'required' => 'Le champ :attribute est requis',
'description.max' => 'La description est limitée à 50 caractères',
'link.max' => 'Le lien est limité à 255 caractères',
];
$validator = Validator::make($data,$rules , $messages);
return $validator;
}
public function createLobby($description , $nb_player ,$link , $game_id , $user_id){
$validator = $this->validator(['description' => $description , 'link' => $link]);
if($validator->fails()){
return response()->json(['errors'=>'my errors']);
/*
dd($validator->errors());
return redirect()->back()->withErrors($validator);
*/
}
else{
return $this->lobby->newQuery()->create([
'description' => $description,
'support_link' => $link,
'nb_player' => $nb_player,
'game_id' => $game_id,
'created_at' => Carbon::now(),
'user_id' => $user_id
]);
}
}
}

Thanks to Kelvin I missed the the return in my controller
public function store(Request $request){
$input = $request->all();
$decription = $input['description'];
$nb_player = $input['nb-players'];
$link = $input['support-link'];
$game_id = $input['game-id'];
//return response()->json(['errors'=>'my errors']);
return $this->r->createLobby($decription , $nb_player , $link , $game_id ,$this->auth->user()->id);
}

Related

How to use livewire pagination with public properties?

I'm facing a weird problem that only accurs when I use pagination with livewire components,
this is the error:
BadMethodCallException
Method Illuminate\Support\Collection::items does not exist.
I know what this errors means, the problem is why it only accurs when I change page in pagination:
this is my Component:
<?php
namespace App\Http\Livewire\Admin;
use Livewire\Component;
use Livewire\WithPagination;
use Livewire\WithFileUploads;
use App\Models\Product;
use App\Models\Category;
use File;
use GlobalsHelper;
class Products extends Component
{
use WithPagination, WithFileUploads;
public $products;
public $subcategories;
// Form
public $name;
public $description;
public $price;
public $quantity;
public $category_id = null;
public $sub_category_id = null;
public $image;
public $selected = [];
public $query = '';
public $filter_by_category = '';
protected $paginationTheme = 'bootstrap';
public function render()
{
$pagination = $this->products;
$this->products = collect($this->products->items());
return view('livewire.admin.products', [
'categories' => Category::all(),
'subcategories' => $this->subcategories,
'products' => $this->products,
'pagination' => $pagination
]);
}
// public function render()
// {
// return view('livewire.admin.products', [
// 'categories' => Category::all(),
// 'subcategories' => $this->subcategories,
// 'products' => $this->products,
// ]);
// }
public function mount()
{
$this->getSubcategories();
$this->index();
}
public function getSubcategories()
{
$this->subcategories = [];
if ( !$this->category_id )
{
$this->category_id = (Category::first()) ? Category::first()->id : null;
}
$category = Category::find($this->category_id);
if ( !$category )
{
return null;
}
$this->subcategories = $category->children;
$this->sub_category_id = ($this->subcategories->first()) ? $this->subcategories->first()->id : null;
}
public function store()
{
$fields = $this->validate([
'name' => ['required', 'string', 'min:5', 'max:250'],
'description' => ['string', 'max:250'],
'price' => ['required', 'numeric', 'min:1'],
'quantity' => ['required', 'numeric', 'min:1'],
'category_id' => ['nullable'],
'sub_category_id' => ['nullable'],
]);
$fields['user_id'] = GlobalsHelper::auth()->id;
$product = Product::create($fields);
if ( !$product )
{
session()->flash('error', __('messages.error_create'));
return;
}
// upload image
$this->storeImage($product);
$this->resetFields();
session()->flash('success', __('messages.success_create'));
}
public function search()
{
$results = Product::where('name', 'LIKE', '%'.$this->query.'%')
->orderBy('id', 'desc')->paginate(5);
$this->products = $results;
}
public function index()
{
$this->products = Product::orderBy('id', 'desc')->paginate(5);
}
public function filterByCategory()
{
$results = Product::where('category_id', '=', $this->filter_by_category)
->orderBy('id', 'desc')->paginate(5);
$this->products = $results;
}
// private
private function resetFields()
{
$this->name = null;
$this->description = null;
$this->price = 0;
$this->quantity = 1;
$this->image = null;
$this->filename = '...';
}
private function storeImage($product)
{
$this->validate([
'image' => ['nullable', 'image', 'max:1024'],
]);
if ( $this->image )
{
// Delete old image if exists
if ( $product->image )
{
File::delete([$product->image->fullpath]);
}
$filename = sha1( uniqid('', true) );
$ext = $this->image->getClientOriginalExtension();
$fullpath = $this->image->store(GlobalsHelper::PRODUCTS_UPLOADS_DIR.'/'.$product->id, 'public');
$product->update([
'image' => [
'name' => basename($fullpath),
'type' => $ext,
'fullpath' => GlobalsHelper::STORAGE_DIR.$fullpath,
'url' => asset(GlobalsHelper::STORAGE_DIR.$fullpath)
]
]);
}
}
}
The idea is that I want to achieve search, store, update, delete, filter operations in same compoenent like in laravel controller, I found solutions online, but only 50% of what I need to achieve.
I have been wasting a lot of time trying to figure this out.
If any one would help me, I will be much appreciated.
At first glance without seeing the view, you are getting the $produts via the mount() method, this will only run ONCE when the livewire component is first rendered. From the docs:
mount() is only ever called when the component is first mounted and will not be called again even when the component is refreshed or rerendered.

Pass dynamic value to Laravel max validation rule

I am working on a sales laravelcollective form whereby the sale_quantity entered should not be more than the stock_quantity in DB. When I use the idea at: Laravel validate dynamically added input with custom messages there is one answer with:
'orderQty.*' => 'required|numeric|min:1|max:'.$product['productQty']
I have done this as you will see in my function store and function update in the SalesController.php, no error occurs but the form refuses to submit and shows this as a flash message:
The sale quantity may not be greater than '.$stocks['stock_quantity'].
It does not mean what it shows because their is a greater stock_quantity in the database.
SalesController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use App\Sale;
use App\Stock;
class SalesController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
function __construct()
{
$this->middleware('permission:sales-list');
$this->middleware('permission:sales-create', ['only' => ['create', 'store']]);
$this->middleware('permission:sales-edit', ['only' => ['edit', 'update']]);
$this->middleware('permission:sales-delete', ['only' => ['destroy']]);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$sales = Sale::orderBy('updated_at', 'desc')->get();
return view('sales.index')->with('sales', $sales);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$stocks = Stock::all();
//dd($stocks);
return view('sales.create', compact('stocks'));
//$sales = Sale::pluck('stock_id')->prepend('stock_id');
//$sales = DB::table('stocks')->select('stock_id')->get();
//return view('sales.create')->with('sales',$sales);
}
public function getUnitSellingPrice(Request $request, $stock_name)
{
$stock = Stock::where('stock_name', $stock_name)->first();
if ($stock == null) {
return null;
}
return response()->json($stock->unit_selling_price);
}
public function store(Request $request)
{
$this->validate($request, [
'stock_name' => 'required',
'sale_quantity' => 'required|numeric|min:1|max:\'.$stock[\'stock_quantity\']',
'unit_selling_price' => 'required',
'total_sales_cost' => 'required'
]);
//create stock
$sale = new Sale;
$sale->stock_name = $request->input('stock_name');
$sale->sale_quantity = $request->input('sale_quantity');
$sale->unit_selling_price = $request->input('unit_selling_price');
$sale->total_sales_cost = $request->input('total_sales_cost');
$sale->save();
DB::table('stocks')->where('stock_name', $request->input('stock_name'))->decrement('stock_quantity', $request->input('sale_quantity'));
return redirect('/sales')->with('success', 'Sale Saved');
}
public function show($sales_id)
{
$sale = Sale::find($sales_id);
return view('sales.show')->with('sale', $sale);
}
/**
* Show the form for editing the specified resource.
*
* #param int $sales_id
* #return \Illuminate\Http\Response
*/
public function edit($sales_id)
{
$sale = Sale::findOrFail($sales_id);
$stocks = Stock::latest('stock_name', 'unit_selling_price')->get();
return view('sales.edit', compact('sale', 'stocks'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $sales_id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $sales_id)
{
$this->validate($request, [
'stock_name' => 'required',
'sale_quantity' => 'required|numeric|min:1|max:\'.$stock[\'stock_quantity\']',
'unit_selling_price' => 'required',
'total_sales_cost' => 'required'
]);
//create stock
$sale = Sale::find($sales_id);
$sale->stock_name = $request->input('stock_name');
$sale->sale_quantity = $request->input('sale_quantity');
$sale->unit_selling_price = $request->input('unit_selling_price');
$sale->total_sales_cost = $request->input('total_sales_cost');
$sale->save();
return redirect('/sales')->with('success', 'Sale Updated');
}
/**
* Remove the specified resource from storage.
*
* #param int $sales_id
* #return \Illuminate\Http\Response
*/
public function destroy($sales_id)
{
$sale = Sale::find($sales_id);
$sale->delete();
return redirect('/sales')->with('success', 'Sale Removed');
}
}
create.blade.php
#extends('layouts.app')
#section('content')
<br>
<h1>Add Sale</h1>
{!! Form::open(['action' => 'SalesController#store', 'method' => 'POST', 'enctype' => 'multipart/form-data']) !!}
<div class="form-group">
<label>Product Name</label>
<select name="stock_name" id="stock_name" class="form-control">
#foreach ($stocks as $stock)
<option value="{{ $stock->stock_name }}">{{ $stock->stock_name}}</option>
#endforeach
</select>
</div>
<div class="form-group">
{{Form::label('sale_quantity', 'Quantity')}}
{{Form::text('sale_quantity', '', ['class' => 'form-control', 'placeholder' => 'Quantity', 'id' => 'sales_quantity'])}}
</div>
<div class="form-group">
{{Form::label('unit_selling_price', 'Unit Selling Price')}}
{{Form::text('unit_selling_price', '', ['class' => 'form-control', 'placeholder' => 'Unit Selling Price', 'id' => 'unit_selling_price'])}}
</div>
<div class="form-group">
{{Form::label('total_sales_cost', 'Total Sales Cost')}}
{{Form::text('total_sales_cost', '', ['class' => 'form-control', 'placeholder' => 'Total Sales Cost', 'id' => 'total_sales_cost', 'readonly' => 'true', 'cursor: pointer' => 'true' ])}}
</div>
{{Form::submit('Submit', ['class' => 'btn btn-primary'])}}
{!! Form::close() !!}
<script>
$(document).ready(function () {
$("#stock_name").on('change', function () {
var stock_name = $(this).val();
$.ajax({
url: '/sales-price/getunitsellingprice/'+stock_name,
method: 'GET',
success: function (response) {
console.log(response);
$("#unit_selling_price").val(response);
},
});
});
});
</script>
<script>
$(document).ready(function () {
$("#total_sales_cost").click(function () {
var sales_quantity = $("#sales_quantity").val();
var unit_selling_price = $("#unit_selling_price").val();
var total_sales_cost = (sales_quantity * unit_selling_price);
$('#total_sales_cost').val(total_sales_cost);
});
});
</script>
#endsection
SalesController.php changes at function store and update.
Those are the only changes, the blade was Okay.
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use App\Sale;
use DB;
use App\Stock;
class SalesController extends Controller
{
function __construct()
{
$this->middleware('permission:sales-list');
$this->middleware('permission:sales-create', ['only' => ['create', 'store']]);
$this->middleware('permission:sales-edit', ['only' => ['edit', 'update']]);
$this->middleware('permission:sales-delete', ['only' => ['destroy']]);
}
public function index()
{
$sales = Sale::orderBy('updated_at', 'desc')->get();
return view('sales.index')->with('sales', $sales);
}
public function create()
{
$stocks = Stock::all();
//dd($stocks);
return view('sales.create', compact('stocks'));
//$sales = Sale::pluck('stock_id')->prepend('stock_id');
//$sales = DB::table('stocks')->select('stock_id')->get();
//return view('sales.create')->with('sales',$sales);
}
public function getUnitSellingPrice(Request $request, $stock_name)
{
$stock = Stock::where('stock_name', $stock_name)->first();
if ($stock == null) {
return null;
}
return response()->json($stock->unit_selling_price);
}
public function getStockUnitCost(Request $request, $stock_name)
{
$stock = Stock::where('stock_name', $stock_name)->first();
if ($stock == null) {
return null;
}
return response()->json($stock->stock_unit_cost);
}
public function salesWebReport(){
$sales = Sale::orderBy('updated_at', 'desc')->get();
return view('sales.saleswebreport')->with('sales', $sales);
}
public function photocopying(){
$stocks = Stock::all();
//dd($stocks);
return view('sales.photocopy', compact('stocks'));
}
public function store(Request $request)
{
//get retrieves an array
//$stock = \App\Stock::where('stock_name', $request->input('stock_name'))->get();
//first retrieves an array BUT removes everything and produces only the required field value
$stock = Stock::where('stock_name', $request->input('stock_name'))->firstOrFail();
$qty = $stock->stock_quantity;
$this->validate($request, [
'stock_name' => 'required',
'sale_quantity' => 'required|numeric|min:1|max:'.$qty,
'unit_selling_price' => 'required',
'total_sales_cost' => 'required',
'stock_profit' => 'required'
]);
//create stock
$sale = new Sale;
$sale->stock_name = $request->input('stock_name');
$sale->sale_quantity = $request->input('sale_quantity');
$sale->unit_selling_price = $request->input('unit_selling_price');
$sale->total_sales_cost = $request->input('total_sales_cost');
$sale->stock_profit = $request->input('stock_profit');
$sale->save();
DB::table('stocks')->where('stock_name', $request->input('stock_name'))->decrement('stock_quantity', $request->input('sale_quantity'));
return redirect('/sales')->with('success', 'Sale Saved');
}
public function show($sales_id)
{
$sale = Sale::find($sales_id);
return view('sales.show')->with('sale', $sale);
}
public function edit($sales_id)
{
$sale = Sale::findOrFail($sales_id);
$stocks = Stock::latest('stock_name', 'unit_selling_price')->get();
return view('sales.edit', compact('sale', 'stocks'));
}
public function update(Request $request, $sales_id)
{
//get retrieves an array
//$stock = \App\Stock::where('stock_name', $request->input('stock_name'))->get();
//first retrieves an array BUT removes everything and produces only the required field value
$stock = Stock::where('stock_name', $request->input('stock_name'))->firstOrFail();
$qty = $stock->stock_quantity;
$this->validate($request, [
'stock_name' => 'required',
'sale_quantity' => 'required|numeric|min:1|max:'.$qty,
'unit_selling_price' => 'required',
'total_sales_cost' => 'required',
'stock_profit' => 'required'
]);
//create stock
$sale = Sale::find($sales_id);
$sale->stock_name = $request->input('stock_name');
$sale->sale_quantity = $request->input('sale_quantity');
$sale->unit_selling_price = $request->input('unit_selling_price');
$sale->total_sales_cost = $request->input('total_sales_cost');
$sale->stock_profit = $request->input('stock_profit');
$sale->save();
return redirect('/sales')->with('success', 'Sale Updated');
}
public function destroy($sales_id)
{
$sale = Sale::find($sales_id);
$sale->delete();
return redirect('/sales')->with('success', 'Sale Removed');
}
}
According to the error shown, it may be that it is taking your variable and array data as a literal string in this line:
'sale_quantity' => 'required|numeric|min:1|max:\'.$stock[\'stock_quantity\']',
Give a try with php double quotes:
'sale_quantity' => "required|numeric|min:1|max:$stock['stock_quantity']",
Or, to make it even easier for the interpreter, assign a simple variable before the validation step:
$qty = $stock['stock_quantity'];
and then in the validator:
'sale_quantity' => "required|numeric|min:1|max:$qty",
You may wish to consider using some type of validation on the client side to make this even stronger as well as to help users. Perhaps pass that $qty value from your edit/create methods on your controller to the blade page, and then use something like JQuery Validation to check on the form before the user even submits it to the server.
So - to solve it, something like this:
public function store(Request $request)
{
$stock = \App\Stock::find($someIdOfYourChoiceOrFromTheForm)
$qty = $stock->stock_quantity;
$this->validate($request, [
'stock_name' => 'required',
'sale_quantity' => "required|numeric|min:1|max:$qty",
'unit_selling_price' => 'required',
'total_sales_cost' => 'required'
]);

Laravel - Call to undefined method App\\User::getAvatarUrlAttribute()

I am using Laravel-5.8 as backend for an application. I have written all the Api for the endpoints.
Laravel: ApiController
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use App\User;
use App\Activity;
use Avatar;
use Storage;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Mail;
use Audit;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
class ApiController extends Controller
{
public $successStatus = 200;
public function __construct() {
}
protected function guard()
{
return Auth::guard();
}
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60,
'user' => auth()->user()->email
], 200);
}
public function returnResponse($success, $data, $errorCode = 0, $message = false) {
$response = array();
$response['success'] = $success;
$response['message'] = isset($message) ? $message : '';
if ($errorCode) {
$response['errorCode'] = isset($errorCode) ? $errorCode : 0;
}
$response['data'] = $data;
return response()->json($response, 200);
}
public function register(Request $request) {
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|string|email|max:255|unique:users',
// 'phone' => 'required',
// 'password' => 'required',
'password' => 'required|string|min:6',
// 'password' => 'required|string|min:6|confirmed',
'password_confirmation' => 'required|same:password',
]);
if ($validator->fails()) {
return $this->returnResponse(false, ['error' => $validator->errors()], 1, 'Invalid User Data');
}
$input = $request->all();
// code for check email / username / phone exist or not
if(isset($input['email'])){
$alreadyExist = User::where(function ($query) use ($input) {
$query->where('email', '=', $input['email']);
})->get();
}
if (count($alreadyExist->toArray()) > 0) {
return $this->returnResponse(false, ['error' => 'Email Already Exist'], 1, 'User Data Already Exist');
}
// code for register user
$user = new User();
$user->name = $input['name'];
$user->email = $input['email'];
$user->password = bcrypt($input['password']);
$user->save();
$mainData = array();
$mainData['to'] = $user->toArray()[0]['email'];
$mainData['from'] = "support#tsllimited.com";
$mainData['subject'] = "Successful Signup";
$mainData['content'] = "Your signup was successful, you can login with the credentials.";
$this->mailSend($mainData);
Activity::create([
'user_id' => $user->id,
'owner_id' => $user->client_id,
'type' => "User Registration",
'title' => "Successful Signup of User",
'state' => 2,
'created_at'=> date('Y-m-d H:i:s')
]);
$success = array();
$success['user_id'] = $user->id;
$success['user']=$user;
return $this->returnResponse(true, $success, 0, 'User registered successfully');
}
public function login(Request $request) {
$authenticated = false;
$validator = Validator::make($request->all(), [
'email' => 'required|string|email',
'password' => 'required|string',
'remember' => 'boolean'
]);
if ($validator->fails()) {
return $this->returnResponse(false, ['error' => $validator->errors()], 1, 'Invalid User Data');
}
$remember = request('remember') ? true : false;
if (Auth::guard('web')->attempt(['email' => request('email'), 'password' => request('password')], $remember)) {
$authenticated = true;
}
if ($authenticated == true) {
$user = Auth::guard('web')->user();
$date = date('Y-m-d');
$success['userId'] = $user->id;
$success['avatar'] = url('/storage/user') . '/' . $user->avatar;
$success['email'] = $user->email;
$success['token'] = $user->createToken('MyApp')->accessToken;
return $this->returnResponse(true, $success);
} else {
$success = array();
return $this->returnResponse(false, $success, 1, 'Invalid User Credential');
}
}
}
api.php
Route::group([
], function () {
Route::post('login', 'ApiController#login');
Route::post('register', 'ApiController#register');
Route::post('forgetPassword', 'ApiController#forgetPassword');
Route::group([
'middleware' => 'auth:api'
], function() {
Route::get('logout', 'AuthController#logout');
Route::get('user', 'AuthController#user');
});
});
I stalled and configured Laravel Passport and also Spatie. I have checked the code and don't know what the error really is. When I test the resgister Post Request on the POSTMAN, I got the error shown below:
See the POSTMAN preview side:
What could have caused the error and how do I resolve it?
You do not have the column avatar on your users table.
Maybe you did not use the trait you need in your User class
class User extends Authenticatable {
use HasAvatar;
// ...
}
I eventually solved the problem myself. The issue is that, I forgot to add:
public function getAvatarUrlAttribute()
{
return Storage::url('avatars/'.$this->id.'/'.$this->avatar);
}
to User Model.
Thanks

Laravel Eloquent Relationship: HasRelationships.php FatalErrorExexeption

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');

Laravel controller with multiple beforeFilter's

I need to filter different authorization roles for different HTTP verbs. Attaching one filter in the controller is no problem, as the example shows:
public function __construct()
{
$this->beforeFilter('roleOne', ['on' => ['get', 'post', 'put', 'delete']]);
}
However, attaching multiple filters, as the next example shows, hides all the routes from the caller.
public function __construct()
{
$this->beforeFilter('roleOne', ['on' => ['get', 'post', 'put', 'delete']]);
$this->beforeFilter('roleTwo', ['on' => ['get']]);
}
And combining the filters lets all traffic through.
public function __construct()
{
$this->beforeFilter('roleOne|roleTwo', ['on' => ['get', 'post', 'put', 'delete']]);
}
Both fails.
I've considered using user levels instead of role names, or attaching level values to the user roles. But the best scenario for me would be to avoid having to change the structure.
Edit, here's the general structure for my filters.
Route::filter('roleOne', function ($route, $request){
$token = $request->header('X-Auth-Token');
// If the token doesn't exist the user isn't authenticated
if ($token === null) {
$data = ['Not authenticated'];
$code = 401;
$response = Response::json([
'error' => true,
'data' => $data,
'code' => $code
], $code
);
return $response;
}
// If the token is invalid the user isn't authenticated
else if ( ! isAuthenticated($token) ) {
$data = ['Not authenticated'];
$code = 401;
$response = Response::json([
'error' => true,
'data' => $data,
'code' => $code
], $code
);
return $response;
}
// If the user is not a member of group s/he doesn't have access
if( ! isAuthorized($token, 'roleOne') ){
$data = ['Not authorized'];
$code = 401;
$response = Response::json([
'error' => true,
'data' => $data,
'code' => $code
], $code
);
return $response;
}
});
I ended up introducing a level parameter in the authorized groups. Then I only needed one single beforeFilter.
public function __construct()
{
$this->beforeFilter('userRole', ['on' => ['get', 'post', 'put', 'delete']]);
}
And the filter now lookes something like...
Route::filter('userRole', function ($route, $request){
$token = $request->header('X-Auth-Token');
// If the token doesn't exist the user isn't authenticated
if ($token === null) {
$data = ['Not authenticated'];
$code = 401;
$response = Response::json([
'error' => true,
'data' => $data,
'code' => $code
], $code
);
return $response;
}
// If the token is invalid the user isn't authenticated
else if ( ! isAuthenticated($token) ) {
$data = ['Not authenticated'];
$code = 401;
$response = Response::json([
'error' => true,
'data' => $data,
'code' => $code
], $code
);
return $response;
}
// If the user is not a member of group Admin s/he doesn't have access
if( ! isAuthorized($token, 'Admin') ){
$data = ['Not authorized'];
$code = 401;
$response = Response::json([
'error' => true,
'data' => $data,
'code' => $code
], $code
);
return $response;
}
});
And the isAuthorized method looks something like this.
public function isAuthorized($token, $group) {
$hasPermission = false;
$user = false;
$requiredGroup = false;
// Attempting to find the user will automatically throw errors if unsuccessful
try {
if( $group !== '*' ){
// Get the needed group
$requiredGroup = $this->groupProvider->findByName($group);
}
// Get the user, including the memberships
$user = $this->userProvider->findByToken($token);
} catch (InvalidTokenException $e) {
$hasPermission = false;
}
// If the group is '*' it means everyone has permission, but has to be authenticated!
// That's why we do this check after the token-check
if ( $group === '*' ) {
return true;
}
if( !$user || !$requiredGroup ) {
$hasPermission = false;
} else {
// Compare user permissions to required
foreach ($user['groups'] as $group) {
if( $group['level'] >= $requiredGroup['level'] ){
$hasPermission = true;
}
}
}
return $hasPermission;
}

Resources