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');
Related
Sorry for my bad english but i have a problem when i try to open localhost:8080/blog this message show up
Too few arguments to function App\Controllers\Blog::view(), 0 passed in C:\xampp\htdocs\baru\vendor\codeigniter4\framework\system\CodeIgniter.php on line 896 and exactly 1 expected
so this is the controller:
use CodeIgniter\Controller;
use App\Models\ModelsBlog;
class Blog extends BaseController
{
public function index()
{$data = [
'title' => 'artikel'
];
$model = new ModelsBlog();
if (!$this->validate([]))
{
$data['validation'] = $this->validator;
$data['artikel'] = $model->getArtikel();
return view('view_list',$data);
}
}
public function form(){
$data = [
'title' => 'Edit Form'
];
helper('form');
return view('view_form', $data);
}
public function view($id){
$data = [
'title' => 'artikel'
];
$model = new ModelsBlog();
$data['artikel'] = $model->PilihBlog($id)->getRow();
return view('view',$data);
}
public function simpan(){
$model = new ModelsBlog();
if ($this->request->getMethod() !== 'post') {
return redirect()->to('blog');
}
$validation = $this->validate([
'file_upload' => 'uploaded[file_upload]|mime_in[file_upload,image/jpg,image/jpeg,image/gif,image/png]|max_size[file_upload,4096]'
]);
if ($validation == FALSE) {
$data = array(
'judul' => $this->request->getPost('judul'),
'isi' => $this->request->getPost('isi')
);
} else {
$upload = $this->request->getFile('file_upload');
$upload->move(WRITEPATH . '../public/assets/blog/images/');
$data = array(
'judul' => $this->request->getPost('judul'),
'isi' => $this->request->getPost('isi'),
'gambar' => $upload->getName()
);
}
$model->SimpanBlog($data);
return redirect()->to('./blog')->with('berhasil', 'Data Berhasil di Simpan');
}
public function form_edit($id){
$data = [
'title' => 'edit artikel'
];
$model = new ModelsBlog();
helper('form');
$data['artikel'] = $model->PilihBlog($id)->getRow();
return view('form_edit',$data);
}
public function edit(){
$model = new ModelsBlog();
if ($this->request->getMethod() !== 'post') {
return redirect()->to('blog');
}
$id = $this->request->getPost('id');
$validation = $this->validate([
'file_upload' => 'uploaded[file_upload]|mime_in[file_upload,image/jpg,image/jpeg,image/gif,image/png]|max_size[file_upload,4096]'
]);
if ($validation == FALSE) {
$data = array(
'judul' => $this->request->getPost('judul'),
'isi' => $this->request->getPost('isi')
);
} else {
$dt = $model->PilihBlog($id)->getRow();
$gambar = $dt->gambar;
$path = '../public/assets/blog/images/';
#unlink($path.$gambar);
$upload = $this->request->getFile('file_upload');
$upload->move(WRITEPATH . '../public/assets/blog/images/');
$data = array(
'judul' => $this->request->getPost('judul'),
'isi' => $this->request->getPost('isi'),
'gambar' => $upload->getName()
);
}
$model->edit_data($id,$data);
return redirect()->to('./blog')->with('berhasil', 'Data Berhasil di Ubah');
}
public function hapus($id){
$model = new ModelsBlog();
$dt = $model->PilihBlog($id)->getRow();
$model->HapusBlog($id);
$gambar = $dt->gambar;
$path = '../public/assets/blog/images/';
#unlink($path.$gambar);
return redirect()->to('./blog')->with('berhasil', 'Data Berhasil di Hapus');
}
}
ModelsBlog.php :
use CodeIgniter\Model;
class ModelsBlog extends Model
{
protected $table = 'artikel';
public function getArtikel()
{
return $this->findAll();
}
public function SimpanBlog($data)
{
$query = $this->db->table($this->table)->insert($data);
return $query;
}
public function PilihBlog($id)
{
$query = $this->getWhere(['id' => $id]);
return $query;
}
public function edit_data($id,$data)
{
$query = $this->db->table($this->table)->update($data, array('id' => $id));
return $query;
}
public function HapusBlog($id)
{
$query = $this->db->table($this->table)->delete(array('id' => $id));
return $query;
}
}
And this is the view.php:
<body style="width: 70%; margin: 0 auto; padding-top: 30px;">
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2><?php echo $artikel->judul; ?></h2>
</div>
</div>
</div>
<hr>
<div class="row">
<div class="col-lg-12">
<div class="row">
<?php
if (!empty($artikel->gambar)) {
echo '<img src="'.base_url("assets/blog/images/$artikel->gambar").'" width="30%">';
}
?>
<?php echo $artikel->isi; ?>
</div>
</div>
</div>
</body>
i cant find any solutions for this error, pls help thank you very much
Let's go over what you're telling the code to do.
First, you make a call to /blog. If you have auto-routing turned on this will put you forward to the controller named 'Blog'.
class Blog extends BaseController
And since you do not extend the URL with anything, the 'index' method will be called.
public function index()
{$data = [
'title' => 'artikel'
];
$model = new ModelsBlog();
if (!$this->validate([]))
{
$data['validation'] = $this->validator;
$data['artikel'] = $model->getArtikel();
return view('view_list',$data);
}
}
The index method sets $data to an array filled with 'title' => 'artikel'. And then fills $model with a new ModelsBlog.
class ModelsBlog extends Model
There is no __construct method defined in ModelsBlog so just the class is loaded and specific execution related to $model stops there, which is fine.
Then, the index() from Blog goes on and checks whether or not $this->validate([]) returns false. Since there's no else statement, if $this->validate([]) were to return true, code execution would stop there. So we'll assume $this->validate([]) returns false. So far so good, there's nothing weird going on with your code.
However, IF $this->validate([]) returns false, you tell the index() to return the function called view(). Normally CodeIgniter would serve you the view you set as the first parameter. But since you also have a Blog method named 'view', CodeIgniter will try to reroute te request to that method. So in other words, the actual request you're trying to make is:
Blog::view()
And since you've stated that view() receives 1 mandatory parameter, the requests triggers an error. You can solve the problem by either renaming the view() method of Blog to something like 'show()' or 'read()'. Anything else that does not conflict with the native CodeIgniter view() function would be good.
Honestly though, you are sending through two parameters in the index() function call so I'm slightly confused why the error generated states you provided 0, but I hope at least you gain some insight from my answer and you manage to fix the problem.
If anyone could provide more information regarding this, feel free to comment underneath and I'll add your information to the answer (if it gets accepted).
I created a new project in Laravel that consumes all data from an API. For private data like a user profile, I need an access token to get the data.
Once I have an access token, how do I set the token as Auth::id() in Laravel? Or perhaps I can store the user profile as Auth::user() so that I can use #auth in a frontend blade file?
class CustomAuthController extends Controller
{
public function index()
{
return view('login');
}
public function store(Request $request)
{
$request->validate([
'phone' => 'required|numeric'
]);
$data = [
'phone' => $request->phone
];
$codeSent = GeneralFunction::WebRequestPublicApi('first-login', $data, null, null, null, true);
if($codeSent->status == "success")
{
return redirect('verify');
} else {
$errors = new MessageBag();
$errors->add("phone", "Invalid phone number");
return view('login')->withErrors($errors);
}
}
public function showVerify()
{
return view('verify');
}
public function verify(Request $request)
{
try {
$request->validate([
'verify' => 'required|size:6'
]);
$data = [
'token_code' => $request->verify,
'source' => 'web'
];
$token = GeneralFunction::WebRequestPublicApi('verify-login', $data, null, null, null, true);
if($token->status === "success")
{
$userData = GeneralFunction::WebRequestPublicApi('membership', null, 'GET', null, null, true, $token->results->access_token);
if($userData->status !== "error")
{
$user = (array) $userData->results[0];
$request->session()->put('token', $token->results->access_token);
Auth::attempt($user, false, false);
return redirect('/');
}
} else {
$errors = new MessageBag();
$errors->add("verify", "Invalid Token");
return view('verify')->withErrors($errors);
}
} catch (Exception $e) {
$errors = new MessageBag();
$errors->add("verify", $e->getMessage());
return view('verify')->withErrors($errors);
}
}
}
I tried using Auth::attempt, Auth::login(), and the other method, but all of these required a user table. My project does not have a database.
You can do something like following.
In the controller
if($auth_ok)
{
session(['user' => ['key' => 'value', 'key2' => 'value2'] ]); // set session data
return view('frontend');
}
In the view
$user = session('user', false);
#if(!$user) // if not logged in
do something
#else // logged in successfully
Welcome my user
#endif
Hope this helps.
i guess the best thing you need to do is to use sqlite and once you got login from your api create a new user from it or find if there is existing already and Auth::login($newUser);
After register redirect to this page.
I want enter this code. (Of course mobile number and the code save in database and send a sms to mobile).
How to enter session code number?
Code
web.php
Route::get('/code', 'HomeController#code')->name('code');
Route::post('/send', 'HomeController#send')->name('send');
RegisterController.php
public function register(Request $request, User $user)
{
$code = rand(10000,99999);
$user = \App\User::create([
'first_name' => $request->first_name,
.
.
.
.
return redirect()->route('code',['mobile'=>$request->mobile]);
HomeController.php
public function code()
{
return view('Home.send');
}
public function send(Request $request)
{
$mobile = $request->session()->get('mobile');
$user = User::whereCode($request->code)
->whereMobile($mobile)
->firstOrFail();
if($user){
$user->verification_code = 1;
$user->save();
alert()->success('ok');
return redirect()->back();
} else {
alert()->error('error');
return redirect()->back();
}
}
send.blad,php
<form action="{{ route('send') }}" method="post">
{{ csrf_field() }}
<div class="form-group">
<label for="code">Code</label>
<input type="text" class="form-control" name="code" id="code">
</div>
<div class="form-group">
<button type="submit" class="btn btn-danger" id="btn-ok">OK</button>
</div>
</form>
I get this error
404
I have verification_code in users table. I want In case of enter true code and mobile number, verification_code change to 1
Take a look on Retrieving Single Models - Not Found Exceptions.
The firstOrFail method will retrieve the first result of the query;
however, if no result is found, a
Illuminate\Database\Eloquent\ModelNotFoundException will be thrown.
If the exception is not caught, a 404 HTTP response is automatically sent
back to the user. It is not necessary to write explicit checks to
return 404 responses when using these methods.
So, you can try catch the exeption:
try {
$mobile = $request->session()->get('mobile');
$user = User::whereCode($request->code)
->whereMobile($mobile)
->firstOrFail();
$user->verification_code = 1;
$user->save();
} catch (Illuminate\Database\Eloquent\ModelNotFoundException $e) {
return redirect()->back()->with('alert', 'error');
}
return redirect()->back()->with('success', 'ok');
Or otherwise use first instead of firstOrFail, which will return null if there is no record that meets the where conditions:
$mobile = $request->session()->get('mobile');
$user = User::whereCode($request->code)
->whereMobile($mobile)
->first();
if(empty($user)){
return redirect()->back()->with('alert', 'error');
}
$user->verification_code = 1;
$user->save();
return redirect()->back()->with('success', 'ok');
I am going to insert and update values using my addpermission function in my Controller
public function addPermission(Request $request, $id, $permission = null)
{
$this->validate($request, [
'status' => 'required'
]);
if(is_null($permission)) {
$permission = new Permission;
$msg = 'Permission has been added to your Collaborator successfully';
} else {
$permission = Permission::findOrFail($permission,['id'])->id;
$msg = 'Permission updated successfully';
}
$permission->status = $request->input('status');
$permission->project_id = $id;
$permission->collaborator_id = $request->input('cid');
$permission->save();
return redirect()->back()->with('info', $msg);
}
My routes
Route::post('projects/{project_id}/permission', [
'uses' => 'ProjectCollaboratorsController#addPermission',
'as' => 'projects.collaborators.permission',
// 'middleware' => ['auth']
]);
Data insert works properly, but update doesn't work.
When I click button to update it is inserts as new record to the database.
My table name is permission and have the following columns
id (autoincrement)
status
project_id
collaborator_id
What do I need to change to make the updating work?
I see an error in this line, this should return the permission object not the id of permission.
$permission = Permission::findOrFail($permission,['id'])->id;
Change to,
$permission = Permission::findOrFail($permission['id']);
You should write this. Hopefully This will solve your problem
public function addPermission(Request $request, $id, $permission)
{
$this->validate($request, [
'status' => 'required'
]);
$per = Permission::where('id', $permission)->first();
if(is_null($permission)) {
$permission = new Permission;
$msg = 'Permission has been added to your Collaborator successfully';
} else {
$permission = Permission::findOrFail($per)->id;
$msg = 'Permission updated successfully';
}
$permission->status = $request->input('status');
$permission->project_id = $id;
$permission->collaborator_id = $request->input('cid');
$permission->save();
return redirect()->back()->with('info', $msg);
}
I think you may need to put an optional route parameter in for permission id.
Route::post('projects/{project_id}/permission/{permission_id?}', [
'uses' => 'ProjectCollaboratorsController#addPermission',
'as' => 'projects.collaborators.permission',
// 'middleware' => ['auth']
]);
I'm having trouble in deleting a record that has file in it. Below is the code.
delete file method :
private function deletePDF(Journal $journal) {
$exist = Storage::disk('file')->exists($journal->file);
if (isset($journal->file) && $exist) {
$delete = Storage::disk('file')->delete($journal->file);
if ($delete) {
return true;
}
return false;
}
}
Destroy method :
public function destroy(Journal $journal, EditionRequest $request) {
$this->deletePDF($journal);
$journal->delete();
return redirect()->route('edition', ['id' => $request->id]);
}
The result game me nothing, it's just return to the page where the record belongs and does not deleting the record. I used the same code for another project with the same laravel version and it's working, but for some reasons it doesn't work here and I'm a lil bit confused.
Update :
EditionRequest :
public function rules() {
// Cek apakah CREATE atau UPDATE
$id = $this->get('id');
if ($this->method() == 'PATCH') {
$volume_rules = 'required|integer|unique_with:edition,number,' . $id;
$number_rules = 'required|integer';
} else {
$volume_rules = 'required|integer|unique_with:edition,number';
$number_rules = 'required|integer';
}
return [
'volume' => $volume_rules,
'number' => $number_rules,
'cover' => 'sometimes|image|max:15000|mimes:jpeg,jpg,bmp,png',
];
}
If it returns to the same page as before, you probably have a validation error in your request!
You can check the errors easily by adding the following snippet to your view:
#if(count($errors) > 0)
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
#endif
With this you should be able to see what's going wrong. Let me know if it worked :)
edit
public function rules() {
// Cek apakah CREATE atau UPDATE
$id = $this->get('id');
if ($this->method() == 'PATCH') {
$volume_rules = 'required|integer|unique_with:edition,number,' . $id;
$number_rules = 'required|integer';
}
else if($this->method() == 'DELETE'){
//your delete validation rules rules
$volume_rules = ''
$number_rules= '';
}
else {
$volume_rules = 'required|integer|unique_with:edition,number';
$number_rules = 'required|integer';
}
return [
'volume' => $volume_rules,
'number' => $number_rules,
'cover' => 'sometimes|image|max:15000|mimes:jpeg,jpg,bmp,png',
];
}
You might even want to not use the request youre using now, which would give you this:
public function destroy(Journal $journal, Request $request)