Record a small problem associated with the model in laravel

  • When I was looking at the code, I suddenly thought of a problem that I didn't want to understand before, but just now, suddenly, it was suddenly bright, hahaha, the code is as follows:
public function index(Request $request)
{
	return view('user_addresses.index', [
	    'addresses' => $request->user()->addresses,
	]);
}
  • There is such a method in the controller, for the following $request->user()->addressespart is like this:
    • First $request->user(), get the model of the current login object.Since the addressesmethod and addressmodel association have been defined in the user model, if you want to get the address of the login object at this time, you can directly$request->user()->addresses
    • The previous question was, if you want to get the address, why not request addressit directly , just wanted to understand, because what you want is the address of the current login object.
  • There is a small problem here:
    • Why that $request->user()->addresses's addressesbehind it does not need parentheses?
    • It Useris a method when it is defined in the model
    public function addresses()
    {
        return $this->hasMany(UserAddress::class);
    }
    
    • Look at the documentation:
    • Insert picture description here
    • Because it is addressesaccessed as a dynamic attribute here, there is no need to add
Published 145 original articles · Like 38 · Visits 170,000+

Guess you like

Origin blog.csdn.net/yehuaner33/article/details/105474801