Pass an object to a route parameter without model binding - php

I have a route like this:
Route::post('{object}', 'CommentController#store')->name('store');
And I want to pass an object as argument to my form action like this:
<form action="{{ route('comment.store', $object) }}" method="post" id="comment--form"></form>
Here is the problem
if I pass my query object as you know I will get the id of query object
if I pass something like this: {{ route('comment.store', (new app\anyObject())) }} I will get exception and for some polymorphism reason I can't use model binding because the object could be any object so I'm wondering if there is any solution for my question
PS
I have a polymorphic comment system and I dont know if it's decoration design pattern or not but I want to save comments dynamically via my interface so I want to save comments dynamically like this:
public function store(Request $request, $object)
{
// comments() is an implementation of an interface
$object->comments()->create([
'name' => auth()->check() ? $request->user()->fullName() : $request->name,
'email' => $request->user()->email ?? $request->email,
'comment' => $request->content,
]);
}
But I can't pass an object as argument is there anyway to pass it through route or any other idea or solution?
Thanks.

You can't pass any object array or form-data in the url . you might want to consider doing base64_encode then decode after in your method. This can solve your issue.

Related

Undefined foreach variable laravel

hello guys im having a problem with passing variable from my controller to views, as it does not identify its variable, here is my code:
RegisterController.php
use App\angkatan;
public function index()
{
$select = Angkatan::all();
return view('/auth/register')->with('name', $select);
}
My Route
web.php
Route::get('register', 'RegisterController#index');
and my view
register
#foreach($name as $ps)
#endforeach
the error say
Undefined variable: name (0)
im very thankful if anyone can help
You are just passing the wrong way $select variable to your view.
when you use Illuminate\View\View::with method you should pass an associative array which as key => value pairs
return view('/auth/register')->with(['name' => $select]);
You can also use compact which allows to pass variable which are accessible inside of the scope of your controller to the view and the string passed as argument to that function will be the name of variable accessible inside of the view file
$select = Angkatan::all();
return view('/auth/register', compact('select'));
You can not pass the variable in this way to the view. You have to pass an array in the second parameter of the with() method - it should be something like this:
return view('greeting', ['name' => 'James']);
return view('/auth/register', ['name' => $select]);
you can pass a second massive parameter to the view,
and also in with method, you need to pass massive as I remember.

How to pass two different ID's in a route laravel?

I have a simple app, I need to pass two different ID's id and code_id in a route, here is my solution I have tried so far
view
{{ __('Code') }}
Here is route config
Route::get('settings/code/{id}/{code_id}', ['as' => 'settings.code', 'uses' => 'SettingController#code']);
Here is my function in a controller
public function code($code_id, $id)
{
$settings = Setting::find($code_id, $id);
dd($settings);
return view('pages.settings.code', compact('settings'));
}
Here is the error I get
Missing required parameters for [Route: settings.code] [URI: settings/code/{id}/{code_id}]. (0)
What is wrong with my code?
First you should pass an array as 2nd argument to route() method:
{{ route('settings.code', ['id' => $settings->id, 'code_id' => $settings->code_id]) }}
And note that:
Route parameters are injected into route callbacks / controllers based on their order - the names of the callback / controller arguments do not matter.
So you should swap the arguments of your controller's method:
public function code($id, $code_id)
{
//...
}
I got my solution like this:
Route::match(["get", "post"], "/patient-member-orders/**{patient_id}/{member_id}**", [PathologyController::class, "patientMemberOrders"])->name("pathology-patient-member-orders");
After that we need to pass that name in our route method's second argument as an array in the Key Value pair.
**route("pathology-patient-member-orders", ["patient_id" => $member->patient_id, "member_id" => $member->id])**
Please correct me if I am wrong.
Chinmay Mishra

Pass multiple arguments to route/controller in laravel

