update function is not working - laravel

I am trying to update my database for a user by this code , but it is not working . there is no change by the way!
public function update( Request $request)
{
$request->user()->tasks()->where('id', '=', $request->id)->update([
'name' => $request->title,
'body' => $request->body,
]);
return redirect('/request');
}

Try code and update database:
App\User::find($request->id)->tasks()->update([
'name' => $request->title,
'body' => $request->body
]);
return redirect('/request');

If you already know the id of the task, make it easy on yourself.
Task::find($request->id)->update([
'name' => $request->title,
'body' => $request->body
]);

Related

How to add id if there's custom validation rule when updating the record in Laravel?

How to add id in stud_num just like in email and username? the codes found in User Controller.
public function update(Request $request, $id)
{
$this->validate($request, [
'first_name' => 'required|max:255|regex:/^([^0-9]*)$/',
'middle_name' => 'nullable|max:255|regex:/^([^0-9]*)$/',
'last_name' => 'required|max:255|regex:/^([^0-9]*)$/',
'contact' => ['required', 'regex:/^(09|\+639)\d{9}$/'],
'course' => 'required',
'role_as' => 'required',
'stud_num' => ['required', 'unique:users,stud_num', 'max:15', new StrMustContain('TG')],
'username' => 'required|alpha_dash|unique:users,username,' . $id,
'email' => 'required|email:rfc,dns|unique:users,email,' . $id
]);
// codes for update
}
Just add id like email and username.
'stud_num' => ['required', 'unique:users,stud_num,'.$id, 'max:15', new StrMustContain('TG')]
you can write it like this:
'stud_num'=>['required',Rule::unique('users','stud_num')->ignore($id),'max:15',new StrMustContain('TG')]

Pagination with many to many relationships

I have products, categories and category_product (pivot) tables in my database.
I want to return the category info and products with pagination in the same response.
I know I can use Product::with('categories')->pagination(20),
but I don't want to attach the category to each product.
What is the proper way to get products belong to a specific category?
I have tried that but I can't get the pagination with that:
$category = Category::where('slug', $slug)->first();
$products = $category->products()->paginate(20);
return response()->json([
'category' => new CategoryResource($category),
'products' => ProductResource::collection($products),
]);
Here is my ProductResource
return [
'id' => $this->id,
'name' => $this->name,
'description' => $this->description,
'code' => $this->code,
'image' => $this->image,
'quantity' => $this->quantity,
'price' => $this->price,
'slug' => $this->slug,
'sort_order' => $this->sort_order,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
'categories' => CategoryResource::collection($this->whenLoaded('categories')),
];
This looks like an issue with the way data is returned from the Collection.
The easiest solution is:
return response()->json([
'category' => new CategoryResource($category),
'products' => ProductResource::collection($products)->response()->getData(true),
]);
You can try as below
$category = Category::where('slug', $slug)
->with('products', function($query) {
$query->paginate(20);
})
->first();
return response()->json([
'category' => new CategoryResource($category),
'products' => ProductResource::collection($category->products),
]);
Hope this is what you are looking for.

mutiple emails controller is not working how do i solve?

i have a problem this controller is not working how can i do? should send mutiple emails how do i solve?
I don't know how to handle it
function submit(Request $request) {
$this->validate($request, [
'email' => 'required|email',
'file' => 'mimes:pdf,doc,docx'
]);
$data = array(
'name' => $request->name,
'cognome' => $request->cognome,
'luogo' => $request->luogo,
'date' => $request->date,
'telefono' => $request->telefono,
'email' => $request->email,
'citta' => $request->citta,
'provincia' => $request->provincia,
'studio' => $request->studio,
'lingua' => $request->lingua,
'livello' => $request->livello,
'lingua2' => $request->lingua2,
'livello2' => $request->livello2,
'file' => $request->file,
'agree' => $request->agree
);
Mail::send('mail', $data, function($message) use ($request,$data){
$message->to('luis#gmail.com', 'luis')->subject('Send mail ' . $request->name);
$message->from($request->email, $request->name);
if($request->hasFile('file')){
$message->attach($request->file('file')->getRealPath(), array(
'as' => $request->file('file')->getClientOriginalName(),
'mime' => $request->file('file')->getMimeType())
);
}
});
Session::flash('success', 'Mail spedita con sucesso');
}
I wish I could solve the problem
any advice? on how to do it?

