Controller:, and I suspect there could be something wrong here ‘user_id’=> request()->user()->id , and I tried numerous ways for this approach like auth()->id, Auth::user()->id
If I click on post button I get the above error,tried my best to solve this problem but I couldn’t. Can someone help me what’s wrong with my code ?. My question may look naive as I’m new to stackoverflow community
While trying to create fake posts on laravel 8, I met with some errors, first it wasn’t creating the posts, then I changed the username to nullable and it created it but I keep having; Attempt to read property «username» on null So, I went back to my database and I changed it back to none, but I still receive the same error code, I will post my codes now. index.blade.php
Laravel Relation «Attempt to read property on null» Error: 4 Possible Solutions
When using a relationship, have you ever seen an error like «Attempt to read property on null»? Another similar one is «Trying to get property ‘xyz’ of non-object».
It usually means that the related record is NULL or soft-deleted. There are multiple ways to gracefully handle such a situation, without showing the error to the user.
A practical example would be a list of Posts with belongsTo relation to Categories.
Now, have you noticed that migration says the category_id field is nullable() ?
So yeah, the code of $post->category->name would throw the error in that case:
Attempt to read property «name» on null
What are our options to handle this nullable field?
Option 1. ‘??’ Operator in Blade
It’s a PHP so-called «Null Coalescing Operator», I have a separate YouTube video about them.
Instead of the empty string, you may provide any value you want:
$post->category->name??'No category'>>
Option 2. optional() in Blade
A similar fix comes not from PHP but from the Laravel layer, in the form of optional() helper.
It will show the empty string for the name, without throwing any errors.
It acts almost the same as the Null Coalesce Operator above, with the slight difference of intention how you use it. You can read more in this Laravel News article.
Option 3. PHP 8: Nullsafe Operator
A newer addition to PHP language is an operator that allows us to call the chained objects or even methods, without being afraid of them returning null.
As Brent points out in his article on the Nullsafe Operator, PHP 8 allows you to write this:
So, in our case, we can have a one-character solution!
It will also return an empty string, without errors.
Option 4. withDefault() in Model
All the options above work on the Blade level, or wherever you present that relationship. But what if you call it multiple times in different parts of the codebase, and you want to define that relation behavior once, instead, by providing some default values?
You can add a default «fallback» model inside of the related method.
Then, in case of the related model not existing, Eloquent will artificially create an empty model of Category. It would then not trigger the PHP error of «property on null», because the object is not null. It has empty data inside, but not null anymore.
Not only that, you can specify the default values as an array inside of that withDefault() model:
This option is more suitable as a global solution when you don’t want to describe the defaults everywhere you would use it in Blade files or other places in code. Define it once in the Model and kinda forget about it.
I know what the problem is but I couldn’t solve it. When I’m creating a category with the code below no problem. But when I try to create a product it doesn’t updates the category_id so I get this error every time. The code is same for both controllers (product uses category controller’s function) My ProductController.php
$data ]); > /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() < $data = Category::all(); return view('admin.product.create', [ 'data' =>$data ]); > /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) < $data = new Product(); $data->category_id = $request->category_id; $data->user_id = 0; // $request->user_id; $data->title = $request->title; $data->keywords = $request->keywords; $data->description = $request->description; $data->detail = $request->detail; $data->price = $request->price; $data->months = $request->months; $data->status = $request->status; if ($request -> file('image')) < $data->image = $request->file('image') -> store('public/images'); > $data->save(); return redirect('admin/product'); > /** * Display the specified resource. * * @param \App\Models\Product $product * @return \Illuminate\Http\Response */ public function show(Product $product,$id) < // $data = Product::find($id); return view('admin.product.show', [ 'data' =>$data ]); > /** * Show the form for editing the specified resource. * * @param \App\Models\Product $product * @return \Illuminate\Http\Response */ public function edit(Product $product, $id) < // $data = Product::find($id); $datalist = Category::all(); return view('admin.product.edit', [ 'data' =>$data, 'datalist' => $datalist ]); > /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Models\Product $product * @return \Illuminate\Http\Response */ public function update(Request $request, Product $product, $id) < // $data = Product::find($id); $data->category_id = $request->category_id; $data->user_id = 0; // $request->user_id; $data->title = $request->title; $data->keywords = $request->keywords; $data->description = $request->description; $data->detail = $request->detail; $data->price = $request->price; $data->months = $request->months; $data->status = $request->status; if ($request -> file('image')) < $data->image = $request->file('image') -> store('public/images'); > $data->save(); return redirect('admin/product'); > /** * Remove the specified resource from storage. * * @param \App\Models\Product $product * @return \Illuminate\Http\Response */ public function destroy(Product $product, $id) < // $data = Product::find($id); if ($data->image)< Storage::delete($data->image); > $data->delete(); return redirect('admin/product'); > >
parent_id == 1) < return $title; >$parent = Category::find($category->parent_id); $title = $parent->title.' > '. $title; return CategoryController::getParentsTree ($parent, $title); > /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() < // $data = Category::all(); return view('admin.category.index', [ 'data' =>$data ]); > /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() < $data = Category::all(); return view('admin.category.create', [ 'data' =>$data ]); > /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) < $data = new Category; $data->parent_id = $request->parent_id; $data->title = $request->title; $data->keywords = $request->keywords; $data->description = $request->description; $data->status = $request->status; if ($request -> file('image')) < $data->image = $request->file('image') -> store('public/images'); > $data->save(); return redirect('admin/category'); > /** * Display the specified resource. * * @param \App\Models\Category $category * @return \Illuminate\Http\Response */ public function show(Category $category,$id) < // $data = Category::find($id); return view('admin.category.show', [ 'data' =>$data ]); > /** * Show the form for editing the specified resource. * * @param \App\Models\Category $category * @return \Illuminate\Http\Response */ public function edit(Category $category, $id) < // $data = Category::find($id); $datalist = Category::all(); return view('admin.category.edit', [ 'data' =>$data, 'datalist' => $datalist ]); > /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Models\Category $category * @return \Illuminate\Http\Response */ public function update(Request $request, Category $category, $id) < // $data = Category::find($id); $data->parent_id = $request->parent_id; $data->title = $request->title; $data->keywords = $request->keywords; $data->description = $request->description; $data->status = $request->status; if ($request -> file('image')) < $data->image = $request->file('image') -> store('public/images'); > $data->save(); return redirect('admin/category'); > /** * Remove the specified resource from storage. * * @param \App\Models\Category $category * @return \Illuminate\Http\Response */ public function destroy(Category $category, $id) < // $data = Category::find($id); if ($data->image)< Storage::delete($data->image); > $data->delete(); return redirect('admin/category'); > >