Undefined variable $statistic_teachers - laravel

I was trying to pass data to my view, but don't why there is a error
my blade which I want to pass data there
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card">
<div class="card-header">{{ __('StatistikAnsicht') }}</div>
<div class="card-body">
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
<table id="statisticforteacher" class="table-responsive" style="width:100%">
<thead>
<th>FrageTitel</th>
<th>Kapitel</th>
<th>RichtigeRate</th>
</thead>
<tbody>
#foreach($statistic_teachers as $value)
<tr>
<td>{{$value -> question_title}}</td>
<td>{{$value -> chapters_id}}</td>
<td>{{$value -> correct_rate}}</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
and my controller, and use a connection with model to pass data
<?php
namespace App\Http\Controllers;
use App\Models\StatisticTeacher;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class StatisticTeacherController extends Controller
{
//
public function statisticteacher(){
$statistic_teachers = StatisticTeacher::all();
return view('statisticsA',compact('statistic_teachers'));
}
}
and this is my route, I think it isn't about my route, when I didn't pass data to the view, everythink works.
Route::get('/author_views.statisticsA', 'PagesController#getStatisticsAdmin')->name('statisticsA')->middleware('auth');
Route::get('/statisticsA', 'StatisticTeacherController#statisticteacher');
and this is model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class StatisticTeacher extends Model
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'id','question_title','chapters_id','correct_answer','wrong_ansers','correct_rate'
];
use HasFactory;
public $timestamps = false;
}
I think everything is ok, can not find such a syntax error, but it still doesn't work
can anyone help?
by the way this is stack trace
enter image description here

Please try below approach.
<?php
class StatisticTeacherController extends Controller
{
//
public function statisticteacher(){
$statistic_teachers = StatisticTeacher::all();
return view('statisticsA',['statistic_teachers' => $statistic_teachers]);
}
}
Check on which line in your blade file is throwing error. Compiled vies are stored inside storage\framework\views directory.

Related

Show counter result in dashboard

I would like to create a dasboard with Laravel 8. I want to count all tickets in the database and display the number in the dashboard. Unfortunately it does not work do you have an idea?
Controller Code
namespace App\Http\Controllers;
use App\Models\Ticket;
use Illuminate\Http\Request;
class DashboardController extends Controller
{
public function index()
{
//
$ticketsCount = Ticket::count();
return view('dashboard.index', compact('ticketsCount'));
}
}
View Code
<div class="col-lg-3 col-6">
<!-- small box -->
<div class="small-box bg-info">
<div class="inner">
<h3>{{ $ticketsCount->count() }}</h3>
<p>Open Tickets</p>
</div>
<div class="icon">
<i class="ion ion-bag"></i>
</div>
More info <i class="fas fa-arrow-circle-right"></i>
</div>
</div>
As I can see, your router returns view file, and not getting into controller.
Route::get('/dashboard', function () {
return view('dashboard.index');
});
change your router to (Laravel version before 8)
Route::get('/dashboard', 'DashboardController#index');
After Laravel version 8
use App\Http\Controllers\DashboardController;
Route::get('/dashboard', [DashboardController::class, 'index']);
Docs
Remove ->count() from your view, you already counted it in controller
$ticketsCount = Ticket::count();
The view code:
<div class="col-lg-3 col-6">
<!-- small box -->
<div class="small-box bg-info">
<div class="inner">
<h3>{{ $ticketsCount }}</h3>
<p>Open Tickets</p>
</div>
<div class="icon">
<i class="ion ion-bag"></i>
</div>
More info <i class="fas fa-arrow-circle-right"></i>
</div>
</div>
I have tried to get the number of users displayed on the view. Unfortunately I always get an error message...
Error:
ErrorException
Undefined variable: counter (View: /laravel/resources/views/dashboard/index.blade.php)
Route (web):
Route::get('/dashboard', function () {
return view('dashboard.index');
});
Model (Dashboard)
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Dashboard extends Model
{
use HasFactory;
}
Controller (DashboardController)
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
class DashboardController extends Controller
{
public function index()
{
$counter = DB::table('users')->count();
return view('dashboard.index', compact('counter'));
}
}
View (dashboard/index.blade.php):
Users: {{ $counter }}

Facade\Ignition\Exceptions\ViewException Error on Laravel?