I'm trying to pass two variables/arguments from my view through a link
<a href="{{ route('shop.order.test', $id,$form['grouping']) }}"
and call the route
Route::get('ordering/test', 'Shop\OrderingController#testing')
->name('shop.order.test');
And call this function with those two arguments
public function testing($id,$grouping){
}
It doesn't seem to be working though. Is my error in my route or my link call?
If you want to have parameters to be passed into controller's method, you need to define route parameters like this
Route::get('ordering/test/{id}/{grouping}', 'Shop\OrderingController#testing');
then you can have it in controller method:
public function testing($id, $grouping)
To generate route for above definition, the second parameter is the array of params to pass. So it will become
{{ route('shop.order.test', ['id' => $id, 'grouping' => $form['grouping']) }}
To pass parameters in a route use an array with the paramter names as keys:
{{ route('shop.order.test', ['id' => $id, 'grouping' => $form['grouping']]) }}
Laravel Doc

Laravel validate data coming from my own application and database

In a function in my controller I call this:
$item = Item::where('i_id', $Id)->where('type', 1)->first();
$firebaseData = app('firebase')->getDatabase()->getReference('items/'.$Id)->getSnapshot()->getValue();
Then I do a lot of "validation" between the data from the two sources above like:
if ($item->time_expires < strtotime(Carbon::now()) && $firebaseData['active'] == 1) {
return response()->json(['errors' => [trans('api.pleaserenew')]], 422);
}
And since this is not data coming from a user/request I cant use Laravels validate method
I dont want to keep this kind of logic inside my controller but where should I put it? Since part of my data is coming from Firebase I cant setup a Eloquent model to handle it either.
I recommend to receive the firebase data via a method within the model:
public function getFirebaseData()
{
app('firebase')->getDatabase()->getReference('items'/ . $this->i_id)->getSnapshot()->getValue();
}
That way you have the logic to receive the data decoupled from controller logic and moved it to where it makes more sense. Adding a validation method could work similarily within the model then:
public function validateData()
{
$combined = array_merge($this->toArray(), $this->getFirebaseData());
Validator::make($combined, [
'active' => 'in:1',
'time_expires' => 'before:' . Carbon::now(),
]);
}
The caveat with this is that the validation error will be thrown within the model instead of the controller, but that shouldn't really be an issue I don't think.
For any data you have in your application you can use Laravel validation.
You can merge your data and process it using Validator facade like this:
$combinedData = array_merge($item->toArray(), $firebaseData);
Validator::make($combinedData, [
'active' => 'required|in:1',
'time_expires' => 'required|before:' . Carbon::now()->toDateTimeString()
], $customMessageArray);
I think the best place for this code is some kind of service class you will inject to controller or other service class using Laravel dependency injection.

How to pass id value from select list to controller when controller expects an object? laravel-4

I've constructed a select list in a dashboard view, which lists id and name of various components. The data is passed to a controller that makes a view using the passed id to pull up the correct component data for that id. Problem is that the controller is constructed to expect an object from which to get the id, so that when I submit the id from the list, I get a "Trying to get property of non-object" error. (It doesn't matter whether I submit to the route or directly to the controller; I get the same error.) Here's the code:
PagesController (that creates list array for the dashboard):
public function showDashboard()
{
$components = Component::lists('name','id');
return View::make('dashboard', array(
'components'=>$components, ...
));
}
Snippet of source code for the select list:
<form method="GET" action="https://..." accept-charset="UTF-8">
<select id="id" name="id"><option value="2">Component Name</option>...
Components Model:
class Component extends Eloquent {
protected $table = 'components'; ... }
ComponentsController:
public function show($id)
{
$component = $this->component->find($id);
return View::make('components.show', array(
'component'=>$component, ...
));
}
dashboard.blade.php:
{{ Form::open(array(
'action' => 'ComponentsController#show',
'method'=>'get'
)) }}
{{ Form::Label('id','Component:') }}
{{ Form::select('id', $components) }}
{{ Form::close() }}
The same controller code is used for other purposes and works fine, for example, when I pass a specific id from a URL, it accepts that id without an error. So, I know this should be something simple involving the form opening, but I can't figure it out. How can I fix this? Thanks!
It will not work because using get method the url will be like this.
http://laravel/puvblic/show?id=2
and laravel will not accept it , rather it accepts a parameter for function in this way
http:/laravel/puvblic/show/2
A better way to do this would be to make your form method as 'POST' . It would be much safer and better this way. and modify your function as.
public function show()
Then , You can get the id in your controller as
Input::get('id')
EDIT:
To make it simple , try this one:
Route::get('{show?}', function()
{
$id = Input::get('id') ;
echo $id; //This will give you the id send via GET
die();
});
Simply follow the GET method , your form will send a GET request and it will come to this route here you can perform your desired function.
I finally figured out the problem, and the solution:
The problem is that the form should (optimally) be sent as POST (not GET), and therefore not changed from the default value provided by Blade. BUT then the route has to be registered correctly as POST, and that's what I wasn't doing before. So,
dashboard.blade.php:
{{ Form::model(null, array('route' => array('lookupsociety'))) }}
{{ Form::select('value', $societies) }} ...
Route:
Route::post('lookupsociety', array('as'=>'lookup society', 'uses'=>'SocietiesController#lookupsociety'));
SocietiesController#lookupsociety:
public function lookupsociety()
{
$id = Input::get('value'); ... // proceed to do whatever is needed with $id value passed from the select list
}
It works perfectly! The key was changing the method in the route to Route::post() instead of Route::get().
I knew it had to be simple -- I simply hadn't stumbled on the solution before :)

Categories