I'm learning Laravel and have created a single form that is shared by the create and edit controller.
The create controller just returns the view.
public function create()
{
return view('hotels.create');
}
However i've had to put my edit controller and return it in an array
return view('hotels.edit', [
'hotel' => Hotel::with('hotelFacilities')->where('id', $id)->get()
]);
Now in my view I have to pass
$hotel[0]->hotelFacilities->fitness_centre
instead of
$hotel->hotelFacilities->fitness_centre
So now my create view is looking for $hotel where it is now $hotel[0] in the shared view. How can I change this so it's looking at the same reference to the $hotel variable?
If you are using the same view for create and edit, you have to pass the same object for views. change code as below.
return view('hotels.create', [
'hotel' => new Hotel
]);
return view('hotels.edit', [
'hotel' => Hotel::with('hotelFacilities')->where('id', $id)->first()
]);
Related
Im using activeform. In my User model, i initialized a model property Public formType;, set its rule to safe and i am trying to use this property with hiddeninput to create condition in the user controller. But i am getting that the activeform doesn't update the value of the property. Ive read this but i am still unclear whats the workaround of updating the property while still using activeform.
Form
<?= $form->field($model, 'formType')->hiddenInput(['value' => 'userRowUpdate'])->label(false) ?>
User Controller
public function actionUpdate($id) {
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post())) {
$model->scannedFile = \yii\web\UploadedFile::getInstance($model, 'scannedFile');
$type = Yii::$app->request->post('formType');
if ($model->processAndSave()) {
FlashHandler::success("User profile updated success!");
if ($type == "userDetailView") {
return $this->redirect(['view', 'id' => $model->id]);
} else if ($type == "userRowUpdate") {
return $this->redirect(Yii::$app->request->referrer);
}
} else {
FlashHandler::err("User profile updated FAIL!");
}
}
return $this->render('update', [
'model' => $model,
]);
}
Replace the hiddeninput from using activeform to
<?=Html::hiddenInput('name', $value);?>
Reasons:-
code in question is probably not the right approach since its creating a attribute/model property just for the condition in action controller
html input wouldnt affect the model but the data is still readable and be used in the actioncontroller as a condition
You can use
Html::activeHiddenInput($model, 'formType')
to avoid hiding the label and it's shorter.
if the value is not being updated, check your rules in the model. That attribute at least must have a safe rule to be able to be assigned on the $model->load(Yii::$pp->request->post()) call
I would like to pass the user_id on create page.
My controller
public function create($user)
{
$loanAmount=LoanAmount::all()->pluck('amount','id');
$userId=User::where('id',$user)->pluck('id')->first();
// $user->id;
// dd($user);
return view('loan/grant-loan-amounts/create/'.$userId)
->with($userId)
->with($loanAmount);
}
Here's my route
Route::resource('loan/grant-loan-amounts', 'Loan\\GrantLoanAmountsController',[
'except' => ['create']
]);
Route::get('loan/grant-loan-amounts/create/{userId}', 'Loan\\GrantLoanAmountsController#create')->name('grant-loan-amounts.create');
I made the create page blank. with only "asd" to display.
what I want to achieve is that, from user list which is on user folder, I'll pass the user id on grant loan amount create a page. But I can't figure out why the route can't be found.
any suggestion?
Don't pass the id in the first parameter of view() function. Only mention the view file in the first parameter of the view function. Pass all variables with compact() function as the second parameter of view(). Example:
public function create($user)
{
$loanAmount=LoanAmount::all()->pluck('amount','id');
$userId=User::query()->findOrFail($user)->id;
return view('user.create',compact('userId','loanAmount')) //in this example 'user' is the folder and 'create' is the file inside user folder
}
Because you have this route:
Route::get('loan/grant-loan-amounts/create/{userId}', 'Loan\\GrantLoanAmountsController#create')->name('grant-loan-amounts.create');
You named the route so you should call it by it's name:
return redirect()->route('grant-loan-amounts.create', $userId);
pluck required one more parameter for fetch data.
public function create($user)
{
$loanAmount=LoanAmount::all()->pluck('amount','id');
$userId=User::findOrFail($user);
return view('YourBladeFileFolderLocationOrFileLocationHere')->compact('userId','loanAmount');
}
now you can fetch or write at blade file like
For Id :
{{ $userId->id }}
For User Name :
{{ $userId->name }}
I am new in Laravel using version 5.8
I do not want to set route manually for every controller.
What i want is that if i give any url for example -
www.example.com/product/product/add/1/2/3
www.example.com/customer/customer/edit/1/2
www.example.com/category/category/view/1
for the above example url i want that url should be treated like
www.example.com/directoryname/controllername/methodname/can have any number of parameter
I have lots of controller in my project so i want this pattern should be automatically identified by route and i do not need to specify manually again and again Directory Name, Controller , method and number of arguments(parameter) in route.
try this:
Route::get('/product/edit/{id}',[
'uses' => 'productController#edit',
'as'=>'product.edit'
]);
Route::get('/products',[
'uses' => 'productController#index',
'as'=>'products'
]);
in the controller:
public function edit($id)
{
$product=Product::find($id);
return view('edit')->with('product',$product);
}
public function index()
{
$products=Product::all();
return view('index')->with('products',$products);
}
in the index view
#foreach($products as $product)
Edit
#endforeach
in the edit view
<p>$product->name</p>
<p>$product->price</p>
I am returning an API response inside a Categories controller in Laravel 5.5 like this...
public function get(Request $request) {
$categories = Category::all();
return Response::json(array(
'error' => false,
'categories_data' => $categories,
));
}
Now I am trying to also have the option to return a specific category, how can I do this as I am already using the get request in this controller?
Do I need to create a new route or can I modify this one to return a specific category only if an ID is supplied, if not then it returns all?
Better case is to create a new route, but you can also change the current one to retrieve all models if the parameter is not supplied. You first gotta choose which approach you will be using. For splitting it into multiple calls you can see Resource controllers and for using one method you can follow Optional Route Parameters
It will be much cleaner if you will create another route. For example
/categories --> That you have
/categories/{id} -> this you need to create
And then add method at same controller
public function show($id) {
$categories = Category::find($id);
return Response::json(array(
'error' => false,
'categories_data' => $categories,
));
}
But if you still want to do it at one route you can try something like this:
/categories -> will list all categories
/categories?id=2 -> will give you category of ID 2
Try this:
public function get(Request $request) {
$id = $request->get('id');
$categories = $id ? Category::find($id) : Category::all();
return Response::json(array(
'error' => false,
'categories_data' => $categories,
));
}
my controller having the below format. how can i transfer to view in laravel
i tried ->with($inboxMessage) . The browser not even completely loaded. It's loading for a lifetime.
$inboxMessage[] = [
'messageId' => $message_id,
'messageSnippet' => $snippet,
'messageSubject' => $message_subject,
'messageDate' => $message_date,
'messageSender' => $message_sender
];
you can return your view in controller with data like below
return view('viewname', ['inboxMessage' => $inboxMessage]);
now $inboxMessage will available in view.
return view("path to your view", compact('inboxMessage'));
return view("view_name",['data'=>$inboxMessage]);
and in view you can access using foreach loop or use print_r($data)
in view if you are using blade template then
#foreach($data as $val)
{{$val->messageId}}
#endforeach
or else use normal foreach loop