Reputation: 2086
This is more of a concept question, so I apologize if it isn't specific enough.
I am coming from a Jquery/AngularJS background; usually I am doing front-end stuff and only work with a back-end sparingly.
I am trying to learn Laravel 5 to expand my skills, but am having trouble conceptually fitting together what I know from Angular with what Laravel is telling me.
I want CRUD functionality to a database using Angular, but I want Laravel to help me get that database from MySQL to JSON so it can be passed.
What I have done is made the following in Laravel:
~Model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Pun extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
public $timestamps = false;
}
~Controller:
namespace App\Http\Controllers;
use App\Pun;
use App\Http\Controllers\Controller;
class PunController extends Controller
{
/**
* Show a list of all available puns.
*
* @return Response
*/
public function index()
{
$puns = Pun::all();
return Response::json($puns->toArray());
}
}
}
~Route:
Route::get('showpunsfromdatabase', function () {
return view('???');
});
The question marks above is where I am having trouble. If I understand it correctly, the controller is supposed to query the database as defined in the model, and output the results as JSON. How do I then direct Angular to this controller so I can get this JSON using the $http
service? Does it have to go in a view that then pulls it in? I don't really want it in a "view", I just want the data (JSON) available to Angular. Am I thinking about this correctly?
My angular controller looks like this:
$scope.punGenerate = function(){
$http.get("???").then(function (response) {$scope.thePunJSON = response.data;});
}
Upvotes: 2
Views: 1448
Reputation: 622
IF you do this:
Route::get('showpunsfromdatabase', function () {
return view('???');
});
You are not calling the controller, you are returning the view directly. To call the controller your route should look like this:
Route::get('showpunsfromdatabase' , [
'as' => 'showpunsfromdatabase.index',
'uses' => 'PunController@index'
]);
Now, from the controller you should load the view including the info returned by the model:
<?php
namespace App\Http\Controllers;
use App\Pun;
use App\Http\Controllers\Controller;
class PunController extends Controller
{
/**
* Show a list of all available puns.
*
* @return Response
*/
public function index()
{
$puns = Pun::all();
return view('???')
->with(['puns' => json_encode($puns)]);
}
}
It's just an example, because I don't know what are you looking for exactly.
Upvotes: 1