Eloquent model object not recognized_ laravel course excerice - laravel

Following an online course on Laravel I got stuck, and I do not see what I am doing wrong.
Can anyone see what I am doing wrong?
I have the following code in my project:
web.php
Route::get('/', function () {
return view('welcome');
});
Route::get('/pizzas', 'PizzaController#index');
Route::get('/pizzas/{id}','PizzaController#show');
Pizza.php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Pizza extends Model
{
use HasFactory;
// protected $tabel = 'pizzas';
}
PizzaController.php:
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\Pizza;
class PizzaController extends Controller
{
//
public function index(){
$pizzas = Pizza::all();
return view('pizzas', [
'pizzas'=>$pizzas,
]);
}
public function show($id){
return view('details', ['id'=> $id]);
}
Pizza.blade.php:
<h1> Pizza List </h1>
#foreach($pizzas as $pizza)
<div>
{{ $pizza->$name }} // HERE IS WHERE THE ERROR OCCURS
</div>
#endforeach
Error message:
ErrorException
Trying to get property '' of non-object (View: D:\xxxxxxxxxxx\laravel\pizzahouse1\resources\views\pizzas.blade.php)
http://localhost:8000/pizzas
error in line 21

<h1> Pizza List </h1>
#foreach($pizzas as $pizza)
<div>
{{ $pizza->$name }} // HERE IS WHERE THE ERROR OCCURS
</div>
#endforeach
Why you are using "$name"?
Error says ,
You are calling for a property that doesn't exists in $pizza.
it should be something like following:
{{ $pizza->name }}
If problem still exists just :
dd($pizza);
Then see the results and call the property.
Hope it would help.

Related

I wrote the delete method according to the Laravel documentation, but the data is not deleted

Employees.php file
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
/**
* #method static find($id)
*/
class Employees extends Model
{
use HasFactory;
protected $table = 'employees';
public $timestamps = false;
}
EmployeesController.php
<?php
namespace App\Http\Controllers;
use App\Models\Employees;
class EmployeesController extends Controller
{
public function employees_salaries()
{
return view('director.employees_salaries');
}
public function employees()
{
$employees = Employees::all();
return view('director.employees', ['employees'=>$employees]);
}
public function destroy($id)
{
$employees = Employees::find($id);
$employees->delete();
return redirect('/director.employees')->with('status', 'Your Data is Deleted');
}
}
employees.blade.php file
<from action="/delete/{{$employee->id}}" method="POST">
#csrf
#method('DELETE')
<button type="submit" class="btn btn-delete btn-form me-3">
Delete
</button>
</from>
route.php file
Route::match(['get', 'post'], '/employees', array(EmployeesController::class, 'employees'))->name('employees');
Route::delete('/delete/{id}', array(EmployeesController::class, 'destroy'))->name('delete');
I cleared the cache but have no idea what the problem is. it looks like I wrote the function correctly
p.s version Laravel 9
mySQL 8
phpMyAdmin
Welcome to SO, i think youre not using the variable you assigned the value into,from controller in your blade view. maybe try to make sure you have the right variable or maybe try to use var dump.
try to put this in your controller b4 parsing value to view, to check whether you get the data you wanted or not
dd('$employees');
make sure you use the variable you assigned in your controller to your view
<?php
namespace App\Http\Controllers;
use App\Models\Employees;
class EmployeesController extends Controller
{
public function employees_salaries()
{
return view('director.employees_salaries');
}
public function employees()
{
$employees = Employees::all();
return view('director.employees', ['employees'=>$employees]); //<< here you name the variable 'employees'
}
public function destroy($id)
{
$employees = Employees::find($id);
$employees->delete();
return redirect('/director.employees')->with('status', 'Your Data is Deleted');
}
}
change this variable in view
<from action="/delete/{{$employee->id}}" method="POST"> //<< this one you use '$employee' instead of '$employees'
#csrf
#method('DELETE')
<button type="submit" class="btn btn-delete btn-form me-3">
Delete
</button>
</from>
there might also be other problem, but for now thats what i can point out.
since im also learning.

Eloquent Relationship belongsTo Return Error In Laravel 8

Let's assume, There Is two Table 'empData' & 'district'. 'empData' table contain 'id', 'name', 'empDistrict' ('empDistrict' contain the corresponding id of district) . and 'District' table contain 'id', 'name' of all districts.
Now I want to fetch the student's details including the district name. (Note: In the empDatatable, I contain only district id) How can I achieve this?
My Implementation
My District Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use App\Models\EmpData;
class District extends Model
{
protected $guarded = [];
public function empdistrict(){
return $this->belongsTo(EmpData::class, 'empDistrict', 'id');
}
}
My EmpData Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\EmpData;
use App\Models\District;
class empDataController extends Controller
{
$data= EmpData::all();
return view('frontend.allusermindata',compact(['data']));
}
My Blade file where I show the data
foreach($data as $user){
<p>Name : {{ $user->empName }}</p>
<p>District : {{ $user->empdistrict()->name}}</p>
}
But I get this error
Trying to get property 'name' of non-object
foreach($data as $user){
<p>Name : {{ $user->empName }}</p>
<p>District : {{ $user->empdistrict->name}}</p>
}
Calling the method returns a BelonsTo class instance. Use laravel magic method by calling it as an attribute.
Further on this question, you'll have performance issues down the line, better load the data in the same query.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\EmpData;
use App\Models\District;
class empDataController extends Controller
{
$data= EmpData::with('empdistrict')->get();
return view('frontend.allusermindata', compact(['data']));
}

Custom encryption trait breaks carbon functionality and gives error: The payload is invalid

I'm using a custom encryption trait on my Journal model. I didn't create this code and vaguely understand how it works, but the original code can be found here on this Laracast forum post.
Encryption.php
<?php
namespace App;
use Illuminate\Support\Facades\Crypt;
trait Encryptable
{
public function getAttribute($key)
{
$value = parent::getAttribute($key);
if (in_array($key, $this->encryptable)) {
$value = Crypt::decrypt($value);
return $value;
}
return $value;
}
public function setAttribute($key, $value)
{
if (in_array($key, $this->encryptable)) {
$value = Crypt::encrypt($value);
}
return parent::setAttribute($key, $value);
}
}
Journal.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Journal extends Model
{
use Encryptable;
protected $encryptable = [
'content'
];
protected $fillable = ['content','user_id'];
}
I'm getting two problems:
Call to a member function toRfc822String() on null (View: /Applications/MAMP/htdocs/thought-records/resources/views/journal/index.blade.php)
When I remove toRfc822String() from my blade file it throws this error: The payload is invalid.
Here is the index.blade.php
<div class="card-body">
#if($entries->isEmpty())
<p>There is nothing here!</p>
#else
#foreach($entries as $entry)
<h3>{{ $entry->created_at }}</h3>
<div v-html="markdown('{{ htmlentities($entry->content) }}')"> </div>
<hr>
#endforeach
#endif
</div>
The getAttribute method has to return something. Your method returns void. Every attribute you try to access via the dynamic property, $model->attribute, will be null because of this.

Laravel - hasMany() and belongsTo() not working correctly for me in #foreach loop

I got following error when I try to use this on my page
Trying to get property of non-object
I have two tables:
cvicenis
id
title
body
category_id
categories
id
name
My Cviceni model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Cviceni extends Model
{
public function category()
{
return $this->belongsTo('App\Category', 'id');
}
}
My Category model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
public function cviceni()
{
return $this->hasMany('App\Cviceni', 'category_id');
}
}
My controller:
public function index()
{
$cviceni = Cviceni::all();
return view('excercises.index', compact('cviceni'));
}
My index.blade:
#extends('layouts.app')
#section('content')
<div class="row">
<div class="col-sm-6 col-md-6 col-lg-3">
<h1>Přehled cvičení</h1>
#if(count($cviceni) > 0)
<ul>
#foreach ($cviceni as $c)
<li> {{ $c->category->name }}</li>
#endforeach
</ul>
#else
<h2>There is nothing to display</h2>
#endif
</div><!-- end of column -->
</div><!-- end of row -->
#endsection
If I use in my controller Cviceni::find(1) then I can get the value from $cviceni->category->name
But not when I use a foreach loop.
Can somebody help me please?
In the Cviceni model, I think you set up the foreign key is wrong. Your foreign key in the table is category_id, while you set up the relationship with foreign key is id. Try to replace the category() relationship with follow
public function category()
{
return $this->belongsTo('App\Category', 'category_id');
}
You need to eager load the models if you need them:
public function index()
{
$cviceni = Cviceni::with("category")->get();
return view('excercises.index', compact('cviceni'));
}

