2015-05-13 22 views
10

Hey ragazzi Sono nuovo in laravel e ho cercato di memorizzare tutti i record di tabella "studente" in una variabile e quindi passare tale variabile a una vista in modo che possa visualizzarli.Passaggio dei dati dal controller per visualizzare in Laravel

Ho un regolatore - ProfileController e dentro che una funzione:

public function showstudents() 
    { 
    $students = DB::table('student')->get(); 
    return View::make("user/regprofile")->with('students',$students); 
    } 

A mio avviso ho questo codice

<html> 
    <head></head> 
    <body> Hi {{Auth::user()->fullname}} 
    @foreach ($students as $student) 
    {{$student->name}} 

    @endforeach 


    @stop 

    </body> 
    </html> 

sto ricevendo questo errore: Variabile non definita: gli studenti (Vedi: regprofile.blade.php)

risposta

11

Puoi dare una prova,

return View::make("user/regprofile", compact('students')); OR 
return View::make("user/regprofile")->with(array('students'=>$students)); 

Mentre, è possibile impostare più variabili qualcosa di simile,

$instructors=""; 
$instituitions=""; 

$compactData=array('students', 'instructors', 'instituitions'); 
$data=array('students'=>$students, 'instructors'=>$instructors, 'instituitions'=>$instituitions); 

return View::make("user/regprofile", compact($compactData)); 
return View::make("user/regprofile")->with($data); 
+0

no, non funziona :( – VP1234

+0

State ottenendo stesso errore? –

+0

Sì, non definito studente variabile – VP1234

0

Prova con questo codice:

return View::make('user/regprofile', array 
    (
     'students' => $students 
    ) 
); 

Oppure, se si desidera passare più variabili in vista:

return View::make('user/regprofile', array 
    (
     'students' => $students, 
     'variable_1' => $variable_1, 
     'variable_2' => $variable_2 
    ) 
); 
6

Per passare una singola variabile da visualizzare.

componenti interni del controller di creare un metodo come:

function sleep() 
{ 
     return view('welcome')->with('title','My App'); 
} 

nel percorso

Route::get('/sleep', '[email protected]'); 

Secondo lei Welcome.blade.php. È possibile eco la variabile come {{ $title }}

per una serie (più valori), il cambiamento di metodo di sonno a:

function sleep() 
{ 
     $data = array(
      'title'=>'My App', 
      'Description'=>'This is New Application', 
      'author'=>'foo' 
      ); 
     return view('welcome')->with($data); 
} 

È possibile accedere a voi variabile come {{ $author }}.

-1

Penso che passare i dati dal controller alla vista sia negativo. Perché non è riutilizzabile e rende il controller più grasso. La vista dovrebbe essere separata in 2 parti: template e helper (che possono ottenere dati da qualsiasi luogo). Puoi cercare view composer in laravel per avere maggiori informazioni.

Problemi correlati