I want to pass the variable id from (the url is /xxxx/{{id}} ) to store
I have a modal box which opens a form. This info is then stored using the controller shown below:
I tried adding $id to pass through the controller (the url is /xxxx/{{id}} )
OpenHome Controller
public function store(Request $request,$id)
$option = new Option;
$option->time = $request->input('time');
$option->date = $request->input('date');
$option->save();
return view('option.create');
ERROR: Type error: Too few arguments to function
App\Http\Controllers\option::store(), 1 passed and exactly 2 expected
dd($request->all());
array:3 [▼
"_token" => "7O23EkldYOYj1d7Fc2xNflcPWMY67ytGTkrymy9g"
"time" => "00:12"
"date" => "12-05-1996"
]
In your question you imply an update of an existing record, but in your code it implies the creation of a new option.
If you wanted to update an option with the $id = 1 you need to have the following route.
Route::put('/options/{id}', 'OptionController#update');
Inside your controller.
public function update(Request $request, $id)
{
$option = Option::find($id);
$option->update([
'time' => $request->input('time'),
'date' => $request->input('date'),
]);
// Redirect to display the list of options.
return redirect('/options');
}
However if you just wanted to pass an additional variable to the store method for use inside the store method, make sure the Route only has single set of {} around the variable.
Route::post('/option/{variable}', 'OptionController#store');
public function store(Request $request, $variable)
{
// User the $variable passed as a route parameter.
}
Related
I want to redirect to my new post when I created a new post in Laravel
But I get a ArgumentCountError
Too few arguments to function App\Http\Controllers\ArticlesController::store(), 1 passed in C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Routing\Controller.php on line 54 and exactly 2 expected
How can I fix it? Thanks
web.php
<?php
Route::resource('articles', ArticlesController::class);
Route::get('/', [ArticlesController::class, 'index'])->name('root');
Route::resource('articles.comments', CommentsController::class);
ArticlesController.php
public function store(Request $request, $id) {
$content = $request->validate([
'title' => 'required|max:30',
'content' => 'required|min:10'
]);
//限制只有透過登入才能CREATE文章
auth()->user()->articles()->create($content);
return redirect('articles/'. $id)->with('notice', '文章發表成功!');
}
create.blade.php
<form class="container-fluid" action="{{ route('articles.store') }}" method="post">
Check your store() method. I think it should get only Request $request.
Example
public function store(Request $request) {
$content = $request->validate([
'title' => 'required|max:30',
'content' => 'required|min:10'
]);
//限制只有透過登入才能CREATE文章
$article = Article::create($content); // static is not best practice, only for example
return redirect('articles/'. $article->id)->with('notice', '文章發表成功!');
}
But before using the create method, you will need to specify either a fillable or guarded. Check docs
Presumably you need / have a way of viewing an article anyway, whether it's just been added or not, so in your web.php you would want a GET request to retrieve an article by passing its ID:
Route::get('/article/{id}', [ArticleController::class, 'viewArticle'])-> name('article.view');
Then you would want a POST request to add a new article :
Route::post('/addarticle', [ArticleController::class, 'addArticle'])-> name('article.add');
In your ArticleController, at the end of your addArticle method, once your new article has been created, you can then return a redirect to your "view article" route referencing its name, and passing in the parameter that it expects - the new article's ID - as part of the route, like so :
$article = new Article();
... populate the article's details here ...
return redirect()->route('article.view', ['id' => $article->id]);
I already solved it by my way
remove $id from store() function
just add $article before auth()->user()->articles()->create($content)
$id change to $article->id from redirect()
Example
public function store(Request $request) {
$content = $request->validate([
'title' => 'required|max:30',
'content' => 'required|min:10'
]);
$article = auth()->user()->articles()->create($content);
return redirect('articles/'. $article->id)->with('notice', '文章發表成功!');
}
Thank you
How can I remove the parameters from a URL after processing in my controller? Like this one:
mydomain/mypage?filter%5Bstatus_id%5D
to
mydomain/mypage
I want to remove the parameters after the ? then I want to use the new URL in my view file. Is this possible in laravel 5.2? I have been trying to use other approaches but unfortunately they are not working well as expected. I also want to include my data in my view file. The existing functionality is like this:
public function processData(IndexRequest $request){
//process data and other checkings
return view('admin.index')
->with([
'data' => $data,
'person' => $persons,
]);
}
I want it to be like:
public function processData(IndexRequest $request){
//process data and other checkings
// when checking the full url is
// mydomain/mypage?filter%5Bstatus_id%5D
// then I want to remove the parameters after the question mark which can be done by doing
// request()->url()
// And now I want to change the currently used url using the request()->url() data
return view('admin.index')
->with([
'data' => $data,
'person' => $persons,
]);
}
I'm stuck here for days already. Any inputs are appreciated.
You can use request()->url(), it will return the URL without the parameters
public function processData(IndexRequest $request){
$url_with_parameters = $request()->url();
$url= explode("?", $url_with_parameters );
//avoid redirect loop
if (isset($url[1])){
return URL::to($url[0]);
}
else{
return view('admin.index')
->with(['data' => $data,
'person' =>$persons,]);
}
}
add new url to your routes and assuming it will point to SomeController#SomeMethod, the SomeMethod should be something like :
public function SomeMethod(){
// get $data and $persons
return view('admin.index')
->with(['data' => $data,
'person' =>$persons,]);
}
I hope this helps
Using Laravel Spark, if I wanted to swap in a new implementation for the configureTeamForNewUser, at first it looks like it's possible because of the Spark::interact call here
#File: spark/src/Interactions/Auth/Register.php
Spark::interact(self::class.'#configureTeamForNewUser', [$request, $user]);
i.e. the framework calls configureTeamForNewUser using Spark::interact, which means I can Spark::swap it.
However, if I look at the configureTemForNewUser method itself
#File: spark/src/Interactions/Auth/Register.php
public function configureTeamForNewUser(RegisterRequest $request, $user)
{
if ($invitation = $request->invitation()) {
Spark::interact(AddTeamMember::class, [$invitation->team, $user]);
self::$team = $invitation->team;
$invitation->delete();
} elseif (Spark::onlyTeamPlans()) {
self::$team = Spark::interact(CreateTeam::class, [
$user, ['name' => $request->team, 'slug' => $request->team_slug]
]);
}
$user->currentTeam();
}
This method assigns a value to the private $team class property. It's my understanding that if I use Spark::swap my callback is called instead of the original method. Initial tests confirm this. However, since my callback can't set $team, this means my callback would change the behavior of the system in a way that's going to break other spark functionality.
Is the above a correct understanding of the system? Or am I missing something, and it would be possible to swap in another function call (somehow calling the original configureTeamForNewUser)?
Of course, you can swap this configureTeamForNewUser method. Spark create a team for a user at the registration. You have to add the swap method inside the Booted() method of App/Providers/SparkServiceProvider.php class.
in the top use following,
use Laravel\Spark\Contracts\Interactions\Auth\Register;
use Laravel\Spark\Contracts\Http\Requests\Auth\RegisterRequest;
use Laravel\Spark\Contracts\Interactions\Settings\Teams\CreateTeam;
use Laravel\Spark\Contracts\Interactions\Settings\Teams\AddTeamMember;
In my case I want to add new field call "custom_one" to the teams table. Inside the booted() method, swap the method as bellow.
Spark::swap('Register#configureTeamForNewUser', function(RegisterRequest $request, $user){
if ($invitation = $request->invitation()) {
Spark::interact(AddTeamMember::class, [$invitation->team, $user]);
self::$team = $invitation->team;
$invitation->delete();
} elseif (Spark::onlyTeamPlans()) {
self::$team = Spark::interact(CreateTeam::class, [ $user,
[
'name' => $request->team,
'slug' => $request->team_slug,
'custom_one' => $request->custom_one,
] ]);
}
$user->currentTeam();
});
In order to add a new custom_one field, I had to swap the TeamRepository#createmethod as well. After swapping configureTeamForNewUser method, swap the TeamRepository#create method onside the booted(),
Spark::swap('TeamRepository#create', function ($user, $data) {
$attributes = [
'owner_id' => $user->id,
'name' => $data['name'],
'custom_one' => $data['custom_one'],
'trial_ends_at' => Carbon::now()->addDays(Spark::teamTrialDays()),
];
if (Spark::teamsIdentifiedByPath()) {
$attributes['slug'] = $data['slug'];
}
return Spark::team()->forceCreate($attributes);
});
Then proceed with your registration.
See Laravel Spark documentation
When I'm adding or editing an entry to my database table websites I load the instance of the website to be modified (or a blank one for creating a website). This works great, this is my controller:
<?php namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Request;
use App\Models\User;
use App\Models\Status;
use App\Models\Website;
class WebsitesController extends Controller {
/**
* Show / Process the create website form to the user.
*
* #return Response
*/
public function create()
{
$statuses = Status::all();
$users = User::all();
$website = Website::find(0);
return view('admin/websites/create', [
'statuses' => $statuses,
'users' => $users,
'website' => $website
]);
}
public function update($id)
{
$statuses = Status::all();
$users = User::all();
$website = Website::findOrFail($id);
return view('admin/websites/update', [
'statuses' => $statuses,
'users' => $users,
'website' => $website
]);
}
}
The problem is when I submit the form and there is an error. The user is returned to the page and the errors displayed. I also pass the users input back so I can repopulate the form with what they entered. But how can I replace the values in website with the values from input if it's present without actually saving to the database? I've been playing around with this all day and not found a working solution.
My create method is this:
public function postCreate(Request $request)
{
$v = Validator::make($request->all(), Website::rules());
if ($v->fails())
{
return redirect()->back()->withInput()->withErrors($v);
}
$website = Website::create($request->all());
return redirect()->action('Admin\HomeController#index')->with('messages', [['text' => 'Website created', 'class' => 'alert-success']]);
}
I'm passing the input back to the original form, but the form populates its values from the Website Eloquent model. **How can I get the input from $request->all() into $website?
I've tried using fill(), but I just get Call to a member function fill() on null when using it in the create function.
The create method attempts to insert a record to the database and returns an instance of the model if it is successful. If you use create() with invalid values, the insert will fail. I think this is why there is a null instead of an instance of the model, which causes your error:
Call to a member function fill() on null
Instead of using create() You could create the website model without the database insert using
$website = new Website;
$website->fill($request->all());
before you run the validation. If the validation passes, then you can insert to your database with $website->save();, otherwise, it will not try to save, but the model should be available for you to use in your form.
Currently, editing profile works for me. However, my problem is, only one element is successfully edited. I can echo previously saved data, and I can even type and edit each of the textboxes. Problem is, only the revision made on "profile" field is properly reflected. All the other fields remain the same.
here's what I have so far:
in controller page:
public function edit_profile()
{
//loads client profile and allows editing to be done
$this->validateRole('client');
$this->load->model('job_model');
$id = $this->auth_model->get_user_id();
$data['client'] = $this->auth_model->get_client($id);
$this->load->view('client/edit_profile', $data);
}
public function edit_profile_submit()
{
$this->validateRole('client');
$this->load->model('auth_model');
//$this->auth_model->edit_client_profile($this->auth_model->get_user_id(), $_POST['tagline']);
$this->auth_model->edit_client_profile($this->auth_model->get_user_id(), $_POST['profile']);
//$this->auth_model->edit_client_profile($this->auth_model->get_user_id(), $_POST['billing_mode']);
redirect('client/view_profile?message=Profile updated.');
}
in model page:
public function edit_client_profile($id, $profile)
{
// allows client to edit his or her profile
$data = array(
//'tagline' => $tagline,
'profile' => $profile
//'billing_mode' => $billing_mode
);
$this->db->where('id', $id);
$this->db->update('client', $data);
}
I tried editing my controller and model page only to get errors so I commented the added lines for now instead.
I am looking forward to any possible help.
Thanks!
The error is probably because you have two undefined variables in your $data array each time you call the model. Instead of creating the array in your model, create it in your controller:
$data = array(
'tagline' => $_POST['tagline'],
'profile' => $_POST['profile'],
'billing_mode' => $_POST['billing_mode']
);
Then call the model
$this->auth_model->edit_client_profile($this->auth_model->get_user_id(), $data);
Remove the array creation from your model, change the second parameter being passed to $data:
public function edit_client_profile($id, $data)
{
$this->db->where('id', $id);
$this->db->update('client', $data);
}