Laravel Spatie Medialibrary: upload multiple images through REST API

I'm using the Spatie MediaLibrary library in a Laravel application. I want to upload 0 or more photos to my app via a REST API.
I can get it to work when the photo attribute contains 1 file
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'slug' => 'required',
'description' => 'required',
'price' => 'required|integer',
'photo' => 'nullable|file'
]);
$listing = Listing::Create([
'user_id' => auth('api')->user()->id,
'name' => $request->name,
'slug' => $request->slug,
'description' => $request->description,
'price' => $request->price,
]);
// stores the photo
if ($request->hasFile('photo')) {
$listing->addMediaFromRequest('photo')->toMediaCollection('photos');
}
return new ListingResource($listing);
}
The postman request looks as follows:
I know want to change the code so it can handle multiple photos in the request. I'm using the following code in the controller above to do so:
if ($request->hasFile('photo')) {
foreach ($request->input('photo', []) as $photo) {
$listing->addMediaFromRequest('photo')->toMediaCollection('photos');
}
}
and I have changed the attribute to photos[] instead of photo.
The code never goes into the foreach loop even.
Anyone has a hint on how to solve this?
Apparently the Spatie Medialibrary has a function called addMultipleMediaFromRequest. The full code is now
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'slug' => 'required',
'description' => 'required',
'price' => 'required|integer',
'photo' => 'nullable'
]);
$listing = Listing::Create([
'user_id' => auth('api')->user()->id,
'name' => $request->name,
'slug' => $request->slug,
'description' => $request->description,
'price' => $request->price,
]);
if ($request->hasFile('photo')) {
$fileAdders = $listing->addMultipleMediaFromRequest(['photo'])
->each(function ($fileAdder) {
$fileAdder->toMediaCollection('photos');
});
}
return new ListingResource($listing);
}
In Postman, I'm calling it as follows:
documentation reference
I managed to upload multiple files like this:
if($request->file('photos')) {
foreach ($request->file('photos') as $photo) {
$post->addMedia($photo)->toMediaCollection('post');
}
}
Check this out:
https://github.com/spatie/laravel-medialibrary/issues/227#issuecomment-220794240
This code is working for me.
View
<input type="file" name="photo[]" multiple />
ListingController
public function store(Request $request)
{
if ($request->hasFile('photo')) {
$fileAdders = $listing->addMultipleMediaFromRequest(['photo'])
->each(function ($fileAdder) {
$fileAdder->toMediaCollection('photos');
});
}
}

Laravel 5.2 PHPUnit attach() doesn't move file

I have this method to store new user
public function register(CreateUserRequest $request){
$file = $request->file('idcard');
$fileName = rand(0, 99999).$file->getClientOriginalName();
if($request->hasFile('idcard') && $request->file('idcard')->isValid()){
$request->file('idcard')->move("images/idcard/", $fileName);
}
User::create([
'role_id' => 1,
'email' => $request->email,
'password' => $request->password,
'full_name' => $request->full_name,
'address' => $request->address,
'phone' => $request->phone,
'family_name' => $request->family_name,
'family_address' => $request->family_address,
'family_phone' => $request->family_phone,
'idcard' => $fileName,
'status' => 'unconfirmed',
'balance' => 0,
]);
Session::flash('success', 'Please check your email to activate your account.');
return redirect('/register');
}
And I have this unit test
public function testNewUserRegistration()
{
$this->visit('/register')
->type('This is full name', 'full_name')
->type('JL. Mulyorejo 226 D', 'address')
->type('085788884877', 'phone')
->type('Rizky Sugiarto', 'family_name')
->type('JL. Kandangan', 'family_address')
->type('085766669999', 'family_phone')
->attach('/var/www/html/autodealer/images/pics/banner_car.jpg', 'idcard')
->type('mail#yahoo.co.id', 'email')
->type('123456789', 'password')
->type('123456789', 'password_confirmation')
->press('Submit')
->seeInDatabase('users', ['email' => 'mail#yahoo.co.id', 'role_id' => 1, 'balance' => 0, 'status' => 'unconfirmed'])
->seePageIs('/register')
->see('Please check your email to activate your account.');
}
If I test my function via browser, it successfuly input database and move file.
But when I test via PHPUnit it pass the test, successfully input database but the image doesn't move.
Is there something wrong with my attach() or something else wrong?
Thanks, any help appreciated.

Resources