I have a project about quizzes and their questions,
I don't know why but when i'm trying to get the quiz's questions i get
this error
This are my files and scripts:
Route web.php file:
Route::get('/admin/quizzes/{id}/questions', 'AdminQuizzesController#questions')->name('admin.quizzes.questions')
Model Quiz.php file:
class Quiz extends Model
{
protected $dates = [ 'start_at', 'end_at', 'created_at', 'updated_at', 'deleted_at'];
protected $fillable = [
'title', 'category_id', 'level_id', 'is_active', 'start_at', 'end_at'
];
public function questions(){
return $this->belongsToMany('App\Question');
}
}
Model Question.php file:
class Question extends Model
{
protected $dates = ['created_at', 'updated_at', 'deleted_at'];
protected $fillable = [
'title', 'correct_answer', 'category_id', 'level_id'
];
public function quiz(){
return $this->belongsTo('App\Quiz');
}
}
Controller AdminQuizzesController.php file:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Quiz;
class AdminQuizzesController extends Controller
{
public function questions($id)
{
$quiz = Quiz::findOrFail($id);
$questions = $quiz->questions;
return view('admin.quizzes.questions.index', compact('quiz', 'questions'));
}
}
the answer of #MazinoSUkah solved my problem.
just did 'composer dump-autoload' in my cmd
AFAIK composer dump-autoload regenerates the list of all classes that need to be included in the project (autoload_classmap.php). Ideal for when you have a new class inside your project or changed/renamed a class file. Hope it helps.
Related
hi im using laravel 8 and im trying to do some code after create or update
like if model has create set created_by = Auth::user()->id ect
and this is my model code
<?php
namespace App\Models;
use Helper;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Notifications\Notifiable;
use Auth;
use App\Models\User;
use Spatie\Activitylog\Traits\LogsActivity;
class Account extends Model
{
use Notifiable,SoftDeletes,LogsActivity;
protected static $logAttributes =
[
'number',
'name',
'foreign_name',
'main_account_id',
'user_id',
'account_state_id',
'note',
'balance_limit',
'approved_state_id'
];
protected static $logName = 'accounts';
protected static $logAttributesToIgnore = [ 'updated_at'];
protected $table = 'accounts';
protected $fillable =
[
'number',
'name',
'foreign_name',
'main_account_id',
'user_id',
'account_state_id',
'note',
'approved_state_id',
'balance_limit',
'created_by','deleted_by'
];
public static function boot()
{
parent::boot();
self::creating(function($model){
$model->created_by = Auth::user()->id; // this code work
});
static::updating(function ($model) {
dd('asdf'); // this not working
});
self::deleting(function($model){
dd($model); // this not working
});
self::restoring(function($model){
dd($model); // this not working
});
}
}
now the code in
static::updating(function ($model) {
dd('asdf'); // this not working
});
is not working when i update any account also in delete and restore
the dd('asdf'); not working
any help here thanks ..
Please try to override the booted method instead of boot. It is an update from laravel 7.
protected static function booted()
{
static::created(function ($user) {
//
});
}
Check the official documentation on Using Closures
I have three tables: events - admins - dependencies
The relationship between them is the following:
a dependency has many admins, an admin has many events
like that:
I'm trying to show the name of the dependency to which the admin that created the event belongs.
How could I bring data with Laravel from this three tables?
controller:
class WelcomeController extends Controller
{
public function evento($slug){
$event = Event::where('slug', $slug)->first();
return view('evento', compact('event'));
}
Event model:
class Event extends Model
{
protected $fillable = [
'admin_id', 'place_id', 'name', 'slug', 'excerpt', 'body', 'status', 'file'
];
public function admins(){
return $this->belongsTo('App\Admin', 'admin_id');
}
Admin model:
protected $fillable = [
'name', 'email', 'password', 'cargo', 'dependence_id'
];
public function dependencyAdmin(){
return $this->belongsTo(Dependence::class);
}
Dependence Model:
class Dependence extends Model
{
protected $fillable = [
'name', 'slug'
];
public function adminsDependence(){
return $this->hasMany(Admin::class);
}
So I try to show it in the view, but it does not work:
<div class="panel-heading">
Dependencia:
{{$event->admins->dependencyAdmin->name}}
</div>
The problem is that you're only retrieving the event model without loading the relationship. See here for more explanation
$event = Event::where('slug', $slug)->first();
$eventAdmins = $event->admins()->get();
$eventAdminDependency = $eventAdmins->dependencyAdmin()->get();
I am using Laravel 5.3 and this model:
namespace App\Models;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Storage;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
use SoftDeletes;
protected $table = 'categories';
protected $fillable = [
'name',
'slug',
'description',
'thumbnail',
'parent',
'created_by'
];
protected $hidden = [
'created_by'
];
protected $dates = ['deleted_at'];
public static function getSubcategories($category)
{
return Category::whereParent(Category::whereSlug($category)->first()->id)->get();
}
}
It works perfectly on my localhost server, but when I upload it on my production server, it outputs following error:
Trying to get property of non-object (on line ....)
It is on this line:
return Category::whereParent(Category::whereSlug($category)->first()->id)->get();
(Lines are hidden, because this model has much more functions and would be too long for this post)
Full trace:
its because the Category::whereSlug($category)->first() is returning null and that you are trying to get id of that null. so its as the error states that you are trying to get a property of non object.
I see that you are trying to get self reference category. you could so it this way as a relationships.
//children
public function categories()
{
return $this->hasMany(self::class, 'parent');
}
//parent
public function parent()
{
return $this->belongsTo(self::class, 'parent');
}
if you want to select recursively you could add this too.
public function parentRecursive()
{
return $this->parent()->with('parentRecursive');
}
public function categoriesRecursive()
{
return $this->categories()->with('categoriesRecursive');
}
im new to Laravel and have a relationship question.
The goal is to get all News where news.page_id = page.id AND page.pagetype_id = pagetype.id WHERE pagetype.component = news AND page.app_id = 1
class News extends Model
{
protected $table = 'news';
protected $fillable = ['page_id', 'title', 'description', 'active', 'created_at', 'updated_at'];
}
class Page extends Model
{
protected $table = 'pages';
protected $fillable = ['app_id', 'unique_id', 'pagetype_id', 'title', 'picture_url', 'short_description', 'description', 'valid_since', 'valid_until', 'extras', 'active', 'created_at', 'updated_at'];
public function pagetype() {
return $this->belongsTo('App\Models\PageType', 'pagetype_id');
}
}
class PageType extends Model
{
protected $table = 'pagetypes';
protected $fillable = ['pagetype', 'component', 'active', 'created_at', 'updated_at'];
public function page() {
return $this->belongsToMany('App\Models\Page', 'pagetypes', 'id', 'id');
}
}
// now i need All News Items where page.pagetype_id = pagetypes.id and patchtypes.component = news
// First Attempts are
Page::whereHas('pagetype', function ($q) {
$q->where('component', 'news');
})->where(['app_id' => 1])->get();
// result is all Pages which has the proper component news.
This is what i have tried yet, but in my attempt i'll only receive the proper pages but of course not the news.
My "current" solution is to get all the pages and then loop through News::where('page_id', $myPageId). But im pretty sure its possible to get a proper relationship to get also news.
I cant do any other model since there are many different pagetypes and components aswell.
Thanks so far.
You need to add relationship function to news model.
public function pages() {
return $this->belongsTo('App\Models\Page');
}
And call it through News model.
News::with('pages')->where('app_id',1);
First off all I think that you are wrong with you PageType relation
class PageType extends Model
{
protected $table = 'pagetypes';
protected $fillable = ['pagetype', 'component', 'active', 'created_at', 'updated_at'];
public function page() {
return $this->hasMany('App\Models\Page');
// if i understood you correctly you haven't got any pivot table
}
}
Then you should link your News and Page like so
News.php
class News extends Model
{
protected $table = 'news';
protected $fillable = ['page_id', 'title', 'description', 'active', 'created_at', 'updated_at'];
public function page() {
return $this->belongsTo('App\Models\Page');
}
}
Page.php
class Page extends Model
{
protected $table = 'pages';
protected $fillable = ['app_id', 'unique_id', 'pagetype_id', 'title', 'picture_url', 'short_description', 'description', 'valid_since', 'valid_until', 'extras', 'active', 'created_at', 'updated_at'];
public function pagetype() {
return $this->belongsTo('App\Models\PageType');
}
public function news() {
return $this->hasMany('App\Models\News');
}
}
Then you can achieve your goal
News::whereHas('page', function($q) use($appId) {
$q->where('app_id',$appId);
})->whereHas('page.pagetype', function($q) {
$q->where('component', 'news');
})->get();
I wan't to get the name of the user who created is own thread. Like Michael did a thread about food. So at the bottom of the food-thread should be the name of Michael.
I've wrote the code for this but it doesn't really works. Maybe someone of you can find the mistake.
I have two models. A thread Model and a users model.
thread model:
<?php
namespace App\Models\Thread;
use Illuminate\Database\Eloquent\Model;
use App\User;
class Thread extends Model {
public $table = 'thread';
public $fillable = [
'thread',
'content',
'user_id'
];
public function userthread() {
return $this->belongsTo('User','user_id', 'id');
user model:
<?php
namespace App;
use ...
protected $table = 'users';
protected $fillable = ['name', 'email', 'password'];
protected $hidden = ['password', 'remember_token'];
public function threaduser() {
return $this->hasMany('App\Models\Thread\Thread','user_id', 'id');
}
}
and now the controller method, where I'm trying to get the name:
public function show($id)
{
$thread = Thread::query()->findOrFail($id);
$threaduser = Thread::where('user_id', Auth::user()->id)->with('userthread')->get();
return view('test.show', [
'thread' => $thread,
'threaduser' => $threaduser
]);
}
in my html:
{{$threaduser->name}}
The error message I get is :
Undefined property: Illuminate\Database\Eloquent\Collection::$name (View: /var/www/laravel/logs/resources/views/test/show.blade.php)
I hope someone can help me there.
change it to
{{$threaduser->userthread->name}}
change userthread() function in your Thread Class to
public function userthread() {
return $this->belongsTo('App\User','user_id', 'id');
}
get() gives you a Collection not a Model you either have to do a foreach on it like
#foreach ($threadusers as $threaduser)
{{ $threaduser->userthread->name }}
#endforeach
Or use first instead of get if there is only one Thread per User.
Depending on what you want to do, of course.