Laravel 8.x - pass pivot table data to mailable - php

I have a platform where students can apply for academic courses. When an application is sent, apart from being saved into the database, it must fire an email with the information of the applicant along with the titles of the applied courses.
An Applicant can apply for many Courses, hence the pivot table Applicant_Course. The Applicant model:
class Applicant extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'fname',
'lname',
'email',
'phone',
'is_student',
];
public function courses()
{
return $this->belongsToMany(Course::class)->withTimestamps();
}
The Mail\ApplicationMail:
public function __construct(Applicant $applicant)
{
$this->applicant = $applicant;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
// return $this->view('view.name');
}
The problem is that I cannot figure out how to pass the Applicant object into the mailable. This is what the applicationMail view looks like:
<tr class="email-row">
<td class="left-column"><b>Email: </b></td>
<td class="right-column email-cell">
<a href="{{ $email }}">
{{ $email }}
</a>
</td>
</tr>
#isset($phone)
<tr>
<td class="left-column"><b>Phone: </b></td>
<td class="right-column">
<td class="right-column subject-text">{{ $phone }}</td>
</td>
</tr>
#endisset
<tr>
#foreach ($applicant->courses as $course)
<div class="application-body-item">
<p>{{$course->title}}</p>
<p>Course Code: {{$course->code}}</p>
<hr>
</div>
#endforeach
</tr>
But the line where it says: '#foreach ($applicant->courses as $course)' returns the error: 'Undefined variable: applicant'.
Here is my ApplicationsController:
$input = $request->all();
\Mail::send('applicationMail', array(
'title' => $input['title'],
'org' => $input['org'],
'fname' => $input['fname'],
'lname' => $input['lname'],
'email' => $input['email'],
'course-check' => $input['course-check'],
'phone' => $input['phone'],
'created_at' => $input['created_at'],
'updated_at' => $input['updated_at'],
), function($message) use ($request){
$message->from(env('MAIL_USERNAME'));
$message->to(env('MAIL_USERNAME'))->subject($request->get('subject'));
});
Any idea how to pass the Applicant's data into the mailable so that I can retrieve the pivot table data (from the Applicant_Course table) just like I do inside a normal view ?

Related

Grab manufacturer logo by 'id' or 'name' and display in table - Laravel 8 - aJax

