Laravel Resource is empty - laravel

I'm passing data to these functions via Axios/Vue. The Eloquent interactions work perfectly. When I store (i.e. create a new call) the resource returns as expected. When I update a record, it updates in the database, however, I get a blank response. In other words the return new CallResource($call) returns nothing. I can't work out where I've gone wrong.
public function store(Request $request)
{
$call = $this->validate($request, [
'title' => 'required',
'job_id' => 'required',
'location' => 'required',
'starts' => 'required|date|before:ends',
'ends' => 'required|date|after:starts',
'rate' => 'required'
]);
$call = Call::create($call);
return new CallResource($call);
}
public function update(Request $request, $id)
{
$data = $this->validate($request, [
'title' => 'required',
'job_id' => 'required',
'location' => 'required',
'starts' => 'required|date|before:ends',
'ends' => 'required|date|after:starts',
'rate' => 'required'
]);
$call = Call::find($id);
$call->update($data);
return new CallResource($call);
}
The call resource is really simple
class CallResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'location' => $this->location,
'starts' => $this->starts,
'ends' => $this->ends,
'rate' => $this->rate
];
}
}
Laravel 5.6 fyi.

Related

Laravel Resource return value from another Resource?

I tried to find a solution here but nothing worked. I want to return values from TagResource using MealResource because I have TagTranslations table and I'm getting the data from the table with translations in TagResource.
Relationships are correctly formed, meal and tag models are connected via meal_tags table and tagtranslations belongsTo Tag::class.
I used TagResource like this:
class TagResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
*/
public function toArray($request)
{
$translation = $this->translations->where('tag_id', $this->id)->first();
return
[
'id' => $this->id,
'title' => $translation->title,
'slug' => $translation->slug,
];
}
}
and MealResource like this:
public function toArray($request)
{
$translation = $this->translations->where('meal_id', $this->id)->first();
$category_translation = $this->category->translations->where('category_id', $this->category->id)->first();
return [
'id' => $this->id,
'title' => $translation->title,
'decription' => $translation->description,
'category' => [
'id' => $this->category->id,
'title' => $category_translation->title,
'slug' => $category_translation->slug,
],
'tags' => FILL IN THE BLANK (have used TagResource:collection() and new TagResource()) and didnt work
];
}
public function toArray($request)
{
$translation = $this->translations->where('meal_id', $this->id)->first();
$category_translation = $this->category->translations->where('category_id', $this->category->id)->first();
return [
'id' => $this->id,
'title' => $translation->title,
'decription' => $translation->description,
'category' => [
'id' => $this->category->id,
'title' => $category_translation->title,
'slug' => $category_translation->slug,
],
'tags' => TagResource::collection($this->tags),
];
}
If all the Relationships namings/mappings are correct then this will work.And please make sure that model are perfectly mapped respectively.

Laravel MM sync throws Illuminate\Database\Eloquent\Relations\HasOne exception

I try to save many to many relations inside loop here is the code
$user = User::firstOrCreate(
[
'username' => $member->username,
'email' => $member->email
],
[
'password' => $member->password,
'name' => $member->fullname,
'email' => $member->email,
'firstname' => $member->firstname,
'lastname' => $member->lastname,
'username' => $member->username,
'active' => $member->active
]
);
if ($user) {
$user->account()->firstOrCreate([
'user_id' => $user->id,
],
[
'address' => $member->address,
'phone' => $member->phone,
'web' => $member->web,
'company' => $member->company,
'company_email' => $member->company_email,
'company_phone' => $member->company_phone,
'fax' => $member->fax,
'company_fax' => $member->company_fax,
'has_newsletter' => $member->newsletter,
'published' => $member->listing,
'zip' => $member->zip,
'association_id' => $member->association_id,
'affiliate_id' => $member->affiliate_id,
]);
if ($member->activity_group_ids) {
$user->account()->occupations()->snyc(explode(',',$member->activity_group_ids));
}
$user->assignRole('member');
}
but I keep getting Call to undefined method Illuminate\Database\Eloquent\Relations\HasOne::occupations()
my models:
User
/**
* #return HasOne
*/
public function account()
{
return $this->hasOne(Member::class);
}
Member
/**
* #return BelongsTo
*/
public function user()
{
return $this->belongsTo(User::class);
}
/**
* #return BelongsToMany
*/
public function occupations()
{
return $this->belongsToMany(OccupationGroup::class, 'members_occupational_groups', 'member_id', 'occupation_group_id');
}
OccupationGroup
/**
* #return BelongsToMany
*/
public function members()
{
return $this->belongsToMany(Member::class, 'members_occupational_groups', 'occupation_group_id', 'member_id');
}
What is wrong in this case?

Route [dealer] not defined. in laravel?

