UPDATE
I have contact form. it works good. I would like to display $data array at
final page which is admintemp.blade.php.
I can display $data array at one step before final page. but I would like to display those at last page too.
I thoguht just add this
return view('mail.complete', ['data' => $data]);
is fine. but I got this error
Invalid argument supplied for foreach()
Could you teach me right way please?
Here is my code
/*
*confirm page
*/
public function confirm(Request $request)
{
$rules = [
'orderer' => 'required'
];
$this->validate($request, $rules);
$data = $request->all();
$request->session()->put('data',$data);
return view('mail.confirm', compact("data"));
}
/*
* complete page
*/
public function complete(Request $request)
{
$data = $request->session()->pull('data');
$token = array_shift($data);
$Contact = Contact::create($data);
$data = session()->regenerateToken();
return view('mail.complete', ['data' => $data]);
}
UPDATES 2
complete.blade.php
#foreach ($data as $val)
{{ $val->id }}
{{ $val->tel }}
#endforeach
for example you have two step form
first step post method:
public function postCreateStep1(Request $request)
{
$validatedData = $request->validate([
'name' => 'required',
]);
if (empty($request->session()->get('contact'))) {
$contact = new Contact();
$contact->fill($validatedData);
$request->session()->put('contact', $contact);
} else {
$contact = $request->session()->get('contact');
$contact->fill($validatedData);
$request->session()->put('contact', $contact);
}
return redirect('/create-step2');
}
second step post method:
public function postCreateStep2(Request $request)
{
$validatedData = $request->validate([
'family' => 'required',
]);
if (empty($request->session()->get('contact'))) {
$contact = new Contact();
$contact->fill($validatedData);
$request->session()->put('contact', $contact);
} else {
$contact = $request->session()->get('contact');
$contact->fill($validatedData);
$request->session()->put('contact', $contact);
}
$created_contact = Contact::create([
'name' => $contact->name,
'family' => $contact->family,
]);
// Do whatever you want with $created_contact
return redirect('/');
}
Related
I have configured a resource route as below
Route::resource('users', UserController::class);
When a user posts data, it will call the store method in the controller where it will add the data and set a message for success/failure.
public function store(Request $request)
{
// return $request;
$request->validate(
[
"firstName" => 'required',
"lastName" => 'required',
"phoneNo" => 'required',
"email" => 'email:rfc,dns'
]
);
$date = date(now());
$data = [
'firstName' => $request->firstName,
'lastName' => $request->lastName,
'phoneNo' => $request->phoneNo,
'email' => $request->email,
'designation' => $request->designation,
'status' => $request->status,
'createdAt' => $date,
'updatedAt' => $date,
];
$user = Firebase::insertData($data, static::$collection);
if ($user->id() != null) {
$message = "User Created Successfully";
} else {
$message = "Something went wrong. Please contact System Admin with error code USR001";
}
return redirect()->route('users.index', ['message' => $message]);
}
This will redirect to the index method of the same controller. How can I use the $message parameter in the index method and send it to the view? My index method is below
public function index()
{
$userCollection = app('firebase.firestore')->database()->collection('users');
$userData = $userCollection->documents();
$response = [];
$app = app();
foreach ($userData as $data) {
$user = $app->make('stdClass');
$user->firstName = $data["firstName"];
$user->lastName = $data["lastName"];
$user->phoneNo = $data["phoneNo"];
$user->email = $data["email"];
$user->designation = $data["designation"];
$user->status = $data["status"];
$user->createdAt = $data["createdAt"];
$user->updatedAt = $data["updatedAt"];
array_push($response, $user);
}
return view('pages.user.list-user', ['response' => $response]);
}
You can directly pass the message as a flash message using the with() method with the redirect method.
Edit your redirect code as:
return redirect()->route('users.index')->with('message', $message]);
and add the below code in your pages.user.list-user blade file:
#if (session('message'))
<div class="alert alert-success">
{{ session('message') }}
</div>
#endif
Visit https://laravel.com/docs/8.x/redirects#redirecting-with-flashed-session-data for more info on redirects with a flash message.
Replace your redirect code :
return redirect()->route('users.index', ['message' => $message]);
with
return view('pages.user.list-user', ['message' => $message]);
(1) First of all, pass the message in the parameter of index function:
public function index($message)
{
...
}
(2) This is okay, you wrote correctly:
return redirect()->route('users.index', ['message' => $message]);
(3) Now just access the message in the view (blade) and print it:
{{ $message }}
You can also store message in $response array and simply pass the $response to the desired view:
$response['message'] = $message;
You can have the index method like if the parameter used in the controller.
public function index(Request $request)
{
// Your code
$message = $request['message'];
}
If you want to access the message in view use
return redirect()->route('users.index')->with('message', $message]);
and access from the view using session('message') like in OMi Shah's answer
I can't return a toast error message. Where am I making a mistake? Message returns when successful.
My code is as follows:
public function store(Request $request)
{
$validated = $request->validate([
'category_name' => 'required|unique:categories|max:50',
]);
$data = array();
$data['category_name'] = $request->category_name;
$save = DB::table('categories')->insert($data);
if ($save) {
Toastr::success('Post Successfully Saved :)', 'Success');
return redirect()->route('admin.category');
} else {
Toastr::error('Error :)', 'Error');
return redirect()->route('admin.category');
}
}
Try the following:
public function store(Request $request)
{
$validated = $request->validate([
'category_name' => 'required|unique:categories|max:50',
]);
$data = array();
$data['category_name'] = $request->category_name;
$save = DB::table('categories')->insert($data);
if (!$save) {
Toastr::error('Error :)', 'Error');
return redirect()->route('admin.category');
} else {
Toastr::success('Post Successfully Saved :)', 'Success');
return redirect()->route('admin.category');
}
}
You can try this code.. You can use ->fails() function to check the inputs
public function store(Request $request)
{
$validated = $request->validate([
'category_name' => 'required|unique:categories|max:50',
]);
if($validated->fails()){
Toastr::error('Error :)','Error');
return redirect()->route('admin.category');
}
$data=$request->only(['category_name']);
$save = DB::table('categories')->insert($data);
Toastr::success('Post Successfully Saved :)','Success');
return redirect()->route('admin.category');
}
I found the solution . I created a validator myself
public function store(Request $request)
{
$validated = Validator::make($request->all(), [
'category_name' => 'required|unique:categories|max:50',
]);
$notificationerror=array(
'messege'=>'Category Added Error',
'alert-type'=>'error',
'positionClass' =>'toast-top-right'
);
if($validated->fails()){
return redirect()->route('admin.category')->with($notificationerror);
}
$data=array();
$data['category_name']=$request->category_name;
DB::table('categories')->insert($data);
$notification=array(
'messege'=>'Category Added Successfully',
'alert-type'=>'success',
);
return redirect()->route('admin.category')->with($notification);
}
I am a beginner in laravel. I'm trying to submit a post with the option to upload multiple files if the user wants. I keep getting the error "Undefined variable: data." Where did I go wrong?
public function store(Request $request)
{
//validate
$this->validate($request, [
'title' => 'required|min:10',
'body' => 'required|min:20',
'filename' => 'nullable|max:2480',
'filename.*' => 'mimes:jpeg,jpg,png'
]);
//store Image
if($request->file('filename'))
{
foreach($request->file('filename') as $image)
{
$name=time().$image->getClientOriginalName();;
$image->move(public_path().'/images/', $name);
$data[] = $name;
}
}
$post= new Post();
$post->user_id = auth()->user()->id;
$post->title = $request->input('title');
$post->body = $request->input('body');
$post->filename=json_encode($data);
$post->save();
return back()->withMessage('Post created successfully.');
}
I think that it will be better to declare your array outside the foreach loop.
You can try something like this:
Outside your foreach loop.
$data = array();
Inside your foreach loop, try to populate the array like this:
array_push($data, $name);
public function store(Request $request)
{
//validate
$this->validate($request, [
'title' => 'required|min:10',
'body' => 'required|min:20',
'filename' => 'nullable|max:2480',
'filename.*' => 'mimes:jpeg,jpg,png'
]);
//Initialize an empty array
$data = array();
//store Image
if($request->file('filename'))
{
foreach($request->file('filename') as $image)
{
$name=time().$image->getClientOriginalName();;
$image->move(public_path().'/images/', $name);
//populate array here
array_push($data, $name);
}
}
$post= new Post();
$post->user_id = auth()->user()->id;
$post->title = $request->input('title');
$post->body = $request->input('body');
$post->filename=json_encode($data);
$post->save();
return back()->withMessage('Post created successfully.');
}
I am adding and editing a user with same function (Store), when ever i add a user it asks me image is required but whenever i edit a user which have image it also ask me image is required and i want if a image is already present it wont ask me , please see my above code i had recently changed my code according to Gurpal singh
In my controller
public function rules()
{
$child_details = Children::findOrFail($inputs['id']);
$rules = [
'child_name' => 'required',
'gender' => 'required',
'dob' => 'required',
'current_class' => 'required',
'b_group' => 'required',
'm_tongue' => 'required',
'image' => 'image',
];
if ($child_details->notHavingImageInDb()){
$rules['image'] = 'required|image';
}
return $rules;
}
public function Postchild(Request $request)
{
$data = \Input::except(array('_token')) ;
$validator = \Validator::make($data,$rules);
$inputs = $request->all();
if ($validator->fails())
{
return redirect()->back()->withInput()->withErrors($validator->messages());
}
if(!empty($inputs['id'])){
$child_details = Children::findOrFail($inputs['id']);
}else{
$child_details = new Children;
}
$child_details->parent_id = Auth::User()->id;
$child_details->child_name = $inputs['child_name'];
$child_image = $request->file('image');
if($child_image){
$tmpFilePath = 'uploads/childrens/';
$extension = $child_image->getClientOriginalExtension();
$hardPath = str_slug($inputs['child_name'], '-').'-'.md5(time());
$img = Image::make($child_image);
//$img->resize(180)->save($tmpFilePath.$hardPath.'-b.jpg');
$img->fit(250, 250)->save($tmpFilePath.$hardPath.'.'.$extension);
$child_details->image = $hardPath.'.'.$extension;
}
$child_details->save();
if(!empty($inputs['id'])){
return \Redirect()->route('child_list')->with('success', 'Child has been updated');
}else{
return \Redirect()->route('child_list')->with('success', 'Child has been added');
}
}
You can use Conditionally Adding Rules Not having image in database
Add this in model
public function notHavingImageInDb()
{
return (empty($this->image))?true:false;
}
This is the validation rule request
public function rules()
{
$user = User::find(Auth::id());
$rules = [
'name' =>'required|max:100',
'image' =>'image',
];
if ($user->notHavingImageInDb()){
$rules['image'] = 'required|image';
}
return $rules;
}
Don't forgot to import auth and user model
ie
use App\User;
use Auth;
for more detail click here
You can normally do like below :
$rule = array(
'name' => 'required',
);
if (!empty($inputs['id'])) {
$user = User::findOrFail($inputs['id']);
} else {
$rule["image"] = "required";
$user = new User;
}
It is better to separate them or simply create another function. But you can put an if statement that if the image is in the request or not.
Like this:
if(! isset($data['image'])){ //if the image is not in the request
//Your code
}
else{ //if the image is in the request
//Your code
}
If you want a code for storing, renaming, moving an image feel free to request.
You can use validation's after hook.
public function Postchild(Request $request)
{
//Define your rules
$rules = [
'child_name' => 'required',
'gender' => 'required',
'dob' => 'required',
'current_class' => 'required',
'b_group' => 'required',
'm_tongue' => 'required',
];
//Validate your data
$data = $request->except('_token');
$validator = \Validator::make($data,$rules);
$validator->after(function ($validator) {
//Check the mode of request (Create or Update)
if(!empty($data['id'])){
$child_details = Children::findOrFail($data['id']);
if($child_details->image == null){
$validator->errors()->add('image', 'Image field is required');
}
}
});
if ($validator->fails()) {
return redirect()->back()
->withErrors($validator)
->withInput();
}
}
Just this few lines can solve your problems... You have to check there image have or not.
Rules in a private or protected function
private function validateRequest($request)
{
//This is for Update without required image, this will check that In DB image have or not
$child_image = Children::find($request->id);
$rules = [];
if ($child_image) :
if ($child_image->image == null):
$rules['image'] = 'required|image|max:1999';
endif;
//This is for regular validation
else :
$rules = [
'image' => 'required|image|max:1999',
];
endif;
return $rules;
}
I have a Laravel Lumen API. I'm seeing an issue with the update functionality.
In my controller, the code for updating an item is:
public function update(Request $request, $id)
{
$this->validate($request, [
'name' => 'required',
'description' => 'required',
'completed' => 'required',
]);
$todo = Todo::find($id);
$todo->name = $request->name;
$todo->description = $request->description;
$todo->completed = $request->completed;
$todo->save();
return response()->json(['status' => 'success']);
}
I can update the todo item using:
http://lumen-todo.app/api/51?name=test&description=test&completed=1
however was hoping I could send the parameters in a json body, like this
PUT http://lumen-todo.app/api
{
"id": 1
"name": "Test",
"description": "Test",
"completed": 1,
}
For adding items, it works via a json body, so don't understand why it does not work for updates. For info, the 'add item' controller code is here:
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'description' => 'required',
'completed' => 'required'
]);
$todo = new Todo();
$todo->name = $request->name;
$todo->description = $request->description;
$todo->completed = $request->completed;
$todo->save();
return response()->json(['status' => 'success']);
}
If you want to get the json data from request payload, validate and store it, use
public function store(Request $request)
{
$data = $request->json()->all();
$this->validate($data, [
'name' => 'required',
'description' => 'required',
'completed' => 'required'
]);
$resource = $this->model->find($id);
$resource->fill($request);
$resource->save();
return response()->json(['status' => 'success']);
}
Instead of doing this:
$todo = new Todo();
$todo->name = $request->name;
$todo->description = $request->description;
$todo->completed = $request->completed;
$todo->save();
Do, this:
use App\Todo;
protected $model;
public function __construct(Todo $model) {
$this->model = $model;
}
$resource = $this->model->find($id);
$resource->fill($request);
$resource->save();
Also, you can do json_decode() function to change your json params to array and use that to validate and save data.