Laravel how to pass request from controller to resource collection? - laravel

I will pass a parameter in the request. The query won't change. How can I pass the request to SurveyResouce
public function getAllSurveys(\Illuminate\Http\Request $request) {
$surveys = DB::table('surveys')
->select('id', 'survey_name')
->get();
return response()->json([
'error' => false,
'data' => SurveyResource::collection($surveys)
],
}
I want get the request parameters in the resource
public function toArray($request) {
$controller = new SurveyController(new SurveyRepository());
return [
'question' => $request->has('ques') ? $request->input('ques'):'',
];
}

You can try by directly using request() helper function. Like request('parameter');

Related

laravel 8 passing data to redirect url

i have store function for save data to database and i want redirect to another url with passing $invoice variable
this is my store function :
$order = Order::create([
'no' => $invoice,
'spg' => $request->spg,
'nama' => $request->nama,
'hp' => $request->hp,
'alamat' => $request->alamat,
]);
return redirect('invoicelink', compact('invoice'));
this is my route file:
Route::resource('/', OrderController::class);
Route::get('invoicelink/{invoice}', [OrderController::class, 'invoicelink'])->name('invoicelink');
and this is my invoicelink function:
public function invoicelink($invoice)
{
dd($invoice);
}
How to do it? very grateful if someone help to solve my problem. thanks
If you look at the helper function you are calling, I don't think it is what you are looking for.
function redirect($to = null, $status = 302, $headers = [], $secure = null)
{
if (is_null($to)) {
return app('redirect');
}
return app('redirect')->to($to, $status, $headers, $secure);
}
I think what you want is
Redirect::route('invoiceLink', $invoice);
You can also use the redirect function, but it would look like this
redirect()->route('invoiceLink', $invoice);
You can see this documented here https://laravel.com/docs/8.x/responses#redirecting-named-routes
i found the solution:
web.php
Route::get('invoicelink/{invoice}', [OrderController::class, 'invoicelink'])->name('invoicelink');
controller:
public function invoicelink($invoice)
{
//dd($invoice);
return $invoice;
}
then use redirect:
return redirect()->route('invoicelink', [$invoice]);

Call to a member function move() on null when update in laravel

I got this errror when trying to update data. If I update the image there's no error, but if I'm not it showing Call to a member function move() on null
This is my code:
public function update($id, Request $request)
{
$change = Profile::findorfail($id);
$before = $change->foto_profil;
$profile = [
'fullname' => $request['fullname'],
'phone' => $request['phone'],
'ttl' => $request['ttl'],
'foto_profil' => $before
];
$request->foto_profil->move(public_path().'/image', $before);
$change->update($profile);
return redirect('/profil');
}
You may determine if a file is present on the request using the hasFile() method :
if($request->hasFile('foto_profil')){
$request->foto_profil->move(public_path().'/image', $before);
}
See the documentation here
just add validation if photo exists in request
if($request->foto_profil) {
$request->foto_profil->move(public_path().'/image', $before);
}

Laravel - request validation

I extedned request class to create my own valdiation rules. In that class I added my custom validation function. In function I check if tags are pass regEx and I would like to filter tags to remove tags shorter then 2 characters.
And later keep in request only tags that passed validation.
public function createPost(PostRequest $request)
{
dd($request->all()); //In this place I would like to keep only tags passed through validation not all tags recived in request
}
Is it possibile to do it? How to set it in Request class?
'tags' => [
'nullable',
'string',
function ($attribute, $value, $fail){
$tagsArray = explode(',', $value);
if(count($tagsArray) > 5) {
$fail(__('place.tags_max_limit'));
}
$tagsFiltered = [];
foreach ($tagsArray as $tag){
$tag = trim($tag);
if(preg_match('/^[a-zA-Z]+$/',$tag)){
$tagsFiltered[] = $tag;
};
}
return $tagsFiltered;
}
],
EDIT:
I think we miss understanding. I would like to after validation have only tags that returned in variable $tagsFiltered; Not the same as recived in input.
You have to create this custom regex rule and use it into rules() function.
Like so:
public function rules()
{
return [
'tag' => 'regex:/[^]{2,}/'
];
}
public function createPost(PostRequest $request)
{
$request->validated();
}
And then just call it via validated() function wherever you want.
first define validation rule with this command:
php artisan make:rule TagsFilter
navigate to TagsFilter rule file and define your filter on passes method:
public function passes($attribute, $value)
{
$tagsArray = explode(',', $value);
$tagsFiltered = [];
foreach ($tagsArray as $tag){
$tag = trim($tag);
if(preg_match('/^[a-zA-Z]+$/',$tag)){
$tagsFiltered[] = $tag;
};
}
return count($tagsArray) > 5 && count($tagsFiltered) > 0;
}
then include your rule in your validation on controller:
$request->validate([
'tags' => ['required', new TagsFilter],
]);

how to inject a file into http request

i have a test case:
$response = $this->postJson('api/unit/'.$unit->id.'/import',['file' =>Storage::get('file/file.xlsx')]);
$response->assertJsonFragment(['a'=>'b']);
my controller:
public function import(Request $request, Unit $unit)
{
$this->validate($request, [
'file' => 'file|required_without:rows',
'rows' => 'array|required_without:file',
'dry_run' => 'boolean',
]);
if ($request->has('rows')) {
//
} else {
$results = $request->file('file');
}
return "ok";
}
but i think my test case is wrong,because when i dd($reuqest->file('file')) in my controller, it return null.
So, how can i request file into my controller.
please help
You can use UploadFile like this:
$fileName= 'file.png';
$filePath=sys_get_temp_dir().'/'.$fileName;
$mimeTypeFile=mime_content_type($filePath);
$file=new UploadedFile($filePath, $fileName, $mimeTypeFile, filesize('$filePath'), null, true)
$response = $this->postJson('api/unit/'.$unit->id.'/import',['file' =>$file]);
$response->assertJsonFragment(['a'=>'b']);
with null is The error constant of the upload, true is test mode
more detail for Symfony UploadedFile, read this
As mentioned in this https://laravel.com/docs/5.4/http-tests#testing-file-uploads.
Try something like this. Import use Illuminate\Http\UploadedFile;
UploadedFile::fake()->create('file.xlsx', $size);
Storage::disk('file')->assertExists('file.xlsx');

How To Create Conditional for Unique Validation (UPDATE/PATCH) on Form Request

I'm trying to get my controller cleaner by moving 'validation request' into a form request called 'BookRequest'.
The problem is on the update process, I try to create a condition to check, if it PATCH or POST with the following codes
MyRequest.php
public function rules()
{
// Check Create or Update
if ($this->method() == 'PATCH')
{
$a_rules = 'required|string|size:6|unique:books,column2,' .$this->get('id');
$b_rules = 'sometimes|string|size:10|unique:books,column3,' .$this->get('id');
}
else
{
$a_rules = 'required|string|size:6|unique:books,column2';
$b_rules = 'sometimes|string|size:10|unique:books,column3';
}
return [
'column1' => 'required|string|max:100',
'column2' => $a_rules,
'column3' => $b_rules,
'column4' => 'required|date',
'column5' => 'required|in:foo,bar',
'column6' => 'required',
'column7' => 'required',
'column8' => 'required',
];
}
.$this->get('id') it failed, the form still treat the unique on the update.
Controller#update
public function update($id, BookRequest $request)
{
$book = Book::findOrFail($id);
$input = $request->all();
$book->update($request->all());
return view('dashboards.book');
}
Controller#edit
public function edit($id)
{
$book = Book::findOrFail($id);
return view('dashboards.edit', compact('book'));
}
Controller#create
public function create()
{
return view('dashboards.create');
}
Controller#store
public function store(BookRequest $request)
{
$input = $request->all();
$book = Book::create($input);
return redirect('dashboards/book/index');
}
I try the alternative .$book->id, and it throw me an ErrorException Undefined variable: book
Any suggestion? I'm using Laravel 5.2 by the way
You are using book as your route parameter but trying to get with id. try this-
if ($this->method() == 'PATCH')
{
$a_rules = 'required|string|size:6|unique:books,column2,' .$this->route()->parameter('book');
$b_rules = 'sometimes|string|size:10|unique:books,column3,' .$this->route()->parameter('book');
}
Hope it helps :)

Resources