Working on my friend's code, it seems all features like Post, Tag, Category, etc are working fine. I want to add a feature to upload a pdf and download it from front end. After adding DownloadController and Downloads model, It shows varies errors. Most irritating error is
Trying to get property 'unreadNotifications' of non-object(View: /var/www/html/tes/resources/views/admin/layouts/header.blade.php)
Routes:
//Admin Routes
Route::group(['namespace'=>'Admin'], function (){
Route::get('admin/home','HomeController#index')->name('admin.index');
//Users Routes
Route::resource('admin/user','UserController');
//Roles Routes
Route::resource('admin/role','RoleController');
//permissions Routes
Route::resource('admin/permission','PermissionController');
//Download Manager Routes - CV
Route::resource('admin/cv','Downloadcontroller');
//Post Routes
Route::DELETE('postDeleteSelected','PostController#deleteSelected')->name('deleteSelected');
Route::get('admin/post/remove/{post}','PostController#remove')->name('posts.remove');
Route::get('admin/post/trash','PostController#trashed')->name('posts.trashed');
Route::get('admin/post/recover/{id}','PostController#recover')->name('posts.recover');
Route::get('markAsRead','PostController#markRead')->name('markRead');
Route::resource('admin/post','PostController');
//Tag Routes
Route::resource('admin/tag','TagController');
//Category Routes
Route::resource('admin/category','CategoryController');
//Admin Auth Routes
Route::get('admin-login','Auth\LoginController#showLoginForm')->name('admin.login');
Route::post('admin-login','Auth\LoginController#login');
});
Controller:
namespace App\Http\Controllers\Admin;
use App\Model\admin\admin;
use App\Model\user\Downloads;
use App\Http\Controllers\Controller;
use App\Notifications\TaskCompleted;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Notification;
class Downloadcontroller extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function index()
{
return view('admin.cv.show');
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$data = new Downloads;
if ($request->file('file')){
$file = $request->file('file');
$filename = time().'.'.$file->getClientOriginalExtension();
$request->file->move('storage/'.$filename);
$data->file = $filename;
}
$data->title = $request->title;
$data->description = $request->description;
$data->uploader = Auth::user()->name;
$data->save();
$users = admin::where('id','3')->get();
Notification::send($users, new TaskCompleted($data));
return redirect(route('cv.index'))->with('toast_success','Post Created Successfully');
}
View: in admin.cv.show, the template extends the admin.layouts.app. and the problematic view is here.
<li class="nav-item dropdown">
<a class="nav-link" data-toggle="dropdown" href="#">
<i class="far fa-bell"></i>
#if (Auth::check())
#if(auth()->user()->unreadNotifications->count())
<span class="badge badge-warning navbar-badge">{{auth()->user()->unreadNotifications->count()}}</span>
#endif
#endif
</a>
<div class="dropdown-menu dropdown-menu-lg dropdown-menu-right">
<span class="dropdown-item dropdown-header">
Mark All as Read
</span>
#foreach(auth()->user()->unreadNotifications as $notification)
<div class="dropdown-divider"></div>
<a href="#" class="dropdown-item" style="background-color: lightgrey">
<p><i class="fas fa-envelope mr-2"></i>{{$notification->data['data']}}
<span class="float-right text-muted text-sm">{{$notification->created_at->diffForHumans()}}</span>
</p>
</a>
#endforeach
#foreach(auth()->user()->readNotifications->take(5) as $notification)
<div class="dropdown-divider"></div>
<a href="#" class="dropdown-item">
<p><i class="fas fa-envelope mr-2"></i>{{$notification->data['data']}}
<span class="float-right text-muted text-sm">3 mins</span>
</p>
</a>
#endforeach
<div class="dropdown-divider"></div>
See All Notifications
</div>
</li>
Related
web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\HomeController;
use App\Http\Controllers\PostsController;
use App\Http\Controllers\AboutController;
use App\Http\Controllers\ContactController;
use App\Http\Controllers\CategoryController;
use App\Http\Controllers\TagController;
use App\Http\Controllers\AdminControllers\DashboardController;
use App\Http\Controllers\AdminControllers\AdminPostsController;
use App\Http\Controllers\AdminControllers\AdminCategoriesController;
use App\Http\Controllers\AdminControllers\TinyMCEController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', [HomeController::class,'index'])->name("home");
Route::get('/posts/{post:slug}',[PostsController::class,'show'])->name("posts.show");
Route::post('/posts/{post:slug}',[PostsController::class,'addComment'])->name("posts.add_comment");
Route::get('/contact', [ContactController::class , 'create'])->name("contact.create");
Route::post('/contact', [ContactController::class , 'store'])->name("contact.store");
Route::get('/about', AboutController::class)->name("about");
Route::get('/categories/{category:slug}',[CategoryController::class,'show'])->name("categories.show");
Route::get('/categories',[CategoryController::class,'index'])->name("categories.index");
/// /tags/{tag:slug} === SHOULD BE /tags/{tag:name}
Route::get('/tags/{tag:name}',[TagController::class,'show'])->name("tags.show");
// Admin Dashboard
//Route::get('/admin',[DashboardController::class,'index'])->name("admin.index");
Route::prefix('admin')->name('admin.')->middleware(['auth','isadmin'])->group(function(){
Route::get('/',[DashboardController::class,'index'])->name("index");
Route::post('upload_tinymce_image',[TinyMCEController::class,'upload_tinymce_image'])->name('upload_tinymce_image');
Route::resource('posts',AdminPostsController::class);
Route::resource('categories',AdminCategoriesController::class);
});
require __DIR__.'/auth.php';
AdminCategoriesController.php
<?php
namespace App\Http\Controllers\AdminControllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use App\Models\Category;
class AdminCategoriesController extends Controller
{
public function index()
{
return view('dashboard.categories.index');
}
public function create()
{
return view('dashboard.categories.create');
}
public function store(Request $request)
{
}
public function show(Category $category)
{
return view('dashboard.categories.show', [
'category' => $category
]);
}
public function edit(Category $category)
{
return view('dashboard.categories.edit', [
'category' => $category
]);
}
public function update(Request $request, Category $category)
{
}
public function destroy(Category $category)
{
}
}
nav.blade.php
<!--sidebar wrapper -->
<div class="sidebar-wrapper" data-simplebar="true">
<div class="sidebar-header">
<div>
<img src="{{asset('assets/images/logo-icon.png')}}" class="logo-icon" alt="logo icon">
</div>
<div>
<h4 class="logo-text">MYBLOG</h4>
</div>
<div class="toggle-icon ms-auto"><i class='bx bx-arrow-to-left'></i>
</div>
</div>
<!--navigation-->
<ul class="metismenu" id="menu">
<li>
<a href="" target="_blank">
<div class="parent-icon"><i class='bx bx-home-circle'></i></div>
<div class="menu-title">Dashboard</div>
</a>
</li>
<li>
<a href="javascript:;" class="has-arrow">
<div class="parent-icon"><i class='bx bx-message-square-edit'></i>
</div>
<div class="menu-title">Posts</div>
</a>
<ul>
<li> <i class="bx bx-right-arrow-alt"></i>All Posts
</li>
<li> <i class="bx bx-right-arrow-alt"></i>Add New Post
</li>
</ul>
</li>
<li>
<a href="" class="has-arrow">
<div class="parent-icon"><i class='bx bx-menu'></i>
</div>
<div class="menu-title">Categories</div>
</a>
<ul>
<li> <i class="bx bx-right-arrow-alt"></i>All Categories
</li>
<li> <i class="bx bx-right-arrow-alt"></i>Add New Category
</li>
</ul>
</li>
</ul>
<!--end navigation-->
</div>
<!--end sidebar wrapper -->
I develop a blog and I have a resource controller for posts and worked fine when I created another one for categories gave my that error "Route [admin.categories.index] not defined." .
Just I put the route in dashboard the error raise and gone if I commented the two routes for categories in nav.blade.php file
According to Laravel 9 Documentation
Route::resources([
'posts' => AdminPostsController::class,
'categories'=> AdminCategoriesController::class
]);
then I ran php artisan route:clear.
finally the routes appears.
I have a project for food ordering. On my object(restaurant) show page I'm calling all product categories with relationship for foreach products that belongs to that category.
I'm also using laravel livewire and this is my Component:
<?php
namespace App\Http\Livewire\Stores;
use Livewire\Component;
use Illuminate\Http\Request;
use App\Models\Store;
use App\Models\CategoryProduct;
use App\Models\Product;
use App\Http\Livewire\Cart;
use App\Models\Favourite;
use Session;
use Auth;
class Show extends Component
{
public $store;
public $categories;
public $ratings;
public $message = '';
public $supplements = [];
public $supplementsArray = [];
public $features = [];
public $featuresArray = '';
public $quantity = 1;
public $deliveryPrice = 0;
public function render(Request $request)
{
if(!Session::has('cart')){
return view('livewire.stores.show');
}
$items = explode('|', $this->featuresArray);
$oldCart = Session::get('cart');
$store_id = $this->store->id;
$oldCart->deliveryPrice = $this->store->delivery_price;
if($oldCart->storeId != $store_id){
$request->session()->forget('cart');
}
$cart = new Cart($oldCart);
//dd(session()->get('cart'));
return view('livewire.stores.show',[
'products' => $cart->items,
'totalPrice' => $cart->totalPrice + $cart->deliveryPrice,
'totalQty' => $cart->totalQty,
'ordersPrice' => $cart->ordersPrice,
'storeId' => $cart->storeId,
]);
}
}
This public $categories; variable is from my Controller:
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$store = Store::find($id);
$categories = CategoryProduct::where('store_id', $store->id)->get();
$ratings = $store->getAllRatings($store->id);
if($store->checkWorktime() == 'Zatvoreno'){
return view('website.stores.closed', compact('store', 'categories', 'ratings'));
}
return view('website.stores.show', compact('store', 'categories', 'ratings'));
}
And in my blade view this is how I'm viewing it:
#foreach($categories as $category)
<div class="row m-0" id="{{$category->id}}">
<h6 class="p-3 m-0 bg-light font-weight-bold w-100">{{$category->title}} <span class="float-right">
<small class="text-black-50">{{count($category->categoryProducts)}} proizvoda</small></span>
</h6>
<div class="col-md-12 px-0 border-top">
<div class="">
<ul class="list-group list-group-flush">
#foreach($category->categoryProducts as $product)
<a href="#0" class="list-group-item list-group-item-action" data-toggle="modal" data-target="#modal{{$product->id}}">
<div class="row">
<div class="col-9">
<b class="text-dark">{{$product->title}}</b><br>
<small class="text-muted">{{$product->description}}</small><br><br>
#if($product->features->isNotEmpty())
<small class="text-dark" style="font-size:14px !important;">od {{$product->price}}€</small>
#else
<small class="text-dark" style="font-size:14px !important;">{{$product->price}}€</small>
#endif
</div>
#if($product->thumbnail)
<div class="col-3">
<span class="float-right">
<img src="{{$product->thumbnail->getUrl('showPreview')}}" style="width:80px;height:80px;border-radius:50%;object-fit:cover;" alt="">
</span>
</div>
#endif
</div>
</a>
#include('website.stores.product-modal')
#endforeach
</ul>
</div>
</div>
</div>
#endforeach
And my page is loading crazy slow. I know I'm something doing wrong and I know that there is a way to speed this up. How can I do that?
I am new to laravel and i am working in resource controller CRUD operation.i have done with show function and my front end will get the id from the user and i need to show the details using id. For this i have used resource controller show function . Problem is , how to return the id ? i tried with below formats
http://localhost/sbadmin/public/invoice/invoice/show?12
http://localhost/sbadmin/public/invoice/invoice/show/12
both are returning 404 only.
Can anyone suggest how to write this uri ?
Here is my web.php
<?php
Route::prefix('invoice')->group(function() {
Route::get('/createInvoice', 'Invoice\InvoiceController#getAllInvoiceDetails');
Route::post('/addInvoice', 'Invoice\InvoiceController#addInvoice');
Route::post('/checkPhoneNumberAndFetchData', 'Invoice\InvoiceController#checkPhoneNumberAndReturnData');
Route::resource('invoice', 'Invoice\InvoiceManagementController')->only([
'index', 'show'
]);
Route::get('/searchInvoice','Invoice\InvoiceController#searchInvoice');
Route::get('/viewAllInvoice','Invoice\InvoiceController#viewAllInvoice');
Route::get('/viewInvoicesAsJson','Invoice\InvoiceController#viewInvoicesAsJson');
});
Controller:
namespace Modules\Invoice\Http\Controllers\Invoice;
use Illuminate\Routing\Controller;
use Illuminate\Http\Request;
use Modules\Invoice\Entities\Invoice;
class InvoiceManagementController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('invoice::viewinvoices');
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//return $id;
$invoices = Invoice::findOrFail($id)->with(['user','events','payments'])->get();
return view('invoice::invoice');
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
/**
* Responds to requests to GET /users/show/1
*/
public function getShow($id)
{
//
}
}
blade.php:
<div class="card o-hidden border-0 shadow-lg my-5">
<div class="card-body p-0">
<!-- Nested Row within Card Body -->
<div class="row">
<div class="col-lg-5 d-none d-lg-block bg-register-image"></div>
<div class="col-lg-7">
<div class="p-5">
<div class="text-center">
<h1 class="h4 text-gray-900 mb-4">Search Invoice</h1>
</div>
<form id="form" onsubmit="return OnSubmitForm();" >
#csrf
<div class="form-group row">
<div class="col-sm-6 mb-3 mb-sm-0">
<input type="text" class="form-control form-control-user" name="invoice_id" id="id" placeholder="Enter Invoice number" >
</div>
</div>
<button type="submit" class="btn btn-primary btn-user btn-block">
View Invoice
</button>
<hr>
<a href="index.html" class="btn btn-google btn-user btn-block" hidden="">
<i class="fab fa-google fa-fw"></i> Register with Google
</a>
<a href="index.html" class="btn btn-facebook btn-user btn-block" hidden="">
<i class="fab fa-facebook-f fa-fw"></i> Register with Facebook
</a>
</form>
<div class="text-center" hidden="">
<a class="small" href="forgot-password.html">Forgot Password?</a>
</div>
<div class="text-center" hidden="">
<a class="small" href="login.html">Already have an account? Login!</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Bootstrap core JavaScript-->
<script src="{{ asset('sbadmin/vendor/jquery/jquery.min.js') }}"></script>
<script src="{{ asset('sbadmin/vendor/bootstrap/js/bootstrap.bundle.min.js') }}"></script>
<!-- Core plugin JavaScript-->
<script src="{{ asset('sbadmin/vendor/jquery-easing/jquery.easing.min.js') }}"></script>
<!-- Custom scripts for all pages-->
<script src="{{ asset('sbadmin/js/sb-admin-2.min.js') }}"></script>
<script type="text/javascript">
function OnSubmitForm()
{
$('#form').prop('action',"invoice/show/"+$('#id').val());
return true;
}
</script>
For Laravel resource controller actions no need to add the CRUD actions
GET/invoice, mapped to the index() method,
GET /invoice/create, mapped to the create() method,
POST /invoice, mapped to the store() method,
GET /invoice/{id}, mapped to the show() method,
GET /invoice/{id}/edit, mapped to the edit() method,
PUT/PATCH /invoice/{id}, mapped to the update() method,
DELETE /invoice/{id}, mapped to the destroy() method.
And try to access your show route action like this:
http://localhost/sbadmin/public/invoice/invoice/12
You don't need to append show in url.
Route::resource('invoice', 'Invoice\InvoiceManagementController')->only([
'index', 'show'
]);
http://localhost/sbadmin/public/invoice/invoice/show/12 -> remove show from here.
Now you url look like.
http://localhost/sbadmin/public/invoice/invoice/12 -> show method
Here, I elaborate more.
Get | http://localhost/sbadmin/public/invoice/invoice | index method
Post | http://localhost/sbadmin/public/invoice/invoice | store method
get | http://localhost/sbadmin/public/invoice/invoice/12 | show method.
first of all change your prefix in routes to:
Route::group(['prefix' => 'invoice', 'as' => 'invoice.'], function(){
then in your script :
function OnSubmitForm()
{
$('#form').prop('action',"invoice/invoice/"+$('#id').val());
return true;
}
i hope this works.
this is my routes
Route::get('/', 'frontcontroller#index');
Route::get('/index.html', 'frontcontroller#index');
Route::get('/checkout.html', 'frontcontroller#checkout');
Route::get('/furniture.html', 'frontcontroller#furniture');
Route::get('/login.html', 'frontcontroller#login');
Route::get('/products.html', 'frontcontroller#products');
Route::get('/register.html', 'frontcontroller#register');
Route::get('/single.html', 'frontcontroller#single');
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::group(['prefix' => 'admin','middleware'=>'auth'], function () {
Route::get('/', function () {
return view('admin.index');
})->name('admin.index');
});
this is a side navigation:
{{-- Side Navigation --}}
<div class="col-md-2">
<div class="sidebar content-box" style="display: block;">
<ul class="nav">
<!-- Main menu -->
<li class="current"><a href="{{route('admin.index')}}"><i class="glyphicon glyphicon-home"></i>
Dashboard</a></li>
<li class="submenu">
<a href="#">
<i class="glyphicon glyphicon-list"></i> Products
<span class="caret pull-right"></span>
</a>
<!-- Sub menu -->
<ul>
<li>Add Product</li>
</ul>
</li>
</ul>
</div>
</div> <!-- ADMIN SIDE NAV-->
This is the route function
/**
* Get the URL to a named route.
*
* #param string $name
* #param mixed $parameters
* #param bool $absolute
* #return string
*
* #throws \InvalidArgumentException
*/
public function route($name, $parameters = [], $absolute = true)
{
if (! is_null($route = $this->routes->getByName($name))) {
return $this->toRoute($route, $parameters, $absolute);
}
throw new InvalidArgumentException("Route [{$name}] not defined.");
}
Why I have this problem?
Route [product.index] not defined.
(View:C:\Users\Antonio\Desktop\uni\musicshop\resources\views\admin\layout\includes\sidenav.blade.php)
(View:C:\Users\Antonio\Desktop\uni\musicshop\resources\views\admin\layout\includes\sidenav.blade.php)
(View:C:\Users\Antonio\Desktop\uni\musicshop\resources\views\admin\layout\includes\sidenav.blade.php)
This is the code of the problem:
enter image description here
you should set name route
Route::get('/products.html', 'frontcontroller#products')->name('product.index');
I created two roles: admin and editor. I can secure the menus of these modules directly into the resources/views/vendor/backpack/base/inc/sidebar.blade.php using
#role('admin')
<li class="header">{{ trans('backpack::base.administration') }}</li>
<!-- ================================================ -->
<!-- ==== Recommended place for admin menu items ==== -->
<!-- ================================================ -->
<li><i class="fa fa-dashboard"></i> <span>{{ trans('backpack::base.dashboard') }}</span></li>
<li><i class="fa fa-files-o"></i> <span>File manager</span></li>
<li><i class="fa fa-hdd-o"></i> <span>Backups</span></li>
<li><i class="fa fa-terminal"></i> <span>Logs</span></li>
<li><i class="fa fa-cog"></i> <span>Settings</span></li>
<!-- ======================================= -->
<li class="header">{{ trans('backpack::base.user') }}</li>
<!-- Users, Roles Permissions -->
<li class="treeview">
<i class="fa fa-group"></i> <span>Users, Roles, Permissions</span> <i class="fa fa-angle-left pull-right"></i>
<ul class="treeview-menu">
<li><i class="fa fa-user"></i> <span>Users</span></li>
<li><i class="fa fa-group"></i> <span>Roles</span></li>
<li><i class="fa fa-key"></i> <span>Permissions</span></li>
</ul>
</li>
#endrole
<li><i class="fa fa-sign-out"></i> <span>{{ trans('backpack::base.logout') }}</span></li>
</ul>
Of course, this is not the end, as you still have to secure access to the module for the editor by entering the URL. in vendor/backpack/permissionmanager/src/app/Http/Controllers/PermissionCrudController.php method setup can use
Auth::user()->hasRole('admin')
and throw error or redirect but ...
This is not a good solution (writing in modules in vendor). What should I do? How to secure editor access to the mentioned modules. Sorry if it's too easy for you, I'm just starting to have fun with Laravel
PS. https://github.com/spatie/laravel-permission/issues/507
I'd recommend creating middleware to check for a permission or a role, and lock people out using role:admin or permission:admin, something like this:
PermissionMiddleware.php:
<?php
namespace App\Http\Middleware;
use Closure;
use Auth;
class PermissionMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next, $permission)
{
if (Auth::guest()) {
return redirect('login');
}
if (! $request->user()->can($permission)) {
abort(403);
}
return $next($request);
}
}
RoleMiddleware.php:
<?php
namespace App\Http\Middleware;
use Closure;
use Auth;
class RoleMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next, $role)
{
if (Auth::guest()) {
return redirect('login');
}
if (! $request->user()->hasRole($role)) {
abort(403);
}
return $next($request);
}
}
You should then be able to use these when you write the routes to your CRUDs. If you want to overwrite the routes created in Backpack\Base, you should be able to easily do that by creating a file routes/backpack/base.php. Backpack will then load that file, instead of the one in the package. See https://github.com/laravel-backpack/base#overwriting-functionality for more details.
Hope it helps!