Morning all.
I have created a vehicle database with somewhat detailed information like engine type, fuel, transmission, manufacturer and so on...
I started out by selecting the logo for each entry and soon realized that I will end up with a folder full of the same logos just named differently by timestamp.
I am therefore trying to create a process of manually uploading all the manufacturer logos into an assets folder then when I input the 'Manufacturer Name' it will use the information to pull the relevant logo from public/storage/assets.
My Vehicle Model
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Vehicle extends Model
{
use HasFactory; /** Name of columns fillable */
protected $table = 'vehicles';
protected $fillable = [
'make',
'model_name',
'version',
'powertrain',
'trans',
'fuel',
'model_year',
'image',
'created_at'
];
};
My VehiclesController
namespace App\Http\Controllers;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Models\Vehicle;
use Illuminate\Http\Controllers;
use Illuminate\Database\Migrations\CreateVehiclesTable;
class VehiclesController extends Controller
{
public function index()
{
return view('index');
}
/** Handle insert */
public function store(Request $request)
{
// print_r($_POST);
// print_r($_FILES);
// // }
$file = $request->file('image');
$filename = time(). '.' .$file->getClientOriginalExtension();
$file->storeAs('public/images', $filename);
// handle insert vehicle ajax request
$vehicle = Vehicle::create(
[
'make' => $request->make,
'model_name' => $request->model_name,
'version' => $request->version,
'powertrain' => $request->powertrain,
'trans' => $request->trans,
'fuel' => $request->fuel,
'model_year' => $request->model_year,
'image' => $filename
]
);
return response()->json($vehicle);
}
// FETCH ALL AJAX REQUEST
public function fetchAll()
{
$vehicles = Vehicle::all(); //Could be model or controller...
$output = '';
if ($vehicles->count() > 0) {
$output .= '<table class="table table-striped table-sm text-center align-middle" >
<thead>
<tr>
<th class="tbl-head">ID</th>
<th class="tbl-head">Image</th>
<th class="tbl-head">Make</th>
<th class="tbl-head">Model</th>
<th class="tbl-head">Derivative</th>
<th class="tbl-head">Powertrain</th>
<th class="tbl-head">Transmission</th>
<th class="tbl-head">Fuel Type</th>
<th class="tbl-head">Model Year</th>
</tr>
</thead>
<tbody>';
foreach ($vehicles as $vehicle) {
$output .= '<tr class="tbl exp_tbl">
<td>'.$vehicle->id.'</td>
<td><img src="./storage/images/'.$vehicle->image.'" class="img-thumbnail justify-content-sm-center rounded-circle"></td>
<td>'.$vehicle->make.'</td>
<td>'.$vehicle->model_name.'</td>
<td>'.$vehicle->version.'</td>
<td>'.$vehicle->powertrain.'</td>
<td>'.$vehicle->trans.'</td>
<td>'.$vehicle->fuel.'</td>
<td>'.$vehicle->model_year.'</td>
<td>
<i class="bi-pencil-square h4"></i>
<i class-"bi-trash h4"></i>
</td>
</tr>';
}
$output .= '</tbody></table>';
echo $output;
} else {
echo '<h1 class="text-center text-secondary my-5">No vehicles in the database!</h1>';
}
}
public function time($time)
{
$time->Carbon::now();
}
}
My Migration file
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateManufacturersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('manufacturers', function (Blueprint $table) {
$table->id('id');
$table->string('manu_logo');
$table->string('manu_name');
$table->timestamps('created_at');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('manufacturers');
}
}
I am under the impression that I will need to generate a new model and use the present VehiclesController to pull the logo from the manufacturers model.
I think I'm getting a little confused and would appreciate any help, if anymore information is needed please dont hesitate to ask
Thanks In Advance
there are several solutions:
a) use manufacturer id to get access to logo;
b) use manufacturer name to provide logo, but in this case you need to load manufacturer relation every time;
c) use image field to provide logo url based on manufacturer when creating Vehicle model (in other variants you don't need image field in Vehicle model or it can be used to provide vehicle photo not the manufacturer logo);
d) upload logo when creating/updating Manufacturer to use it (based on your manufacturer table migration - this is the one you want).
so
a) steps:
upload bunch of logos into public/logo folder with relevant to car manufacturer id like 1.png, 2.png etc in whatever way you want (either manually or with some form with upload request)
in your Vehicle model create getter to get access to logo url
in controller use created in step 2 getter to provide displaying of associated logo
// Vehicle Model
public function getLogoUrlAttribute() {
$path = "logo/$this->make.png";
return Storage::exists($path) ? Storage::url($path) : '';
}
// controller fetchAll() method
...
<td><img src="$vehicle->logo_url" class="img-thumbnail justify-content-sm-center rounded-circle"></td>
...
b) steps:
upload bunch of logos into public/logo folder with relevant to car manufacturer name like wv.png, audi.png etc in whatever way you want (either manually or with some form with upload request)
in your Vehicle model create getter to get access to logo url
in controller use created in step 2 getter to provide displaying of associated logo
// Vehicle Model
public function getLogoUrlAttribute() {
if (!$this->relationLoaded('manufacturer') {
return '';
}
$name = $this->manufacturer-> manu_name;
$path = "logo/$name.png";
return Storage::exists($path) ? Storage::url($path) : '';
}
// controller fetchAll() method
...
<td><img src="$vehicle->logo_url" class="img-thumbnail justify-content-sm-center rounded-circle"></td>
...
c) steps:
upload bunch of logos into public/logo folder with relevant to car manufacturer id like 1.png, 2.png etc in whatever way you want (either manually or with some form with upload request)
when creating new vihecle set path to logo into image field
// store() method
/* you don't need this anymore
$file = $request->file('image');
$filename = time(). '.' .$file->getClientOriginalExtension();
$file->storeAs('public/images', $filename);*/
$path = Storage::exists('logo/$request->make.png') ? "logo/$request->make.png" : '';
$vehicle = Vehicle::create(
[
'make' => $request->make,
'model_name' => $request->model_name,
'version' => $request->version,
'powertrain' => $request->powertrain,
'trans' => $request->trans,
'fuel' => $request->fuel,
'model_year' => $request->model_year,
'image' => $path
]
);
// fetchAll() method
...
<td><img src="Storage::url($vehicle->image)" class="img-thumbnail justify-content-sm-center rounded-circle"></td>
...
of make it even better
//Vehicle model
public function getLogoUrlAttribute() {
return Storage::url($this->image);
}
// fetchAll() method
...
<td><img src="$vehicle->logo_url" class="img-thumbnail justify-content-sm-center rounded-circle"></td>
...
d) steps:
when creating Manufacturer you uploading its logo (save it with whatever you want name as it will be tied by path)
get logo url from preloaded manufacturer relation
// ManufacturerController
public function store() {
// create new manufacturer and store provided logo image
}
// Vehicle model
public function manufacturer() {
return $this->hasOne(Manufacturer::class, 'make', 'id');
}
// Manufacturer model
public function getLogoUrlAttribute() {
return Storage::url("logs/$this->manu_logo.png");
}
// vehicle controller
public function fetchAll() {
// note preloading manufacturer relation
$vehicles = Vehicle::with('manufacturer')->get();
...
<td><img src="" . $vehicle->manufacturer->logo_url class="img-thumbnail justify-content-sm-center rounded-circle"></td>
...
}
and just to be sure avoiding n+1 request problem i'd suggest still use getter in Vehicle model for logo
// adding to Vehicle model
public function getLogoUrlAttribute() {
if (!$this->relationLoaded('manufacturer') {
return '';
}
$name = $this->manufacturer->manu_logo;
$path = "logo/$name.png";
return Storage::exists($path) ? Storage::url($path) : '';
}
// fetchAll() method
...
<td><img src="$vehicle->logo_url" class="img-thumbnail justify-content-sm-center rounded-circle"></td>
...
some thoughts about your fetchAll() method:
i'd suggest you to let blade build page for you - this will make controller nice and clear
public function fetchAll() {
// note preloading manufacturer relation
$vehicles = Vehicle::with('manufacturer')->get();
return view('vehicle-index', ['$vehicles'=>$vehicles]);
}
and all html stuff in vehicle-index.blade.php with much more pleasant to work with
<html lang="{{ app()->getLocale() }}">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta name="Pragma" content="no-cache" />
<meta name="Expires" content="0" />
<title>title</title>
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body>
#if ($vehicles->isEmpty())
<h1 class="text-center text-secondary my-5">No vehicles in the database!</h1>
#else
<table class="table table-striped table-sm text-center align-middle">
<thead>
<tr>
<th class="tbl-head">ID</th>
<th class="tbl-head">Image</th>
<th class="tbl-head">Make</th>
<th class="tbl-head">Model</th>
<th class="tbl-head">Derivative</th>
<th class="tbl-head">Powertrain</th>
<th class="tbl-head">Transmission</th>
<th class="tbl-head">Fuel Type</th>
<th class="tbl-head">Model Year</th>
</tr>
</thead>
<tbody>
<tr class="tbl exp_tbl">
<td>{{ $vehicle->id }}</td>
<td><img src="{{ $vehicle->logo_url }}" class="img-thumbnail justify-content-sm-center rounded-circle"></td>
<td>{{ $vehicle->make }}</td>
<td>{{ $vehicle->model_name }}</td>
<td>{{ $vehicle->version }}</td>
<td>{{ $vehicle->powertrain }}</td>
<td>{{ $vehicle->trans }}</td>
<td>{{ $vehicle->fuel }}</td>
<td>{{ $vehicle->model_year }}</td>
<td>
<i class="bi-pencil-square h4"></i>
<i class="bi-trash h4"></i>
</td>
</tr>
</tbody>
</table>
#endif
</body>

How can I bring a session variable into the AuthServiceProvider in this Laravel 8 application?

I am working on a Laravel 8 app with users, roles and permissions. I use Microsoft Azure for user sign-up and sign-in. I began by following this tutorial on their website.
I use a custom middleware in routes\web.php to discriminate authenticated users from guests:
Route::group(['prefix' => 'dashboard', 'middleware' => ['checkSignedIn']], function() {
Route::get('/', [DashboardContoller::class, 'index'])->name('dashboard');
//More routes
});
I get a list of comma-separated user permissions specific to every user role, from a permissions MySQL table.
I store the userPermissions variable in a session like this:
public function storeTokens($accessToken, $user, $user_role, $user_permissions) {
session([
'accessToken' => $accessToken->getToken(),
'refreshToken' => $accessToken->getRefreshToken(),
'tokenExpires' => $accessToken->getExpires(),
'userName' => $user->getDisplayName(),
'firstName' => $user->getGivenName(),
'lastName' => $user->getSurname(),
'userRole' => $user_role,
'userPermissions' => $user_permissions,
'userEmail' => null !== $user->getMail() ? $user->getMail() : $user->getUserPrincipalName(),
'userTimeZone' => $user->getMailboxSettings()->getTimeZone()
]);
}
This alows me to output the current (signed in) user's list of permissions in a view (the navbar.blade.php partial), directly from the session, like this:
#if(session('userPermissions'))
<ul>
#foreach (session('userPermissions') as $up)
<li>{{ $up }}</li>
#endforeach
</ul>
#endif
The goal
My intention (the purpose of creating session('userPermissions')) is to use the user's permissions in Gates. For this purpose, in app\Providers\AuthServiceProvider.php I have:
// More code
use Illuminate\Support\Facades\Gate;
// More code
/* View Users */
Gate::define('view-users', function() {
return in_array('view-users', session('userPermissions'));
});
In the base-controller (app\Http\Controllers\Controller.php) I have imported the Gate facade with use Illuminate\Support\Facades\Gate and then, in users.blade.php
#can('view-users')
<h2>Users</h2>
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Role</th>
</tr>
</thead>
#if ($users)
<tbody>
#foreach ($users as $user)
<tr>
<td>{{ $user->first_name }} {{ $user->last_name }}</td>
<td>{{ $user->email }}</td>
<td>{{ $user->role }}</td>
</tr>
#endforeach
</tbody>
#endif
</table>
#endcan
The problem
Evan if the current user does have the view-users permission (and that is visible in the navbar), the Users table is not present and doing dd(session('userPermissions')) in AuthServiceProvider.php returns null.
Where is my mistake?
Assuming you have Policy & Gate registered in App\Providers\AuthServiceProvider.
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* #var array
*/
protected $policies = [
User::class => UserPolicy::class,
];
/**
* Register any application authentication / authorization services.
*
* #return void
*/
public function boot()
{
$this->registerPolicies();
// this merely maps the name of the gate
Gate::define('view-users', [UserPolicy::class, 'index']);
}
}
CLI command:
php artisan make:policy UserPolicy --model=User
Then in class UserPolicy, you have to implement method index().
One can check in the controller already, before even rendering any Blade template.
For your use case ... see the examples for: Methods Without Models or Guest Users.
It's pointless to depend on session(), when the Gate knows User $user ...

