Function is not returning true value - laravel

I have a Model that takes care of followers:
Schema::create('follows', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id');
$table->unsignedBigInteger('follower_id');
$table->dateTime('followed_date')->nullable();
$table->dateTime('unfollowed_date')->nullable();
$table->timestamps();
$table->unique(['user_id', 'follower_id']);
});
The issue is I have this piece of code in the User.php model that is not returning true when I follow the user:
public function following()
{
return $this->hasMany(Follow::class);
}
public function isFollowing($profileUser)
{
return $this->following()->where(['user_id' => $profileUser, 'follower_id' => auth()->id()])->exists();
}
Here is the code that I have in the view:
#if(auth()->user()->isFollowing($profileUser->id) == FALSE)
<li>
<form action="/follow/{{ $profileUser->name }}" method="POST">
{{ csrf_field() }}
<input type="hidden" name="user_id" value="{{ $profileUser->id }}">
<input type="hidden" name="follower_id" value="{{ auth()->user()->id }}">
<button type="submit">Follow</button>
</form>
</li>
#else
<li>
<form action="/follow/{{ $profileUser->name }}" method="POST">
{{ csrf_field() }}
<input type="hidden" name="user_id" value="{{ $profileUser->id }}">
<input type="hidden" name="follower_id" value="{{ auth()->user()->id }}">
<button type="submit">Unfollow</button>
</form>
</li>
#endif
Does anyone know why my code is not working? Thanks in advance!

So the issue was I didn't even know the structure of my Model,
I confused the user_id column with the $request->follower_id,
I'm going to make it following_id to make it more clear what the relationship is...
A user will be "following" another user... simple!

Related

Laravel 9 Update Form Values with controller MVC

