Laravel Controller add content?

0

I'm newbie and would like some help, I have a controller that performs a query.

Controller

$user = $this->user->find('1');    
view('index', compact('user'));

View

@forelse ($user as $u)    
    <h1>{{ $u->name }}</h1>    
@endforeach

In View would need to put some extra field example: active, but would not like to tinker in the database just put a field and access in

{{ $u->ativo }}

I hope it was clear.

To clarify further ...

user was just an example, instead of passing another object to View in Controller would like to change that object and include items in it, let's say I pass user and post instead to make a new foreach .

Instead:

view('index', compact('user'),compact('post'));

Like

view('index', compact('user')); 

Note: user or another example name only.

Instead:

View

<h1>{{ $user->name }}</h1>    

@forelse ($post as $u)    
    <h1>{{ $u->name }}</h1>    
@endforeach

this:

@forelse ($user as $u)    
    <h1>{{ $u->name }}</h1>    
    <h1>{{ $u->Postname }}</h1>  
@endforeach

I hope the explanation is better.

    
asked by anonymous 03.01.2019 / 07:36

1 answer

0

What you're looking for is to scan the posts of a user who has multiple posts. Let's suppose that's it. First: The eloquent can make associations between models through the methods of relationship: link . / p>

Let's consider the following relationship:

user
 -id
 -name
posts
 -id
 -autor_id
 -title

In the User model you need to add this method:

public function posts(){
   $this->hasMany('App\Posts', 'autor_id');
}

And in the Posts model the following method:

public function autor(){
   $this->hasOne('App\User', 'autor_id' , 'id');
}

Now it's easy to do this: controller

 $users = $this->user->all();    
 return  view('index', compact('users'));

view

 @foreach ($users as $user)    
        <h1>{{ $user->name }}</h1>    
        @foreach ($user->posts as $post)        
           <h1>{{ $post->title }}</h1>  
        @endforeach  
  @endforeach

Or the other way around: controller

 $posts = $this->post->all();    
 return  view('index', compact('posts'));

view

 @foreach ($posts as $post)    
     <h1>{{ $post->title }}</h1>    
     <h1>{{ $post->autor->name }}</h1> 
 @endforeach

Or also:

controller

 $posts = $this->user->find(1);    
 return  view('index', compact('user'));

view

 @foreach ($user as $posts)    
    <h1>{{ $user->name }}</h1>
      @foreach ($user->posts as $post)    
        <h1>{{ $post->title }}</h1>
       @endforeach
 @endforeach

Each relationship has a more appropriate method to reallocate these entities. However you have to be very careful about doing this. The leavel adopts some standards to search this information in the database so it may be necessary to manually configure each parameter necessary for the method to work. These methods come from Illuminate\Database\Eloquent\Model and there are many ways to do this.

    
03.01.2019 / 18:29