Laravel 8.x - Form checkboxes to pivot table

I am building a platform where students can apply for academic courses.
The students use a form to provide some personal information and then choose at least one course to apply for.
When the form is sent, the ApplicationsController validates the inputs and checks that there is at least one course checked. The controller:
public function student_store(Request $request, Course $course)
{
$request->validate([
'fname' => 'required|string|min:2|max:40',
'lname' => 'required|string|min:2|max:40',
'email' => 'required|email|min:6|max:254',
'course-check' => 'required',
'phone' => 'required|digits:10',
'created_at' => \Carbon\Carbon::now(),
'updated_at' => \Carbon\Carbon::now(),
]);
If the validation is ok, a new Applicant is created in the database using the form inputs:
$input = $request->all();
Applicant::create($input);
However the goal is to also create one or more new instances in the pivot table applicant_course, depending on which one or more courses the student has selected. So far I have this:
$applicant = Applicant::where('fname', $input['fname'] )
->where('lname', $input['lname'] )
->where('email', $input['email'] )
->latest()->first();
$checkboxes = $request->all('course-check');
foreach ($checkboxes as $checkbox){
$applicant->courses()->where('course_id', $checkbox)->attach($course->id);
}
}
However, all that the controller function does, is to validate the inputs and create a new Applicant in the database with their data but nothing is added in the pivot table.
Here is the view structure (ignore the $program variables):
#foreach ($courses as $course)
#if ($course->program_id == $program->id)
<div class="course course-{{$program->id}}-{{$course->id}}">
<div class="course-header">
<label class="course-number" for="course-check-{{$program->id}}-{{$course->id}}">{{$program->id}}0{{$course->id}}0</label>
<label class="course-title" for="course-check-{{$program->id}}-{{$course->id}}">{{$course->title}}</label>
<input type="checkbox" name="course-check[{{ $course->id }}]" class="course-check" id="course-check-{{$program->id}}-{{$course->id}}" value="" >
</div>
</div>
#endif
#endforeach
Here is the Applicant model:
class Applicant extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'fname',
'lname',
'email',
'phone',
];
public function courses()
{
return $this->belongsToMany(Course::class)->withTimestamps();
}
}
Can someone help ?
Thanks in advance!
I think you need to change checkbox name like below
<input type="checkbox" name="course-check[]" class="course-check" id="course-check-{{$program->id}}-{{$course->id}}" value="{{ $course->id }}" >
Then in controller
$checkboxes = $request->get('course-check');
$applicant->courses()->sync($checkboxes);
or
$checkboxes = $request->get('course-check');
$applicant->courses()->attach($checkboxes);
To know difference between attach and sync
Ref:https://laravel.com/docs/8.x/eloquent-relationships#updating-many-to-many-relationships