I defined my route but it is not showing that Route [dealer] not defined.
Route::resource('/dealer', DealerController::class);
This is my controller where there is index, create and store method is in same page.
public function index()
{
$users = User::all();
return view('dealer', compact('users'));
}
public function create()
{
$dealers = Dealer::all();
return view('dealer', compact('dealers'));
}
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'email' => 'required',
'password' => 'required',
'name_of_firm' => 'required',
'address' => 'required',
'number' => 'required',
]);
$user = User::create([
'name' => $request->input('name'),
'email' => $request->input('email'),
'password' => Hash::make($request->input('password')),
'name_of_firm' => $request->input('name_of_firm'),
'address' => $request->input('address'),
'number' => $request->input('number'),
]);
return redirect()->route('dealer')->withSuccess('done');
}
https://laravel.com/docs/8.x/controllers#actions-handled-by-resource-controller
Look at the example from the documentation. There exists no such route in your ressource controller.
Depending on what you want you either have to use dealer.index, dealer.show or dealer.edit
Normally you would also use the plural form and not the singular form of the word.

Laravel Validation of two combined columns

i am new to Laravel i need some help in validation. i have two fields one is for country code and other is for phone number and they are being stored separately in respective column in database. i want to validate phone number as unique what i want is get phone number (1234567) country_Code(+12) join them as one like (+121234567) and then validate(unique) against db columns country_Code(+12) + phone(1234567). how can i achieve this?
here is my validation rules method for custom form request
public function rules()
{
return [
'first_name' => 'required|string',
'last_name' => 'required|string',
'email' => ['required', Rule::unique('clients')->ignore($this->client)],
'country_code' => 'required',
'phone' => ['required',Rule::unique('clients')->ignore($this->client)],
'receive_video_lessons' => 'required|boolean'
];
}
You could use a custom rule. Try something like this:
public function rules()
{
return [
'first_name' => ['required', 'string'],
'last_name' => ['required', 'string'],
'email' => ['required', Rule::unique('clients')->ignore($this->client)],
'country_code' => ['required'],
'phone' => ['required', new IsValidPhoneNumber($this->country_code, $this->client)],
'receive_video_lessons' => 'required|boolean'
];
}
Then in your custom validation rule:
class IsValidPhoneNumber implements Rule
{
protected $countryCode;
protected $clientId;
public function __construct($countryCode, $clientId)
{
$this->countryCode = $countryCode;
$this->clientId = $clientId;
}
public function passes($attribute, $value)
{
return ! Client::where('country_code', $this->countryCode)
->where('phone', $value)
->where('client_id', '!=', $this->clientId)
->exists();
}
public function message()
{
return 'This :attribute is not valid.';
}
}
You might have to massage it to work but you get the idea.

custom table in user model laravel

I'm using oauth2 and my table users is "coUsers" . I added this in my User Model
App\User
protected $table = 'coUsers';
public function getAuthPassword()
{
return $this->pass;
}
AuthController
public function login(Request $request)
{
$request->validate([
'usuario' => 'required|string|email',
'clave' => 'required|string',
//'remember_me' => 'boolean'
]);
$credentials = [
'usuario' => $request->get('usuario'),
'password' => $request->get('clave'),
];
if(!Auth::attempt($credentials)){
return response()->json([
'message' => 'Unauthorized'
], 401);
}
$user = $request->user();
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->token;
if ($request->remember_me)
$token->expires_at = Carbon::now()->addWeeks(1);
$token->save();
return response()->json([
'access_token' => $tokenResult->accessToken,
'token_type' => 'Bearer',
'expires_at' => Carbon::parse($tokenResult->token->expires_at)->toDateTimeString()
]);
}
public function firstLogin(Request $request)
{
$request->validate([
'usuario' => 'required|string|email|unique:users',
'clave' => 'required|string',
'nuevaClave' => 'required|string'
]);
$user = User::where('usuario', $request['usuario'])
->where('clave', $request['clave'])
->first();
$user->clave = bcrypt($request['nuevaClave']);
$user->first_login = false;
$user->save();
return response()->json([
$user->toArray()
]);
}
Auth login works OK, but I want to use User::where in firstLogin.... I get this error:
Illuminate\Database\QueryException: SQLSTATE[42703]: Undefined column: 7 ERROR: column "usuario" does not exist
LINE 1: select count() as aggregate from "users" where "usuario" = ...
^ (SQL: select count() as aggregate from "users" where "usuario" = xxxxx#gmail.com) in file \vendor\laravel\framework\src\Illuminate\Database\Connection.php on line 669
Look in the users table instead of using the table that I indicated in the model.
You may change 'usuario' => 'required|string|email|unique:users', to 'usuario' => 'required|string|email|unique:coUsers', in your firstLogin method
You may also change this 'unique:users' in validator method inside your App\Http\Controllers\Auth\RegisterController
'email' => ['required', 'string', 'email', 'max:255', 'unique:users']
to
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:coUsers'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}

Resources