I want to update my input values ​​in the form in my database by sending them from the route to the controller. What am I doing wrong? Can you help me? I tried the #method('PUT') method before. It's a bit confusing. I am sharing the codes. I will be very happy if you can help, thank you.
...
<div class="modal-body">
<div class="form-group text-center"
style="position: center; margin-top:3em;">
<form action="{{ 'edit-name/' . $user->id }}" method="POST"
enctype="multipart/form-data">
#csrf
<label for="fname">
{{ __('welcome.fullname') }}:</label>
<input name="name1" type="hidden"
placeholder="{{ $user->name }}">
</div>
<br>
<br>
<br>
{{-- //Name Edit Button --}}
<button type="submit"
class="btn-sm app-btn-secondary">{{ __('welcome.confirm') }}</button>
...
my route and controller
...
Route::get('edit-name/{id}', [HomeController::class, 'editname']);
...
...
public function editname(Request $request, $id){
dd(1);
$user= Auth::user();
dd($user);
$id=$request->id;
$name=$request->input('name1');
$isUpdateSuccess = User::where('id', $id) ->update(['name1'=>$name, ]);
if($isUpdateSuccess)
echo '<h1>Update Success</h1>';
else echo '<h1>Update Failed </h1>';
}
...
you are sending the data from modal using POST method but in your route you are using this data by GET method. I will suggest you to use POST method so that user_id will not be append in URL, so try this,
Your blade
<div class="modal-body">
<div class="form-group text-center" style="position: center; margin-top:3em;">
<form action="{{ 'edit-name' }}" method="POST" enctype="multipart/form-data">
#csrf
<input type="hidden" name="id" placeholder="{{ $user->id }}">
<label for="fname">
{{ __('welcome.fullname') }}:</label>
<input name="name1" type="text" placeholder="{{ $user->name }}">
</div>
<br>
<br>
<br>
{{-- //Name Edit Button --}}
<button type="submit" class="btn-sm app-btn-secondary">{{__('welcome.confirm') }}</button>
Your route
Route::post('/edit-name', [HomeController::class, 'editname']);
Your controller
public function editname(Request $request){
// dd(1);
$user= Auth::user();
// dd($user);
$id=$request->id;
$name=$request->input('name1');
$isUpdateSuccess = User::where('id', $id) ->update(['name1'=>$name, ]);
if($isUpdateSuccess)
echo '<h1>Update Success</h1>';
else echo '<h1>Update Failed </h1>';
}
Change action
from
action="{{ 'edit-name/'. $user->id }}"
to
action="{{ url('edit-name',$user->id) }}"

create dynamically checkbox in blade

I´m traying to create list of checkbox in my blade with all roles that i have in my DB. I´m doing loop to get all roles and if to check that roles have this user that i´m doing edit:
#foreach($roles as $rol)
#foreach ($selRoles as $role)
#if ($role == $rol->id)
<div class="col-md-4">
<input type="checkbox" name="rol" checked=checked class="form-check-input" value="{{ $rol->id }}" id="{{ $rol->id }}">
{{ $rol->name }}
</div>
#else
<div class="col-md-4">
<input type="checkbox" name="rol" class="form-check-input" value="{{ $rol->id }}" id="{{ $rol->id }}">
{{ $rol->name }}
</div>
#endif
#endforeach
#endforeach
With this code, my problem it´s that all my roles it´s duplicated. In my controller i have this:
public function edit(User $usuario)
{
$roles = Bouncer::role()->orderBy('title', 'DESC')->get();
$selRoles = $usuario->roles->pluck('id')->toArray(); //selRoles it´s roles from user
$usuario->load('roles');
return view('admin.empleados.edit', compact('usuario', 'roles','selRoles'));
}
and retult in blade it´s:
teleoperadora
teleoperadora
teleoperadora
repartidor
repartidor
repartidor
prueba
prueba
prueba
Jefe de equipo
Jefe de equipo
Jefe de equipo
jefa-sala
jefa-sala
jefa-sala
instalador
instalador
for example. I don´t know that i´m doing bad for get this result in my blade. Anybody can help me please?
Thanks for read and help. Sorry for my english
Your roles get duplicated because you are using two foreach loops. Your selected roles are an array, so it should suffice to check if a role->id is in that array:
#foreach($roles as $role)
<div class="col-md-4">
<input type="checkbox" name="rol" #if(in_array($role->id, $selRoles))checked=checked#endif class="form-check-input" value="{{ $role->id }}" id="{{ $role->id }}">
{{ $role->name }}
</div>
#endforeach
The part #if(in_array($role->id, $selRoles))checked=checked#endif will check the checkbox if the role's id is in your array of selected roles.

How to fill the form checkboxes with checked data from database laravel 5.8

I'm having a problem in my update Form,
I create user with multiple roles assigned using checkboxes in my form, and when I need to update a user i get all the data into my update form input fields except the checkbox fields will be empty. Is there a way that I can get the checkbox checked with the data from database ?
Here's my User Model Relationship
public function roles()
{
return $this->belongsToMany(Role::class)->withTimestamps();
}
Here's my Role Model Relationship
public function users()
{
return $this->belongsToMany(User::class)->withTimestamps();
}
Here's my Edit User Form
<form action="{{ route('users.update',['user'=>$user]) }}" method="POST">
#method('PATCH')
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" class="form-control" value="{{ old('name') ?? $user->name }}">
<span class="text-danger">{{ $errors->first('name') }}</span>
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" name="email" class="form-control" value="{{ old('email') ?? $user->email }}">
<span class="text-danger">{{ $errors->first('email') }}</span>
</div>
<div class="form-group">
#foreach ($roles as $role)
<label for="role">{{ $role->name }}</label>
<input type="checkbox" name="role[{{$role->id}}]" value="{{ old($role->id) }}"
#if(in_array($role->id,old('role',[]) )) checked #endif >
#endforeach
<span class="text-danger">{{ $errors->first('role') }}</span>
</div>
#csrf
<button class="btn btn-primary" type="submit">Create</button>
</form>
Here's my Edit Function
public function edit(User $user)
{
$roles = Role::all();
return view('users.edit', compact('user', 'roles'));
}
I just wanted to know how can I pull data into my checkboxes from the database and mark them as checked
I guess you should check role id with the user role id:
#if(in_array($role->id, $user->roles->toArray())) checked #endif
Finally I found out the answer
<div class="form-group">
#foreach ($roles as $role)
<label for="role">{{ $role->name }}</label>
<input type="checkbox" name="role[]" value="{{ $role->id }}"
{{ $role->users->contains($user->id) ? 'checked' : '' }}
#if(in_array($role->id,old('role',[]))) checked #endif>
#endforeach
<span class="text-danger">{{ $errors->first('role') }}</span>
</div>

Value Displays Blank when I tried to edit in Laravel

I want to edit in laravel
In my controller I have this
public function edit(Book $book)
{
return view ('admin.book.edit')->with('book', $book)->with('authors', Author::all())->with('categories', Category::all());
}
In my index view for all books, I have this
<tbody>
#foreach($books as $book)
...
<td> {{ $book -> name }} </td>
<td>
<a href="{{ route('admin.book.edit',$book->id) }}">
<button class="btn btn-success">Edit</button>
</a>
</td>
...
My Edit view is like this
<form action="#" method="POST" enctype="multipart/form-data">
#csrf
<div class="form-group">
<label for="name">Book Name</label>
<input type="text" class="form-control" name="name" id="name" value="{{ $book->name }}" >
</div>
<div class="form-group">
<label for="about">About the Book </label>
<textarea name="about" id="about" cols="5" rows="5" class="form-control">{{ $book->about }}</textarea>
</div>
In my web.php
Route::get('/admin/book/edit', 'BooksController#edit')->name('admin.book.edit');
My table schema
Schema::create('books', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->text('about');
...
});
I was thinking this value="{{ $book->name }}" will return the value but it returned blank. Probably I am doing something wrong here.
Hi you don't define in your route Model bindings:
Change it to, so Laravel knows that the ID you pass in route should return Book Model. That you use in your edit function edit(Book $book)
Route::get('/admin/book/edit/{book}', 'BooksController#edit')->name('admin.book.edit');
Also take a look into Resource Controllers:
Route::resource('books', 'BooksController');
This will generate all routes you need view/edit/update/delete Check your routes bu running php artisan route:list
Read Docs for more info
They was an error in my route, so I change to this
Route::get('/admin/book/edit/{book}', 'BooksController#edit')->name('admin.book.edit');

Laravel Cannot retrieve a specific record from a form

I am outputting a list from a database table 'books' like this:
function edit()
{
$books = Book::all();
return view('layouts/editbooks', ['books' => $books]);
}
And displaying them like this:
#extends('layouts.master')
#section('title')
#section('content')
<h1>Edit Book</h1>
<form action="{{url('editbook')}}" method="GET">
{{ csrf_field() }}
#foreach ($books as $book)
<div>
<label>{{$book->title}}</label>
<input type='radio' value='{{$book->id}}' name='books[]'/>
</div>
#endforeach
<input type="submit" class="btn btn-warning form-control" value="Edit">
</form>
#endsection
I then want user to choose which record they want to edit by selecting a radio button, and upon clicking a submit button, redirect user to a new page with details of a book.
Therefore I am trying to get a book id from radio button and then if id matches, display everything from that record:
function editing(Request $request)
{
$edit = $request->books;
return view('layouts/editing', ['edit' => $edit]);
}
function updateEdit()
{
$books = DB::table('books')->where('id', $edit)->first();
}
And that is displayed in a view:
#extends('layouts.master')
#section('title')
#section('content')
<h1>Delete Book</h1>
<form action="{{url('removebook')}}" method="POST">
{{ csrf_field() }}
<div>
<input name="name" type="textbox" value="{{ old('name', $edit['name']) }}"/>
</div>
<input type="submit" name="submitBtn" value="Delete Book">
</form>
#endsection
However I get an error message saying:
Undefined index: name (View: C:\xampp\htdocs\laraveladvweb\resources\views\layouts\editing.blade.php)
What is causing the issue?
Isn't $edit just the id of the book?
try this
function editing(Request $request)
{
$edit = $request->books;
$book = DB::table('books')->where('id', $edit)->first();
return view('layouts/editing', ['edit' => $book]);
}
#extends('layouts.master')
#section('title')
#section('content')
<h1>Delete Book</h1>
<form action="{{url('removebook')}}" method="POST">
{{ csrf_field() }}
<div>
<input name="name" type="textbox" value="{{ old('name', $edit['name']) }}"/>
</div>
<input type="submit" name="submitBtn" value="Delete Book">
</form>
#endsection

Resources