Laravel Backpack. 1-1 (one-to-one) relation

I have 2 Eloquent models:
/**
* Entities/Products.php
*/
use CrudTrait;
protected $fillable = [
'name', 'macronutrients_id',
];
public function macronutrients()
{
return $this->hasOne(Macronutrients::class);
}
/**
* Entities/Macronutrients.php
*/
use CrudTrait;
protected $fillable = [
'proteins', 'fats', 'carbons', 'calories', 'product_id'
];
public function product()
{
return $this->belongsTo(Product::class);
}
I don't know how I can show table (or something like list of options) with all macronutrients on product's edit page via Laravel Backpack CRUD?
In other words, I want to make something like this:
on page http://example.com/admin/product/2/edit:
* [text] Name
* Macronutrients:
[number] proteins
[number] fats
[number] carbons
[number] calories
where [text], [number] is input fields.
I resolved this with some custom logic. As a result:
Screenshot of my /admin/product/1/edit
First of all, I created custom field:
<!-- /resources/views/vendor/backpack/crud/fields/product_macronutrients.blade.php -->
<!-- product_macronutrients -->
#php($macronutrients = isset($entry) ? $entry->macronutrients : false)
<div #include('crud::inc.field_wrapper_attributes') >
#include('crud::inc.field_translatable_icon')
<div class="array-container form-group">
<table class="table table-bordered table-striped m-b-0">
<thead>
<tr>
<th class="text-center">{{-- <i class="fa fa-trash"></i>--}} </th>
#foreach( $field['columns'] as $column )
<th style="font-weight: 300!important;">
// l10n strings (productscatalog::labels.proteins, productscatalog::labels.fats and so on)
#lang("productscatalog::labels.$column")
</th>
#endforeach
</tr>
</thead>
<tbody ui-sortable="sortableOptions" class="table-striped">
<tr class="array-row">
<td>
<p><b>#lang("productscatalog::labels.macrontr")</b></p>
</td>
#foreach( $field['columns'] as $column)
<td>
<input
class="form-control input-sm"
type="text"
name="{{ $column }}"
value="{{ old($column) ? old($column) : $macronutrients ? $macronutrients->$column : '' }}"
#include('crud::inc.field_attributes')
/>
</td>
#endforeach
</tr>
</tbody>
</table>
</div>
</div>
And ProductCrudController:
public function setup()
{
// other stuff...
$this->crud->addField([
'label' => 'Macronutrients',
'type' => 'product_macronutrients',
'name' => '',
'columns' => [
'proteins',
'fats',
'carbons',
'calories',
],
]);
}
public function store(StoreRequest $request)
{
$redirect_location = parent::storeCrud($request);
$this->storeOrUpdateMacronutrients($request, $this->crud->entry);
return $redirect_location;
}
public function update(UpdateRequest $request)
{
$redirect_location = parent::updateCrud($request);
$this->storeOrUpdateMacronutrients($request, $this->crud->entry);
return $redirect_location;
}
public function destroy($id)
{
$this->destroyMacronutrients($id);
$return = parent::destroy($id);
return $return;
}
protected function storeOrUpdateMacronutrients(Request $request, Product $product)
{
$macronutrients = Macronutrients::firstOrNew(['id' => $product->id]);
$macronutrients->proteins = $request->input('proteins');
$macronutrients->fats = $request->input('fats');
$macronutrients->carbons = $request->input('carbons');
$macronutrients->calories = $request->input('calories');
$macronutrients->save();
}
protected function destroyMacronutrients($productId)
{
$macronutrients = Macronutrients::findOrFail($productId);
$macronutrients->delete();
}
Hope it helps.
$this->crud->addColumn([
// 1-n relationship
'label' => "Country name", // Table column heading
'type' => "select",
'name' => 'country_name', // the column that contains the ID of that connected entity;
'entity' => 'country', // the method that defines the relationship in your Model
'attribute' => "country_name", // foreign key attribute that is shown to user
'model' => "App\Models\Country",
]);
this is an example for 1-n relationship in laravel backpack