Trying to get property of non-object in Laravel Relationship

I have two tables in my database, an Articles table and a Users table. An Article is posted by a user and a foreign key exists called 'created_by' referring to the 'user_id' field in the Users table.
My Laravel models are as follows:
User model
class User extends Model
{
use Notifiable;
protected $primaryKey = 'user_id';
public function articles()
{
return $this->hasMany('App\Article', 'created_by', 'user_id');
}
}
Article Model
class Article extends Model
{
protected $primaryKey = 'article_id';
public function user()
{
return $this->belongsTo('App\User', 'created_by' 'user_id');
}
}
I have a view dashboard which displays all the articles and the name of the person who posted it and their image.
Dashboard Controller
<?php
namespace App\Http\Controllers;
use App\User;
use App\Article;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class DashboardController extends Controller
{
public function index (Request $request)
{
if($request->session()->get('username')) {
$articles = Article::all();
return view('dashboard', compact('articles'));
}
else
return redirect('login');
}
}
And finally the section of my view I'm getting the 'Trying to get property of non-object' error for.
#foreach($articles as $article)
<div class="row">
<div class="col-lg-1"></div>
<div class="col-lg-9">
<div class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-title">{{ $article->title }} </h3>
</div>
<div class="panel-body">
<p>
{{ $article->content }}
<br><br> - {{ $article->user->first_name }}
</p>
</div>
</div>
</div>
<div class="col-lg-1"><center><br><br>
<img src="{{ asset('images/people/$article->user->image') }}" class="img-circle" alt="Person"></center>
</div>
</div><br><br>
#endforeach
It seems to be the $article->user->first_name that I am having trouble with. If I type $article->user alone, the page will load but nothing appears in that area.
Any ideas, I have been searching for solutions for the last two hours.
I think you need to specify that you want users to load with with the articles, like $articles = Article::with('user')->all();
Drop a dd($articles) right before the return statement and you'll see what you're actually dealing with.
$articles = Article::with('user')->get();
Edit
Try to check also if $article->user is null in the view because if there is no user assigned for an article then you will get "trying to get property of non object" error
so give an extra check when you access user's data.
{{ $article->user !== null ? $article->user->first_name : 'User Not Found' }}
Do this for user photo also
Please edit your controller, pls mark as answered thx.
<?php
namespace App\Http\Controllers;
use App\User;
use App\Article;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class DashboardController extends Controller
{
public function index (Request $request, Article $articles)
{
if($request->session()->get('username')) {
return view('dashboard')->with('articles', $articles->all() );
}
else
return redirect('login');
}
}

Resources