0
I reached a part I cannot figure out. When trying to display a product on home page I get the following error:
Undefined variable: products (View: /home/acer/test/project_basket/basket/resources/views/home.blade.php)
For me is the first project in php and i'm not very practice in this language.
home.blade.php:
#section('content')
<div class="card-deck">
/*Problem Here */
#foreach ($products as $product)
<div class="card">
<img src="{{ $product->imagePath }}" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">{{ $product->title }}</h5>
<p class="color">{{ $product->color }}</p>
Buy Now
<button type="button" class="btn btn-primary float-right">Add to Cart</button>
<div class="price">${{ $product->price }}/div>
</div>
</div>
#endsection
Product.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $fillable = ['imagePath', 'title', 'price', 'color'];
}
ProductController.php:
<?php
namespace App\Http\Controllers;
use App\Product;
use Illuminate\Http\Request;
//use Illuminate\Http\Request;
class ProductController extends Controller
{
/**
*#return \Illuminate\Http\Response
*/
public function index()
{
$products = Product::inRandomorder()->take(6)->get();
return view('home')->with('products', $products);
}
}
Routes:
//Route::view('/`home`', 'home');
Route::get('/', 'ProductController#index')->name('home');
Auth::routes();
Route::get('/home', 'ProfilesController#index')->name('home');
Route::get('/', 'ProfilesController#index')->name('welcome');
//Route::get('/home', 'DasboardController#index')->name('dashboard');
You hare "hitting" the /home endpoint, which looking at your route is pointing to ProfilesController, but you are working on ProductController so have written the wrong Controller in web.php

ErrorException thrown with message "Trying to get property 'subo_name' of non-object

ErrorException thrown with message
"Trying to get property 'subo_name' of non-object (View:
C:\xampp\htdocs\org\resources\views\users\index.blade.php)"
Main model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Maino extends Model
{
protected $fillable = [
'maino_name'
];
public function subo()
{
return $this->hasMany('App\Subo');
}
}
Sub model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Subo extends Model
{
protected $fillable = [
'subo_name','maino_id'
];
public function maino()
{
return $this->belongsTo('App\Maino');
}
public function users()
{
return $this->hasMany('App\User');
}
}
user model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password','role_id'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function role()
{
return $this->belongsTo('App\Role');
}
public function profile()
{
return $this->hasMany('App\Profileinfo');
}
public function suborg()
{
return $this->belongsTo('App\Subo');
}
}
UserController code
public function index()
{
// $user=User::all();
$users=User::all();
return view('users.index',compact('users'));
}
index.blade.php
#extends('mainorg.main')
#section('title','Users')
#section('content')
<!-- DataTables Example -->
#if(Session::has('status'))
<div class="alert alert-success">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span></button>
{{ Session::get('status') }}
</div>
#endif
<div class="card mb-3">
<div class="card-header">
<!-- <i class="fas fa-table"></i>
MainOrg --><div class="container"><button class="btn btn-primary float-right">Add SubOrg</button></div></div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>user</th>
<th>main org</th>
<th>suborg</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tfoot>
<tr>
<th>id</th>
<th>name</th>
<th>user</th>
<th>main org</th>
<th>suborg</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</tfoot>
#foreach($users as $user)
<tr>
<td>{{$user->id}}</td>
<td>{{$user->name}}</td>
<td>{{$user->role->role_name}}</td>
<td>{{$user->suborg->subo_name}}</td>
<td>Edit</td>
<td><form action="{{route('users.destroy',$user->id)}}" method="post">
#method('DELETE')
#csrf
<input type="submit" name="" value="DELETE" class="btn btn-danger">
</form></td>
</tr>
#endforeach
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
#endsection
I am facing problem regarding to this code so please help me solve this problem ......................
The error means that one of your $users doesn't have a suborg while looping. So {{ $user->suborg }} is null, and you can't access ->name of null. To handle this, restrict your users to only those that have a suborg, or check while looping:
public function index() {
$users=User::with('suborg')->has('suborg')->get();
return view('users.index',compact('users'));
}
Note: You can use both with and has in a single query; they do different things.
Or, while looping your users, check existence:
#foreach($users as $user)
<tr>
<td>
#if($user->suborg)
{{ $user->suborg->subo_name }}
#else
No Suborg
#endif
</td>
</tr>
#endforeach
When you creating relation between two or more models then you should use relational method during model use using with in your eloquent call, you can also write when you want to pass multiple like - with(['suborg', 'example']). In index method, bellow $users variable make dd($users) and check is there have any relational data. If found I think, it should work.
public function index()
{
// $user=User::all();
$users=User::with('suborg')->get();
return view('users.index',compact('users'));
}
And your index.blade.php
#foreach($users as $user)
<tr>
<td>{{$user->id}}</td>
<td>{{$user->name}}</td>
<td>{{$user->role->role_name}}</td>
<td>{{$user->suborg->subo_name || 'Not Found'}}</td>
......
#endforeach

Call to a member function get() on null for a function in a model

