Parameter problems in API (Laravel) routes

Asked

Viewed 98 times

-1

Hello!

I’m starting my studies on api Rest. In my application I can only return the employee data according to the id of the company that it belongs to, however, the api is returning the data independent of the company id that I pass as parameter.

Example:

Route

api/company/company_id/employee/employee_id

If I pass the parameters:

api/company/2/employee/3

It returns me the correct data!

But if I do it:

api/company/qualquercoisa/employee/3

Keeps returning the same data.

How do I limit the route so that only pass the employee data according to the id of the company to which it belongs?

My code:

Controller

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Employee;
use App\Http\Controllers\Controller;



class EmployeesController extends Controller
{

    public function getEmployee(Request $request)
    {


        return Employee::findOrFail($request->employee_id); 

    }


}

Model

class Employee extends Model
{
      protected $fillable = [
        'name',
        'position',
        'email',
        'phone',
        'admission',
        'company_id'
    ];

   

      public function company(){
         return $this->belongsTo('App\Company','company_id','id');
    }

  
}

Route


Route::get('api/company/{company_id}/employee/{employee_id}','EmployeesController@getEmployee');

1 answer

0


Guy the Laravel has a way of using regex to restrict routes, one way to do this is by adding a Where:

Route::get('user/{id}',SomeController@someFunction)->where('id', '[0-9]+');

This is advisable as it decreases the chances of passing data in unwanted formats.

As for your question of only passing the employee information if it is from the informed institution, it is something that should be dealt with in your Controller, checking whether the employee institution is equal to the data reported in the URL. An example of this would be:

$employee = Employee::findOrFail($request->employee_id);
if($employee->company_id == $request->company_id)
   return $employee;
abort(404);

Note that I used an Laravel error release stating the 404 non-existent page error, other types of errors can be launched.

References

Regular Expression Constraints

HTTP Exceptions

  • Thank you very much! That’s right, besides having solved, your code clarified a logic that I thought I understood, but I was thinking in the wrong way! @Luanmichel

  • Show!! If you can mark the answer as accepted, then your question is answered. @Lucasmoore

  • yes, I just freaked out! Thanks! @Luanmichel

Browser other questions tagged

You are not signed in. Login or sign up in order to post.