Reputation: 2781
How do I retrieve the result array returned from my model :-
$result = DB::select('select title from mainTable');
return $result;
in my controller so that I can pass it to my view :-
$title = "Main Page";
$data = //I want to assign the result to data
$view = View::make('mainpage')->with('data', $data)->with('title', $title);
Upvotes: 0
Views: 15054
Reputation: 554
If I understand your question correctly, you are trying to figure out how to add something to the $data variable and pass it into a View. If you assign something as
$data['result'] = DB::select('select title from mainTable');
return View::make('main page', $data);
You will now be able to access the query results as $result from within your blade template. I would definitely recommend using the ORM so that you can get the entire result in a single query, as in:
// Model /app/models/Main.php
class Main extends Eloquent {
protected $table = 'mainTable';
}
// Controller (within route method)
$data['result'] = Main::find(1);
/* Gets the mainTable result with an id of 1 */
return View::make('page', $data);
// Template /app/views/page.blade.php
<h1>{{ $result->title }}</h1>
<!-- Outputs the title for the result as an H1 HTML element -->
Upvotes: 2
Reputation: 146191
You can simply create a model like this
class Main extends Eloquent {
protected $table = 'mainTable';
}
Then from your controller you can use following code to get all records from mainTable
table:
$title = "Main Page";
$data = Main::get(array('title'))->toArray(); // Or Main::all(['title']);
return View::make('mainpage')->with('data', $data)->with('title', $title);
Update: You can use something like this if you want
class Main extends Eloquent {
protected $table = 'mainTable';
public function scopeGatAllByFieldName($q, $field = null)
{
if(is_null($field)) return $q;
return $q->select([$field]);
}
}
From your controller you may call it like:
$title = "Main Page";
$data = Main::gatAllByFieldName('title')->get()->toArray();
return View::make('mainpage')->with('data', $data)->with('title', $title);
Upvotes: 1
Reputation: 3658
The Laravel docs (http://laravel.com/docs) do a great job of demonstrating how to use the Database and Query Builder modules.
"The select method will always return an array of results." (http://laravel.com/docs/database.)
$data = DB::select('select title from mainTable');
$view = View::make('mainpage')->with('data', $data)->with('title', $title);
I much prefer using Query Builder.
$data = DB::table('mainTable')->select('title')->get();
$view = View::make('mainpage')->with('data', $data)->with('title', $title);
Upvotes: 0