I'm trying to fetch data from my api using fetch and it returns blank with no errors

I have created a simple app to display members, basically crud and after setting my api routes and resources,
I'm trying to fetch data from my api using vue as my front end and it returns blank without getting errors. What i'm I doing wrong. The Table displays alright but the data is not being fetched.
This is my code.
<template>
<div>
<table class="table table-condensed">
<tr>
<th>Full Name</th>
<th>Gender</th>
<th>Age</th>
<th>Country</th>
</tr>
<tr v-for="member in members" v-bind:key="member.id">
<td>{{member.name}} {{member.surname}}</td>
<td>
{{member.gender}}
</td>
<td>
{{member.age}}
</td>
<td>
{{member.country}}
</td>
</tr>
</table>
</div></template>
<script>
export default {
data(){
return{
members: [],
member:{
id: '',
name: '',
surname: '',
age: '',
gender: '',
email: '',
country: ''
},
}
},
created(){
this.listMembers();
},
methods:{
listMembers(){
fetch(`api/members`,{
method:'Get'
})
.then(res => res.json())
.then(res => {
this.members = this.data;
})
.catch(err => console.log(err));
},
}
}
</script>
for curiosity sake, this is my backend
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illminate\Http\Response;
use App\Members;
use App\Http\Resources\MembersResource;
class MembersController extends Controller
{
//list all Members
public function index(){
$members = Members::orderBy('id','desc')->paginate(10);
return MembersResource::collection($members);
}
//list a single member
public function member($id){
$member = Members::findOrFail($id);
return new MembersResource($member);
}
public function delete_member($id){
$member = Members::findOrFail($id);
if($member->delete()){
return new MembersResource($member);
}
}
}
and my resource
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class MembersResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'surname' => $this->surname,
'gender' => $this->gender,
'age' => $this->age,
'email' => $this->email,
'country' => $this->country
];
//return parent::toArray($request);
}
}
my api routes
Route::get('/members', 'MembersController#index');
Route::get('/member/{id}', 'MembersController#member');
Route::delete('/member/{id}', 'MembersController#delete_member');
I had to make it res.data since the data is my response api and it worked.

Categories