Class not found with laravel? - php

today I am trying to fix the following error. It is telling me for some weird reason that the class for my relationship in laravel does not exist? I am not sure why as the code looks perfectly fine to me.
Class 'App\Database\Website\Roleplay\GovermentRole' not found
Where it is happening:
{{ $governmentMember->government_role->government_title }}
Full code:
#if ($higherGovernment->count() > 0)
#foreach ($higherGovernment as $governmentMember)
<div class="col-md-10">
<div class="col-md-12" style="margin-left:-40px;">
<div class="col-md-1" style="margin-top:-16px;"><img src="http://mywebsite.com/images/get_character_look.php?look={{ $governmentMember->user->look }}&size=b&direction=3&head_direction=3"></div>
<div class="col-md-9" style="margin-left:40px;">
<h4>{{ $governmentMember->government_role->government_title }}<small>The Crown</small></h4>
<p><font color="#aaa">Department here</font></p><br>
</div>
</div>
</div>
#endforeach
#else
There are currently no candigates working in this category.
#endif
Here is my Roleplay Stat class, which $governmentMember is an instance of:
<?php
namespace App\Database\Website\User;
use Eloquent;
class Roleplay extends Eloquent
{
protected $primaryKey = 'id';
protected $table = 'srp_user_statistics';
public $timestamps = false;
protected $fillable = [];
public function user()
{
return $this->belongsTo('App\Database\Website\User\Player', 'user_id', 'id');
}
public function government_role()
{
return $this->belongsTo('App\Database\Website\Roleplay\GovermentRole', 'government_id');
}
}
Here is my GovernmentRole class:
<?php
namespace App\Database\Website\Roleplay;
use Eloquent;
class GovernmentRole extends Eloquent
{
protected $primaryKey = 'id';
protected $table = 'srp_government_roles';
public $timestamps = false;
protected $fillable = [];
public function stats(){
return $this->hasMany('App\Database\Website\User\Roleplay', 'government_id');
}
}
Here is the controller for the blade page:
<?php
namespace App\Http\Controllers\Frontend\User;
use Auth;
use Cache;
use Illuminate\Http\Request;
use App\Database\Website\User\Roleplay;
use App\Database\Website\Roleplay\GovernmentRole;
use App\Database\Website\Roleplay\Life\LifeEvents;
class GovernmentController
{
public function getView()
{
$royalty = Cache::remember('government.royalty', 1, function() {
return GovernmentRole::where('government_type', 'royalty')->first()->stats;
});
$higherGovernment = Cache::remember('government.higher_government', 1, function() {
return GovernmentRole::where('government_type', 'higher_government')->first()->stats;
});
$seniorGovernment = Cache::remember('government.senior_government', 1, function() {
return GovernmentRole::where('government_type', 'senior_ministers')->first()->stats;
});
$juniorGovernment = Cache::remember('government.junior_government', 1, function() {
return GovernmentRole::where('government_type', 'junior_ministers')->first()->stats;
});
return view('frontend.community.government', compact('juniorGovernment', 'seniorGovernment', 'higherGovernment', 'royalty'));
}
}

Sorry to tell you this, but there is a 'typing error' in your relationship method
public function government_role()
{
return $this->belongsTo('App\Database\Website\Roleplay\GovermentRole', 'government_id');
}
You are looking for 'GovermentRole' while the class' name is 'GovernmentRole'. Notice the extra 'n' character after 'r'

The error is because GovermentRole file does not available at specified path i.e.
App\Database\Website\Roleplay\GovermentRole

Make sure the class is in right folder. Then run this command:
composer dumpauto

Related

Undefined variable $categories #Laravel

