Best practice for displaying data in Laravel view

advertisements

What is the best practice, for example to show user data?

  1. Retrieve user in show function inside UserContoller, and pass user variable to the view?

  2. Return view in show function, passing the $user_id, and retrieve the user on the view?

Example 1:

public function show($id)
{
    $user = User::findOrFail($id);
    return view('config.users.show')->withUser($user);
}

Example 2:

public function show($id)
{
    return view('config.users.show')->withId($id);
}


Views are responsible for data representation.

A view can be any output representation of information, such as a chart or a diagram. Multiple views of the same information are possible, such as a bar chart for management and a tabular view for accountants.

The model directly manages the data, logic and rules of the application.

The third part, the controller, accepts input and converts it to commands for the model or view

Source

You should pass the data to the view. and output there, So your first example is correct one.

Instead of withUser() keep using with(key, value)

Example:

public function show($id)
{
    $user = User::findOrFail($id);
    return view('config.users.show')->with('user', $user);
}

In view:

{{ $user->name }} //assuming user have a name attribute