I am trying to have a button of an employee show the text “Already booked” if the variable
count($bookingRequests) returns something and if nothing then show “Book Me’
I get the error above.
I have the following models and their relationships:
User.php and Bookings.php
User:
public function bookings() {
return $this->hasMany('App\Models\Bookings');
}
public function BookingRequest()
{
$this->bookings()->where('booking_status','=','confirmed')->get();
}
Bookings:
public function user(){
return $this->belongsTo('App\Models\User');
}
The view mentioned above is Employeeblock.blade.php:
<div class="row no-gutters mb-5 mb-lg-0" style="padding:10px">
#if(count($bookingRequests))
<a href="#" class="btn btn-primary" data-
toggle="modal" data-target=“#bookingModal">Already Booked</a>
#else
<a href="#" class="btn btn-primary" data-
toggle="modal" data-target="#bookingModal">Book Me</a>
#endif
</div>
Which has data passed onto it by a controller SearchController:
In the following way:
<?php
namespace App\Http\Controllers;
use DB;
use Auth;
use App\Models\Employee;
use App\Models\User;
use App\Models\Bookings;
use Illuminate\Http\Request;
use GuzzleHttp\Client;
use Session;
.
.
.
$bookingRequests=Auth::user()->BookingRequest()->get();
return view(‘search.results’)
->with('bookingRequests',$bookingRequests)
results.blade.php above has the following html:
<div class="panel panel-default">
<div class="panel-heading"><h3></h3></div>
<div class="panel-body">
<div class="row">
<div class="col-lg-12">
#foreach($Employees as $Employee)
#include('user/partials/employeeblock')
#endforeach
</div>
</div>
</div>
</div>
</div>
Replace:
$bookingRequests=Auth::user()->BookingRequest()->get();
with
$bookingRequests=Auth::user()->BookingRequest();
Because your BookingRequest() method already use ->get() method to obtain data from db.

Two controllers one route laravel

I can currently show the index page along with a list of posts. The user can select a post to view post details. For this I have:
Routes:
Route::get('/', 'PostsController#showPosts');
Route::get('post/{slug}', 'PostsController#showPostDetails');
Controller:
<?php
namespace App\Http\Controllers;
use App\Post;
use Illuminate\Http\Request;
class PostsController extends Controller
{
public function showPosts()
{
$posts = Post::simplePaginate(2);
return view('index', ['posts' => $posts]);
}
public function showPostDetails($slug)
{
$post = Post::findBySlug($slug);
return view('post.show',['post'=>$post]);
}
}
Model:
public static function findBySlug($slug)
{
return static::where('slug', $slug)->first();
}
index
#extends('layouts.index')
#section('header')
<!-- Page Header -->
<header class="masthead" style="background-image: url('img/home-bg.jpg')">
<div class="overlay"></div>
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
<div class="site-heading">
<h1>Train Testing</h1>
<span class="subheading">Testing Times</span>
</div>
</div>
</div>
</div>
</header>
#stop
#section('content')
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
#foreach ($posts as $post)
#include('partials.post', ['post' => $post])
#endforeach
{{ $posts->links() }}
</div>
</div>
#stop
partials/post.blade.php
<div class="post-preview">
<a href="/post/{{ $post->slug }}">
<h2 class="post-title">
{{ $post->title }}
</h2>
<h3 class="post-subtitle">
{{ $post->excerpt }}
</h3>
</a>
<p class="post-meta">Posted by
{{ $post->author->name }}
on {{ $post->created_at->format('l d F, Y') }}</p>
</div>
<hr>
I now want to show the posts on all other pages. My other pages currently have the route Route::get('{slug}', 'PagesController#show'); And it makes sense initially to refer back to existing code so use Route::get('{slug}', 'PostsController#showPosts'); like I did on the home page to display posts there.
However I am not sure of the best way to deal with this as I believe you can not have two controllers for one route.
For other pages I currently have:
Controller:
<?php
namespace App\Http\Controllers;
use App\Page;
use Illuminate\Http\Request;
class PagesController extends Controller
{
public function show($slug)
{
$page = Page::findBySlug($slug);
return view('page', ['page' => $page]);
}
}
page.blade:
#extends('layouts.index')
#section('header')
<!-- Page Header -->
<header class="masthead" style="background-image: url('/storage/{{ $page->image }}')">
<div class="overlay"></div>
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
<div class="page-heading"> <h1>{!! $page->title !!}</h1>
<span class="subheading"></span>
</div>
</div>
</div>
</div>
</header>
#stop
#section('content')
<!-- Main Content -->
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
{!! $page->body !!}
</div>
</div>
</div>
#stop
Pages Controller:
use App\Page;
use App\Post;
use Illuminate\Http\Request;
class PagesController extends Controller
{
public function show($slug)
{
$posts = Post::simplePaginate(2);
$page = Page::findBySlug($slug);
return view('page', ['page' => $page, 'posts' => $posts]);
}
Then in page.blade.php I can call $posts without any errors:
#foreach ($posts as $post)
#include('partials.post', ['post' => $post])
#endforeach
{{ $posts->links() }}
Not sure if this is the neatest way but it works.

Resources