I have this controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Category;
class CategoriesController extends Controller
{
public function index()
{
$categories = Category::all();
return view('home', ['categories'=> $categories]);
}
}
and my blade is something like this(his call "home.blade.php")
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.3.3/css/swiper.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.3.3/js/swiper.min.js"></script>
<div class="container">
<div class="row text-center mb-3">
<div class="col-md-12">
<h2>Categorias</h2>
<hr>
#foreach($categories as $cat)
<button>{{ $cat->CATEGORIA_NOME }}</button>
#endforeach
</div>
</div>
the Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
use HasFactory;
protected $fillable = ['CATEGORIA_NOME', 'CATEGORIA_DESC'];
protected $table = 'CATEGORIA';
protected $primaryKey = 'CATEGORIA_ID';
protected $timestamp = false;
public function categorias()
{
return $this->hasMany(Product::class, 'CATEGORIA_ID');
}
}
but i still receiving the error:
Undefined variable $categories
I tried to using the
$categories = Category::all();
return view('home', ['categories'=> $categories]);
or
return view('home')->with('categories', $categories);
but it did not work
try this :
return view('home', ['categories'=> Category::all()]);
if doesn't work try to dump your category model, see if the data is out or not
Try using compact(), like this.
$categories = Category::all();
return view('home', compact('categories'));

Can't display the values from my data base with Laravel Livewire

I'm using a Livewire component, this is my code:
Search.php :
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\Recipe;
use App\Models\Vegetable;
use App\Models\VegetablesRecipe;
class Search extends Component
{
public $query = '';
public $vegetables;
public function mount()
{
$this->resetQuery();
}
public function resetQuery()
{
$this->vegetables = [];
}
public function render()
{
if ($this->query != null) {
return view('livewire.search', [
'vegetables' => Vegetable::where('name', 'like', '%'.$this->query.'%')->get()->toArray()
]);
} else {
return view('livewire.search', [
'vegetables' => Vegetable::all()->toArray()
]);
}
}
}
search.blade.php :
<div class="searchcomponent">
<h1>Search</h1>
<input wire:model="query" type="text" placeholder="Rechercher...">
#if(!empty($query))
<ul>
#if(!empty($vegetables))
<div class="vegetables">
#foreach($vegetables as $vegetable)
<li><span class="material-icons">lunch_dining</span>{{ $vegetable['name'] }}</li>
#endforeach
</div>
#else
<li>No result</li>
#endif
</ul>
#endif
</div>
My vegetable Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Vegetable extends Model
{
use HasFactory;
public $timestamps = false;
protected $fillable = ['name'];
public function recipes(){
return $this->belongsToMany(Recipe::class, 'vegetables_recipes', 'vegetable_id', 'recipe_id');
}
public function getName($id) {
return $this->name;
}
}
My problem is, every time im typing something in my search bar, I just have a No result appearing on my screen even tho i seeded my data base with some vegetables already. Why doesn't it show me for example Carrot when i type it?
Or how can i fill my array vegetables with all the names of my vegetables datatable ?
Defining public $vegetables; will prevent you from passing it to the view.
Remove that. Also remove your mounting logic.
Thus you should have:
class Search extends Component
{
public $query = '';
public function render()
{
if ($this->query != null) {
return view('livewire.search', [
'vegetables' => Vegetable::where('name', 'like', '%'.$this->query.'%')->get()->toArray()
]);
} else {
return view('livewire.search', [
'vegetables' => Vegetable::all()->toArray()
]);
}
}
}
Also make sure you are calling #livewireScripts and #livewireStyles or their alternative syntaxes <livewire:styles /> <livewire:scripts /> from your main view which uses <livewire:search />.
Edit:
Alternatively, you could also use a public properly and write to it using $this->vegetables like so:
class Search extends Component
{
public $query = '';
public $vegetables;
public function render()
{
$this->vegetables = Vegetable::where('name', 'like', '%' . $this->query . '%')->get()->toArray();
return view('livewire.search');
}
}
Also, you can remove the #if(!empty($query)) and the #if(!empty($vegetables)) in place of a #forelse utilising the #empty statement rather than a #foreach. E.g.
#forelse($vegetables as $vegetable)
<li><span class="material-icons">lunch_dining</span>{{ $vegetable['name'] }}</li>
#empty
<li>No result</li>
#endforelse
That way, you will still get a list of your vegetables when the search box is empty, and if it's not empty but there's no matching results, you'll get your "No result" message.
This is because on the mount you are resetting the vegetable array to an empty array.
Refer to this fiddle for more details:
https://laravelplayground.com/#/snippets/f51e212a-dab3-4325-b6b0-4c6af4c0ab72

