Creating a new project with laravel and angularjs

- 1 answer

Ad

I am creating a new project with angularjs and almost my front end job is done.

I am planning for laravel php to interact with my data and use it only for basic operations like fetching data, mailing etc.

Here are my questions.

  1. I plan to take a subdomain, db.mydomain.com where laravel is loaded and the api is referred to that $http call in angularjs. Is this a good practise?

  2. If yes, how do i enable cors request with laravel.

  3. How can i confirm that the $http request is originated only from my website. I assume we can make it via postman too and using postman the users can copy paste the data. How to make it confirm that the laravel main route works only with base url of my website application.

hope i was clear.

Edit 1 After doing as per instructions,i was able to make cors call. But if i use model to collect data from database, its again throwing cors error.

<?php 

 namespace App\Http\Controllers;
 use App\Task;

 class TechnologiesController extends Controller {


public function index()
{
  $technologies = Task::getAll("technologies"); // not working if dont have header in task.php
//$technologies = array("subjects"=>array()); // working. This is without interacting with database.
  $encodedArray = json_encode($technologies);
  echo $encodedArray;
}

}

task.php

use Illuminate\Database\Eloquent\Model;
use DB;

header("Access-Control-Allow-Origin: *"); //using this line solves the cors problem.But i want it to center accesssed

class Task extends Model {

    public static function getAll($tableName){

        return DB::table($tableName)->get();

    }

}

Note : I used to work with laravel 4 and lost my touch. Now i couldnt understand where the model file exactly to be written.

Ad

Answer

Ad
  1. Yup this is good practice. Personally I like the subdomain api.domain.com but it's up to you.
  2. I've used this package for CORS in laravel and it works for me. [Edit: Like @hogan mentioned if you use a subdirectory like /api you won't need CORS to be set up.]
  3. You'll want to implement some kind of authentication. I use JWT. It is very difficult to verify the source with something like HTTP_HOST because it is set by the client and easy to spoof.
Ad
source: stackoverflow.com
Ad