laravel 8 passing data to redirect url - laravel

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]);

Related

Laravel model function best prickets

im new in Laravel , I have an issue as below
I make in category model query to check is category is exist or not
as below
public function scopeIsExist($query ,$id)
{
return $query->where(['deleted' => 1, 'id' => $id])->orderBy('id', 'DESC')->first();
}
and my controller is
public function edit($id)
{
$dataView['category'] = Category::IsExist($id);
if(!$dataView['category'])
{
return view('layouts.error');
}else{
$dataView['title'] = 'name';
$dataView['allCategories'] = Category::Allcategories()->get();
return view('dashboard.category.edit')->with($dataView);
}
}
my problem is when I use method isEXIST if id not found it not redirect to error page but ween i remove ISEXIST AND replace it as below
$dataView['category'] = Category::where(['deleted' => 1, 'id' => $id])->orderBy('id', 'DESC')->first();
it work well .
can any one help me
That's because local scope should return an instance of \Illuminate\Database\Eloquent\Builder. You should remove the first() in the scope and put it in the controller.
Redefine your scope like so:
public function scopeIsExist($query ,$id)
{
return $query->where(['deleted' => 1, 'id' => $id])->orderBy('id', 'DESC');
}
In your controller edit method:
$dataView['category'] = Category::IsExist($id)->first();
You can have a look to the doc for local scopes https://laravel.com/docs/8.x/eloquent#local-scopes

Laravel how to pass request from controller to resource collection?

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');

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 pass a parameter in routes to the controller?

I am trying to refactor my code. If I could pass an argument in the routes page to the controller where the function is, then I could refactor many of function that are almost identical.
Something like this in Router:
Route::get('/entrepreneurs', 'HomeController#show')->withParameter('enterpreneur');
Which gives me something like this in Controller:
public function entrepreneurs($withParameter){
$entrepreneurs = DB::table('stars')->where('type', '=', $withParameter)->get();
return view('entrepreneurs', [
'entrepreneurs' => $entrepreneurs,
]);
}
Is this possible?
-------- Update --------
Some of you are suggestion that I use Route Parameters:
Route::get('/entrepreneurs/{paramName}', 'HomeController#show');
However, I already use Route Model Binding to access individual pages (e.g. www.mywebsite.com/entrepreneurs/Mark_Zuckerberg)
So this is a conflicting with the solutions you guys provided!
Routes:
Route::get('/entrepreneurs/{enterpreneur}', 'HomeController#show');
HomeController.php:
public function show($enterpreneur = "")
{
$entrepreneurs = DB::table('stars')->where('type', '=', $enterpreneur)->get();
return view('entrepreneurs', [
'entrepreneurs' => $entrepreneurs,
]);
}
To pass a static variable along with route
Route::get('/entrepreneurs', 'HomeController#show')->defaults('enterpreneur', 'value');
and access them in your controller as
public function show(Request $request)
{
$entrepreneur = $request->route('entrepreneur');
$entrepreneurs = DB::table('stars')->where('type', '=', $enterpreneur)->get();
return view('entrepreneurs', [
'entrepreneurs' => $entrepreneurs,
]);
}
https://laravel.com/docs/5.4/routing#route-parameters
You can also do:
// --------------- routes ---------------------
Route::get("page", [
"uses" => 'HomeController#show',
"entrepreneurs" => "value"
]);
// -------------- controller -------------------
public function show(Request $request)
{
$entrepreneurs = DB::table('stars')->where('type', '=', $request->route()->getAction()["entrepreneurs"])->get();
return view('entrepreneurs', [
'entrepreneurs' => $entrepreneurs,
]);
}
I think you can try this:
Route::get('/entrepreneurs/{enterpreneur}', 'HomeController#show');
public function entrepreneurs($enterpreneur){
$entrepreneurs = DB::table('stars')->where('type', '=', $enterpreneur)->get();
return view('entrepreneurs', [
'entrepreneurs' => $entrepreneurs,
]);
}
Hope this help for you !!!
If you want to pass param in your routes
Route::get('/entrepreneurs/type/{paramName}', 'HomeController#show');
And for an optionnal param :
Route::get('/entrepreneurs/type/{paramName?}', 'HomeController#show');
With optionnal paramater it should look like this in your controller :
public function show($paramName = null){
$entrepreneurs = DB::table('stars')->where('type', '=', $paramName)->get();
return view('entrepreneurs', [
'entrepreneurs' => $entrepreneurs,
]);
}
You can have more information here : https://laravel.com/docs/5.4/routing#route-parameters

Create Relationship inside the create function

I have a model that has a one to many relationship to the versions of the description.
In my Controller
$tag = Tags::create([
'name' => $request->get('name'),
'user_id' => \Auth::id(),
]);
$tag->update([
'content' => $request->get('description')
]);
In my Model:
public function setContentAttribute(string $value)
{
$this->versions()->create([
'user_id' => \Auth::id(),
'value' => $value
]);
}
So I can't put content directly as an attribute in the create method because there is no Model right now.
But is it possible to overwrite the create Method?
When I try to overwrite something like this in my Model it will do an infinity loop
public static function create($attr) {
return parent::create($attr);
}
So my question is if it is possible to have something like this:
$tag = Tags::create([
'name' => $request->get('name'),
'user_id' => \Auth::id(),
'content' => $request->get('content')
]);
and in the Model:
public static function create($attr) {
$value = $attr['content'];
$attr['content'] = null;
$object = parent::create($attr);
$object->content = $value;
$object->save();
return $object;
}
Update
I didn't overwrite the create method but called it customCreate. So there is no infinity loop anymore and I can pass all variables to the customCreate function that handles the relationships for me.
Solution
After reading the changes from 5.3 to 5.4 it turns out that the create method was moved so you don't have to call parent::create() anymore.
The final solution is:
public static function create($attr) {
$content = $attr['content'];
unset($attr['content']);
$element = static::query()->create($attr);
$element->content = $content;
$element->save();
return $element;
}
I don't see why not and you could probably implement a more general approach? Eg. checking if set{property}Attribute() method exists, if it does - use it to assign a value, if it doesn't - use mass assigning.
Something like:
public static function create($attr) {
$indirect = collect($attr)->filter(function($value, $property) {
return method_exists(self::class, 'set' . camel_case($property) . 'Attribute');
});
$entity = parent::create(array_diff_key($attr, $indirect->toArray()));
$indirect->each(function($value, $property) use ($entity) {
$entity->{$property} = $value;
});
$entity->save();
return $entity;
}
I haven't really tested it but it should work. I use something like this in one of my Symfony apps.

Resources