Null when var dumping for querying eloquent database?

I'm trying to var_dump a table of users associated with a task, and im getting
NULL
Ultimately im trying to get a Task and associated it with the user, im not sure if im doing it correct.
This is using eloquent in Slim.
<?php
namespace App\Controllers;
use Slim\Http\Request;
use Slim\Http\Response;
use Illuminate\Database\Capsule\Manager as DB;
use App\Models\Task;
use App\Models\User;
class TodosController extends BaseController
{
public function getTodos($request, $response, $args)
{
// $sth = $this->db->prepare("SELECT * FROM tasks ORDER BY task");
// $sth->execute();
// $use = User::all();
// below
// $todos = DB::table('tasks')
// ->join('users', 'users.id', '=', 'tasks.user_id')
// ->get();
$todos = User::find(1)->tasks()->first();
var_dump($todos);
return $this->c->view->render($response, 'todos.twig', ['todos' => $todos]);
}
Todos.twig
{% extends "templates/layout.html" %}
{% block content %}
<h1>My Todos</h1>
<ol>
{% for task in todos %}
<div id="task{{task.id}}" class="myl" ng-controller="myCtrl">
<li><h4>{{ task.task}}</h4></li>
<small style="font-style:italic">{{task.created_at |date("m/d/Y")}}</small></br>
<small style="font-style:italic">{{task.user.id}}</small></br>
<button id="disappear" name="task" class="btn btn-sm btn-danger" ng-click="deleteTask({{task.id}})">Delete</button>
</div>
{% endfor %}
</ol>
{% endblock %}
Updated
This is what my other files of code look like.
Not sure on why im getting the error
User Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $table = 'users';
protected $fillable = ['username', 'password'];
public $timestamps = [];
public function tasks()
{
return $this->hasMany('App\Models\Task', 'user_id');
}
}
Task Model
<?php
namespace App\Models;
// use Slim\Views\Twig as View;
// use Interop\Container\ContainerInterface;
use Illuminate\Database\Eloquent\Model;
class Task extends Model
{
protected $table = 'tasks';
protected $fillable = ['task', 'user_id'];
public $timestamps = [];
public function user()
{
return $this->belongsTo('App\Models\User', 'user_id');
}
}
Updated

Laravel Undefined offset error

