Hi Im using a repository pattern in laravel and to create tasks and they all have an estimated time and the project has a capacity of hours. So i need to pass this back when the task is created so they can see how many hours are left.
I have this so far:
TaskRepository.php
public function createTask(array $attributes)
{
if ($this->validator->createATask($attributes)) {
$newAttributes = [
'project_id' => $attributes['project_id'],
'estimated_time' => $attributes['estimated_time'],
'task_name' => $attributes['task_name']
];
$task = Task::updateOrCreate([
'task_name' => $attributes['task_name']
],
$newAttributes);
$task->save();
$project = Project::find($attributes["project_id"])->pluck('capacity_hours');
$tasks = Task::find($attributes["project_id"])->lists('estimated_time');
$tasksTotal = array_sum($tasks);
$capcity_left = ($project - $tasksTotal);
return $capcity_left;
}
throw new ValidationException('Could not create Task', $this->validator->getErrors());
}
and in my controller I have this:
TaskController.php
public function store() {
try {
$this->task_repo->createTask(Input::all());
} catch (ValidationException $e) {
if (Request::ajax()) {
return Response::json(['errors' => $e->getErrors()], 422);
} else {
return Redirect::back()->withInput()->withErrors($e->getErrors());
}
}
if (Request::ajax()) {
return Response::json(["message" => "Task added",'capcity_left'=> $capcity_left]);
} else {
return Redirect::back()->with('success', true)->with(['message', 'Task added', 'capcity_left'=>$capcity_left ]);
}
}
and I have a partial for errrors:
#if(Session::get('success'))
<div class="alert alert-success alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span
aria-hidden="true">×</span></button>
<strong>{{ Session::get('message', '') }} Capacity Left:{{ Session::get('capcity_left', '') }}</strong>
</div>
#endif
However I get this error:
Undefined variable: capcity_left
Any ideas how I can pass this back to the controller? I thought I was by saying return $capcity_left; Do I need to catch this in the controller? If so how can I do that?
You forgot to assign the return value of the createTask method when calling it from the controller. So you need to do this:
public function store() {
try {
// assign the return value here
$capcity_left = $this->task_repo->createTask(Input::all());
} catch (ValidationException $e) {
// ...
}
Related
I am using laravel 8
I want to make when the validation error , it will show the sweetalert or session message when error to the index page just like this
{{-- Flash data --}}
#if(session()->has('success'))
<div class="alert alert-success alert-dismissible fade show" role="alert">
{{ session('success') }}
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
but in my controller have an error here's in my controller
public function verify(VerifyRequest $request)
{
// Verify using VerifyRequest
$validated = array_merge($request->validated(), ['token' => Str::random(127)]);
// the error in this line
if($validated->validate()->fails()){
return redirect(url()->previous() . '#verify-email')->withErrors($request)->withInput();
}
// end the error
// create
Pengaduan::create($validated);
// Setup the email message
$data = [
'content' => 'to create complaint please click the link below',
'url' => 'http://127.0.0.1:8000/complaint/create/' . $validated['token'],
];
// Send to email
Mail::to($validated['email'])->send(new VerifyAlternative($data));
return redirect()
->route('complaint.check')
->with('success', 'Register success. Please Check your email');
}
#endif
here's in my VerifyRequest
class VerifyRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'email' => ['required', Rule::unique('complaints')],
];
}
public function messages()
{
return [
'email.unique' => 'This email is making a Complaint. Wait for the complaint to be completed to make a complaint again'
];
}
protected function prepareForValidation()
{
$this->merge([
'email' => $this->email . '#univesity.com',
]);
}
}
Can anyone help me to solve this as soon as posible. Thank you in advanced
i have flashMessage trait which controllers flashing messages
Trait FlashMessages
{
protected $errorMessages = [];
protected $infoMessages = [];
protected $successMessages = [];
protected $warningMessages = [];
/**
* #param $message
* #param $type
*/
protected function setFlashMessage($message, $type)
{
$model = 'infoMessages';
switch ($type) {
case 'info' : {
$model = 'infoMessage';
}
break;
case 'error' : {
$model = 'errorMessages';
}
break;
case 'success' : {
$model = 'successMessages';
}
break;
case 'warning' : {
$model = 'warningMessages';
}
break;
}
if (is_array($message)) {
foreach ($message as $key => $value) {
array_push($this->$model, $value);
}
} else array_push($this->$model, $message);
}
public function getFlashMessages(): array
{
return [
'error' => $this->errorMessages,
'info' => $this->infoMessages,
'success' => $this->successMessages,
'warning' => $this->warningMessages,
];
}
public function showFlashMessages()
{
session()->flash('error', $this->errorMessages);
session()->flash('info', $this->infoMessages);
session()->flash('success', $this->successMessages);
session()->flash('warning', $this->warningMessages);
}
}
so i include it in my BaseController.php which its source is as follows.
class BaseController extends Controller
{
use FlashMessages;
protected $data = null;
protected function setPageTitle($title, $subTitle)
{
view()->share(['pageTitle' => $title, 'subTitle' => $subTitle]);
}
protected function showErrorPage($errorCode = 404, $message = null)
{
$data['message'] = $message;
return response()->view('errors.'.$errorCode, $data, $errorCode);
}
protected function responseJson($error = true, $responseCode = 200, $message = [], $data = null): \Illuminate\Http\JsonResponse
{
return response()->json([
'error' => $error,
'response_code' => $responseCode,
'message' => $message,
'data' => $data
]);
}
protected function responseRedirect($route, $message, $type = 'info', $error = false, $withOldInputWhenError = false): \Illuminate\Http\RedirectResponse
{
$this->setFlashMessage($message, $type);
$this->showFlashMessages();
if ($error && $withOldInputWhenError) {
return redirect()->back()->withInput();
}
return redirect()->route($route);
}
protected function responseRedirectBack($message, $type = 'info'): \Illuminate\Http\RedirectResponse
{
$this->setFlashMessage($message, $type);
$this->showFlashMessages();
return redirect()->back();
}
}
and my GalleryController extends Basecontroller and store method is as follows for storing new gallery
public function store(Request $request): \Illuminate\Http\RedirectResponse
{
// dd($request->all());
$request->validate([
'name' => 'required',
'address' => 'required',
'city_id' => 'required|integer',
]);
//create new gallery instance
// dd($request);
$gallery = new Gallery();
$gallery->name = $request->name;
$gallery->address = $request->address;
$gallery->city_id = $request->city_id;
$gallery->user_id = Auth::user()->id;
// dd($gallery);
// dump($request->toArray());
$gallery->save();
if (!$gallery) {
return $this->responseRedirectBack('Error occured while creating Gallery');
}
return $this->responseRedirect('galleries.index', 'New Gallery added');
}
lastly i included in my index.blade.php file with flash.blade.php partial which its source code is
#php
$errors = Session::get('error');
$messages = Session::get('success');
$info = Session::get('info');
$warnings = Session::get('warning');
#endphp
#if ($errors) #foreach($errors as $key => $value)
<div class="alert alert-danger alert-dismissible" role="alert">
<button class="close" type="button" data-dismiss="alert">×</button>
<strong>Error!</strong> {{ $value }}
</div>
#endforeach #endif
#if ($messages) #foreach($messages as $key => $value)
<div class="alert alert-success alert-dismissible" role="alert">
<button class="close" type="button" data-dismiss="alert">×</button>
<strong>Success!</strong> {{ $value }}
</div>
#endforeach #endif
#if ($info) #foreach($info as $key => $value)
<div class="alert alert-info alert-dismissible" role="alert">
<button class="close" type="button" data-dismiss="alert">×</button>
<strong>Info!</strong> {{ $value }}
</div>
#endforeach #endif
#if ($warnings) #foreach($warnings as $key => $value)
<div class="alert alert-warning alert-dismissible" role="alert">
<button class="close" type="button" data-dismiss="alert">×</button>
<strong>Warning!</strong> {{ $value }}
</div>
#endforeach #endif
but when i try to save new gallery it is returning an error in flashMessage.php trait file line 46 which is as follows.
if (is_array($message)) {
foreach ($message as $key => $value) {
array_push($this->$model, $value);
}
} else array_push($this->$model, $message);
the error code is comming from else block. so how can i fix this? this code worked with my city controller but not working with this GalleryController. i know ther error is array_push is expecting that the first argument should be an array. but but it says in else bock that $this->$model is null, why as it worked with my other controller, plz help
thanks.
I am developing collaborators adding methods to my project management application. this is my collaborators add form.
colllaborators/form.blade.php
<div class="col-md-4" style="border:1px solid #ccc;margin-left:15px;padding:10px;">
<h4 class="page-header">
Collaborators
</h4>
#if( $collaborators)
#foreach( $collaborators as $collaborator)
<div>
<div>
<span>
<img src="{{ $collaborator->user()->first()->getAvatarUrl() }}" />
</span>
</div>
<button class="btn btn-sm btn-danger delete" style="margin-top:5px;padding:4px;width:35px;"
data-action="/projects/{{ $project->id }}/collaborators/{{ $collaborator->collaborator_id }}"
routes
Route::post('projects/{projects}/collaborators', [
'uses' => 'Project\Collaborators\Controller#addCollaborator',
'as' => 'projects.collaborators.create',
'middleware' => ['auth']
]);
but when I click to collaborators adding buttons following error messages displayed.
Undefined variable: collaborators (View: C:\Users\Flex\Desktop\ddd\resources\views\collaborators\form.blade.php)
how can I fix this problem
edited
class ProjectCollaboratorsController extends Controller
{
public function addCollaborator(Request $request, $id, Collaboration $collaboration)
{
$this->validate($request, [
'collaborator' => 'required|min:5',
]);
$collaborator_username = substr(trim($request->input('collaborator')),1);
$collaboration->project_id = $id;
if( is_null($this->getId($collaborator_username)))
{
return redirect()->back()->with('warning', 'This user does not exist');
}
$collaborator = $this->isCollaborator($id, $this->getId($collaborator_username));
if(! is_null($collaboration))
{
return redirect()->back()->with('warning', 'This user is already a collaborator on this project');
}
$collaboration->collaborator_id = $this->getId($collaborator_username);
$collaboration->save();
return redirect()->back()->with('info', "{$collaborator_username} has been added to your project successfully");
}
private function getId($username)
{
$result = User::where('username', $username)->first();
return (is_null($result)) ? null : $result->id;
}
private function isCollaborator($projectId, $collaboratorId)
{
return Collaboration::where('project_id', $projectId)
->where('collaborator_id', $collaboratorId)
->first();
}
}
see My other part of the form
<form class="form-vertical" role="form" method="post" action="{{ route('projects.collaborators.create', $project->id) }}">
collaborator form route
Route::get('/collaborators', function(){
return view('collaborators.form');
})->name('collaborators.form');
In your form page, you are checking #if( $collaborators) which checks if the $collaborators variable is not empty and then runs the foreach below it.
After you submit your form, you add the collaborator and redirect back with no collaborators. The if condition then tries to check if the variable is empty. At this point the variable has not been defined and hence it throws that error. To fix this error, return redirect back with the collaborators like this:
public function addCollaborator(Request $request, $id, Collaboration $collaboration)
{
$this->validate($request, [
'collaborator' => 'required|min:5',
]);
$collaborator_username = substr(trim($request->input('collaborator')),1);
$collaboration->project_id = $id;
if( is_null($this->getId($collaborator_username)))
{
return redirect()->back()->with('warning', 'This user does not exist');
}
$collaborator = $this->isCollaborator($id, $this->getId($collaborator_username));
if(! is_null($collaboration))
{
return redirect()->back()->with('warning', 'This user is already a collaborator on this project');
}
$collaboration->collaborator_id = $this->getId($collaborator_username);
$collaboration->save();
//Get all collaborators
$collaborators = Collaboration::all(); //if this is how you get all collaborators
//Get the project too
$project = Project::findOrFail($id);
return redirect()->back()->with(['collaborators'=>$collaborators,'project'=>$project,'info'=> "{$collaborator_username} has been added to your project successfully"]);
}
EDIT:
Using the with method puts the data in the session, i would suggest that you manually redirect to the view and flash the message to that view.
public function addCollaborator(Request $request, $id, Collaboration $collaboration)
{
$this->validate($request, [
'collaborator' => 'required|min:5',
]);
$collaborator_username = substr(trim($request->input('collaborator')),1);
$collaboration->project_id = $id;
if( is_null($this->getId($collaborator_username)))
{
return redirect()->back()->with('warning', 'This user does not exist');
}
$collaborator = $this->isCollaborator($id, $this->getId($collaborator_username));
if(! is_null($collaboration))
{
return redirect()->back()->with('warning', 'This user is already a collaborator on this project');
}
$collaboration->collaborator_id = $this->getId($collaborator_username);
$collaboration->save();
//Get all collaborators
$collaborators = Collaboration::all(); //if this is how you get all collaborators
//Get the project too
$project = Project::findOrFail($id);
return redirect()->route('collaborators.form',['collaborators'=>$collaborators,'project'=>$project])->with('info',"{$collaborator_username} has been added to your project successfully");
}
Edit 2
I have changed all the return redirect()->back()'s
public function addCollaborator(Request $request, $id, Collaboration $collaboration)
{
$this->validate($request, [
'collaborator' => 'required|min:5',
]);
$collaborator_username = substr(trim($request->input('collaborator')),1);
$collaboration->project_id = $id;
//Get the project too
$project = Project::findOrFail($id);
if( is_null($this->getId($collaborator_username)))
{
return redirect()->route('collaborators.form',['project'=>$project])->with('warning', 'This user does not exist');
}
$collaborator = $this->isCollaborator($id, $this->getId($collaborator_username));
if(! is_null($collaboration))
{
return redirect()->route('collaborators.form',['project'=>$project])->with('warning', 'This user is already a collaborator on this project');
}
$collaboration->collaborator_id = $this->getId($collaborator_username);
$collaboration->save();
return redirect()->route('collaborators.form',['project'=>$project])->with('info',"{$collaborator_username} has been added to your project successfully");
}
And change your routes to
Route::get('/project/{project}/collaborators', function($id){
$collaborators = Collaboration::all();
$project = Project::findOrFail($id);
return view('collaborators.form',compact('collaborators','project'));
})->name('collaborators.form');
i'm trying to use callback to simply to check my form input, the offical code is here: https://laravel.com/docs/5.2/validation
the following is my function
public function addthread(Request $request) {
$input = $request->all();
$rules = array('title' => 'required|unique:thread|max:255');
$message = array('title.required' => 'The :attribute field is aaa required.');
$validator = Validator::make($input, $rules, $message);
$validator->after(function($validator) {
if ($this->checkOpt()) {
$validator->errors()->add('num_opt', 'Something is wrong with this field!');
echo 'test';
}
});
if ($validator->fails()) {
return redirect('addthreadhtml')->withErrors($validator)->withInput();
}
}
public function checkOpt() {
return false;
}
the blade tpl:
#if (count($errors) > 0)
<div class="container" stytle="max-width:80%">
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
</div>
#endif
The num_opt error never print out, any idea?
checkOpt() is returning FALSE, so the code will never enter the if statment.
if ($this->checkOpt()) { // this is returning false, right ?? so, its not adding the error
$validator->errors()->add('num_opt', 'Something is wrong with this field!');
echo 'test';
}
Your checkOpt() always returns false, so your condition won't ever be satisfied.
I'm trying to make alert with cross sign. Unfortunately cross sign not working. I have included jquery before bootstrap.js. Here is my model. Thanks in Advance
public function create(){
$data = array('name'=> $this->input->post('name'));
$this->db->insert('dbname', $data);
echo'
<div class="alert alert-success">
×You have successfully posted
</div>
';
exit;
}
Change this to
×You have successfully posted
this
×You have successfully posted
And as well as use Model to write data into database. Use follows
In controller
public function create(){
$this->load->model('Model_name');
$result = $this->Model_name->insert_data();
if($result == 1)
{
?>
<div class="alert alert-success">
×You have successfully posted
</div>
<?php
}
else
{
?>
<div class="alert alert-error">
×Failed to poste
</div>
<?php
}
}
In Model
public function insert_data()
{
$data = array(
'name'=> $this->input->post('name')
);
if(!$this->db->insert('dbname', $data))
{
return $log = 0;
}
else
{
return $log = 1;
}
}