I just finishing my blog, using laravel, and I want to add a comment feature on it, but i got few errors like this, can anyone help me, please??,
sorry for my English, English is not my native language,
Thank you :)
(1/1) ErrorException
Undefined offset: 1
Here is my AdminBlog.php Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class AdminBlog extends Model
{
protected $table = 'admin';
protected $fillable = ['title','text','images','slug'];
public function comment(){
return $this->hasMany('App\Comment');
}
}
Comment.php Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
protected $table = 'comment';
protected $fillable = ['name','email','text','post_id'];
public function post(){
return $this->belongsTo('App\AdminBlog');
}
}
BlogController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\AdminBlog;
use App\Comment;
class BlogController extends Controller
{
//Index
public function index(){
$post = AdminBlog::all();
return view('blog/index', compact('post'));
}
//Show
public function show($id){
$post = AdminBlog::findOrFail($id);
$comment = Comment::all();
//dd($comment);
return view('blog/show', ['post' => $post,
'comment' => $comment]);
}
}
show.blade.php
<div class="col-md-12 post-comment-show">
#foreach($post->comment() as $list)
<p>{{ $list->text }}</p>
#foreach
</div>
You should use:
<div class="col-md-12 post-comment-show">
#foreach($post->comment as $list)
<p>{{ $list->text }}</p>
#foreach
</div>
Note that, you have used comment(). Also, you should use a plural name for a hasMany relationship, so comment should be comments.
Also, in your show method, you should use something like the following:
public function show($id)
{
$post = AdminBlog::with('comment')->findOrFail($id);
return view('blog/show', ['post' => $post]);
}
Try the following
$post->comment()->get()
or
$post->comment
when calling a relationship with ()it returns a instance of the query builder and allows you to filter the object. If you remove the call it without () it returns you a collection which is array accessible
Another suggestion if you have many comments you should name your relationship plural.
in this case:
public function comments(){
return $this->hasMany('App\Comment');
}
// Use it like this
$post->comments
You need to change your show function:
public function show($id){
$post = AdminBlog::findOrFail($id);
$comment = Comment::all();
//dd($comment);
return view('blog/show', ['post' => $post,
'comment' => $comment]);
}
TO
public function show($id){
$post = AdminBlog::with('comment')->where('admin.id',$id)->get();
return view('blog/show', compact('post'));
}
Hope this work for you!

Get specific value Laravel

I have car table with status field and there's "available", and "breakdown".
I also got fleet CRUD, once I add fleet I want to show car with only "available" status. what should I add ?
here's my fleet controller code :
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use App\Models\Fleet;
use App\Models\Car;
use App\Models\Attendance;
use App\Helpers\Enums\FleetStatus;
use App\Models\AttendanceDetail;
use Illuminate\Http\Request;
use Yajra\Datatables\Datatables;
use App\Http\Controllers\Base\MasterController;
use Route;
use Illuminate\View\View;
class FleetController extends MasterController
{
protected $detailView = 'fleet.show';
protected $indexView = 'fleet.index';
protected $createView = 'fleet.form';
protected $editView = 'fleet.form';
protected $routeBindModel = 'fleet'; //Route Model Binding name in RouteServiceProvider
protected $redirectPageWhenFormSuccess = 'fleet.index'; //Route Name
protected $title = 'Fleet';
public function save(Request $request, $obj = null) {
if (!$obj) {
$obj = new Fleet;
}
return $this->saveHandler($request, $obj);
}
//Must have this method if need datatable;
public function datatableBuilder($obj = null) {
return Fleet::query();
}
public function makeDatatable($obj) {
return Datatables::of($obj)
->addColumn('action', function ($model) {
return $this->makeActionButtonsForDatatable($model);
})
->editColumn('status', function($model){
return FleetStatus::getString($model->status);
})
->make(true);
}
public function render(View $view, $route = null, $obj = null, $method = 'POST') {
$statusList = FleetStatus::getArray();
$carStatusList = Car::pluck('plate_no', 'id');
$attendanceList = Attendance::pluck('driver_id', 'id');
$workingHourList = Attendance::pluck('working_hours', 'id');
$view->with(compact('statusList', 'carStatusList', 'attendanceList', 'workingHourList'));
return parent::render($view, $route, $obj, $method);
}
}
here's my add form code :
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label>Car </label>
{!! Form::select('car_id', $carStatusList, null, array('class' => 'form-control')) !!}
</div>
</div>
Have you try this:
$carStatusList = Car::where('status', 'available')->pluck('plate_no', 'id')
In your model add a scope
public function scopeAvailable($query){
return $query->where('status', '=', 'available');
}
And then wherever you need to use it:
Car::available()->get()
or
Car::available()->pluck('plate_no' , 'id');
More info here: https://laravel.com/docs/5.3/eloquent#query-scopes
If I understand your question correctly, this will create a list of available cars:
Car::where('status','available')->pluck('plate_no', 'id');

Categories