i'm new in Laravel and i'm building a simple user registration system.
When i access edit route, it seems that it's not getting the requested resource data.
I did some research and all the stuff i read, is already in place. Am i missing something?
web.php(router):
use Illuminate\Support\Facades\Route;
// USER PAGES:
Route::resource('users', 'UsersController');
UsersController.php:
namespace App\Http\Controllers;
use App\Users;
use Illuminate\Http\Request;
class UsersController extends Controller
{
/**
* Show the form for editing the specified resource.
*
* #param \App\Users $users
* #return \Illuminate\Http\Response
*/
public function edit(Users $users)
{
return view('dashboard.user.edit', compact('users'));
}
/**
* Remove the specified resource from storage.
*
* #param \App\Users $users
* #return \Illuminate\Http\Response
*/
public function destroy(Users $users)
{
$users->delete();
return redirect()->route('users.index')
->with('success', "User was removed successfully.");
}
}
edit.blade.php:
<form id="user-data" action="{{route('users.update',$users->id)}}" method="POST" enctype="multipart/form-data">
#csrf
#method('PUT')
<input type="file" id="input-user-photo" name="user_avatar" style="display: none;">
<div class="card">
<div class="card-header">User Data</div>
<div class="card-body card-block">
<div class="form-group">
<div class="input-group">
<div class="input-group-addon">
<i class="fa fa-user"></i>
</div>
<input type="text" id="username" name="name" placeholder="Username" class="form-control" value="{{$users->name}}">
</div>
</div>
<div class="form-group">
<div class="input-group">
<div class="input-group-addon">
<i class="fa fa-envelope"></i>
</div>
<input type="email" id="email" name="email" placeholder="Email" class="form-control" value="{{$users->email}}">
</div>
</div>
<div class="form-group">
<div class="input-group">
<div class="input-group-addon">
<i class="fa fa-asterisk"></i>
</div>
<input type="password" id="password" name="password" placeholder="Password (For not changing, leave it blank)" class="form-control">
</div>
</div>
<div class="form-group">
<div class="input-group">
<div class="input-group-addon">
<i class="fa fa-asterisk"></i>
</div>
<input type="password" id="password-confirmation" placeholder="Password Confirmation" class="form-control">
</div>
</div>
<div class="form-actions form-group">
<a class="btn btn-secondary btn-md" href="<?php echo $_SERVER['HTTP_REFERER']; ?>">Cancel</a>
<button type="submit" class="btn btn-success btn-md">Submit</button>
</div>
</div>
</div>
</form>
On Screen (URL: /users/{{$anyUserId}}/edit):
Also, when i access destroy route it reaches the right controller's method "destroy" and even redirects properly, with success message, as specified in the method, but the resource is not deleted from database. In both cases, it seems to me that it is not finding the resource to inject as parameter within these methods.
Any clues? Thx in advance!
If the resource name is users the route parameter would be user (singular). The route parameters are by default the singular version of the resource name when using resource routing.
For implicit route model binding to work you need the typehinted parameter of your methods to match the route parameter:
public function edit(Users $user)
public function destroy(Users $user)
Side note: usually Model names are singular and their tables are plural.
Related
i hope you are doing good.
i'am new to laravel and i searched a lot but no chance.
So i hava a form it contain fields to submit a comment here is the code :
<!-- comment -->
<div class="clearfix"></div>
<div class="margin-top-35"></div>
<div class="utf-inner-blog-section-title">
<h4><i class="icon-line-awesome-comments-o"></i> Laisse votre commentaire</h4>
</div>
<div class="margin-top-15"></div>
<input type="hidden" name="prop_id" id="prop_id" value="{{ $proprety->id }}">
<div id="add-comment">
<form class="add-comment" action="/commentannonce" method="POST">
#csrf
<input type="hidden" name="prop_id" value="{{ $proprety->id }}">
<fieldset>
<div class="row">
<div class="col-md-6">
<input type="text" placeholder="Nom Complet*" value="" name="nom"
required />
</div>
<div class="col-md-6">
<input type="email" placeholder="Adresse Email *" value="" name="email"
required />
</div>
<div class="col-md-6">
<input type="tel" placeholder="Numéro de téléphone *" value=""
name="telephone" required />
</div>
<div class="col-md-6">
<input type="text" placeholder="Sujet" value="" name="sujet"
required />
</div>
<div class="col-md-12">
<textarea cols="30" placeholder="Commentaire..." rows="2" name="commentaire" required></textarea>
</div>
</div>
</fieldset>
<div class="utf-centered-button">
<button type="submit" class="button">Submit Comment</button>
</div>
<div class="clearfix"></div>
</form>
</div>
<!-- comment -->
when i submit this form it store in the database normally.
here is my model for the comment
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Annoncecomment extends Model
{
use HasFactory;
protected $fillable = [
'prop_id',
'nom',
'telephone',
'email',
'sujet',
'commentaire',
];
}
and this is my controller for the comment :
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request){
$form_data = array(
'prop_id' => $request->prop_id,
'nom' =>$request->nom,
'telephone' => $request->telephone,
'sujet'=>$request->sujet,
'email' =>$request->email,
'commentaire'=>$request->commentaire,
);
$commentaire = Annoncecomment::create($form_data);
$user = User::first();
$commentaire = Annoncecomment::where('prop_id',$request->prop_id)->count();
$commentaires = Annoncecomment::where('prop_id',$request->prop_id)->orderBy('id','desc')->get();
$user = User::first();
return redirect('/proprety/'.$request->prop_id)->with([ 'commentaire'=>$commentaire, 'commentaires'=>$commentaires]);
}
So now i need to display these comments on a property page so i added code to property controller and i made it like this where $commentaires and commentaire are my variables one who get count and seconde to display.
$commentaire = Annoncecomment::where('prop_id',$proprety)->count();
$commentaires = Annoncecomment::where('prop_id',$proprety)->orderBy('id','desc')->get();
$rate = DB::table('clients')
->join('ratings', 'ratings.client', '=', 'clients.id')
->where('ratings.client',$proprety->client)->sum('star_rating');
$rateC = DB::table('clients')
->join('ratings', 'ratings.client', '=', 'clients.id')
->where('ratings.client',$proprety->client)->count();
if($rateC == 0){
$rate = 0;
}else{
$rate = $rate/$rateC;
}
return view('client.propretry.showProprety')->with(["commentaire"=>$commentaire, "commentaires"=>$commentaires,"rate"=>$rate,'cat'=>$cat,'area'=>$area,'price'=>$price,'type'=>$type,'client'=>$client,'similair'=>$similar,'image'=>$image,"states"=>$state,"proprety"=>$proprety]);
Back to the view of the property page i made a foreach but it dont display data and there is NO error or something in the console i made my for each like this :
section class="comments">
<div class="utf-inner-blog-section-title">
<h4><i class="icon-line-awesome-commenting-o"></i> Commentaires ({{ $commentaire->count() }})</h4>
</div>
<ul>
#foreach ($commentaires as $i)
<li>
<div class="avatar"><img src="/assets/media/avatars/blank.png" alt="" /></div>
<div class="comment-content">
<div class="arrow-comment"></div>
<div class="comment-by">{{ $i->nom }}
<span class="date">{{ date('F j, Y', strtotime($i->created_at)) }}</span>
#if (Auth::user())
<a href="#" data-id="{{ $i->id }}" id="replay"
class="reply"><i class="fa fa-reply"></i> Répondre</a>
#endif
</div>
<p>{{ $i->commentaire }}</p>
</div>
<ul>
What i did wrong ?
I know this is a little bit long but i'am struggling for 5 hours now.
Thank you very much
UPDATE UPDATE :
when i change this, from property controller it display all the comment but not the specifique comment for the prop :
this :$commentaires = Annoncecomment::where('prop_id',$proprety)->get();
to this : $commentaires = Annoncecomment::all();
Please pass the data in view method as second parameter not in with;
return view('client.propretry.showProprety', ["commentaire"=>$commentaire, "commentaires"=>$commentaires,"rate"=>$rate,'cat'=>$cat,'area'=>$area,'price'=>$price,'type'=>$type,'client'=>$client,'similair'=>$similar,'image'=>$image,"states"=>$state,"proprety"=>$proprety]);
I'm developing a Laravel app, and have setup a login page, but I'm trying to figure out why my login form isn't posting.
<form role="form" method="post" action="{{ route('login.perform') }}">
<div class="form-group">
<label class="form-control-label">Email address</label>
#if ($errors->has('username'))
<span class="text-danger text-left">{{ $errors->first('username') }}</span>
#endif
<div class="input-group input-group-merge">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-user"></i></span>
</div>
<input type="email" class="form-control" id="input-email" placeholder="name#example.com">
</div>
</div>
<div class="form-group mb-4">
<div class="d-flex align-items-center justify-content-between">
<div>
<label class="form-control-label">Password</label>
#if ($errors->has('password'))
<span class="text-danger text-left">{{ $errors->first('password') }}</span>
#endif
</div>
<div class="mb-2">
Lost password?
</div>
</div>
<div class="input-group input-group-merge">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-key"></i></span>
</div>
<input type="password" class="form-control" id="input-password" placeholder="Password">
<div class="input-group-append">
<span class="input-group-text">
<a href="#" data-toggle="password-text" data-target="#input-password">
<i class="fas fa-eye"></i>
</a>
</span>
</div>
</div>
</div>
<div class="mt-4">
<button type="button" class="btn btn-sm btn-primary btn-icon rounded-pill">
<span class="btn-inner--text">Sign in</span>
<span class="btn-inner--icon"><i class="fas fa-long-arrow-alt-right"></i></span>
</button>
</div>
</form>
This is the controller that handles the login request.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\LoginRequest;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
/**
* Display login page.
*
* #return Renderable
*/
public function show()
{
return view('auth.login');
}
/**
* Handle account login request
*
* #param LoginRequest $request
*
* #return \Illuminate\Http\Response
*/
public function login(LoginRequest $request)
{
$credentials = $request->getCredentials();
if(!Auth::validate($credentials)):
return redirect()->to('login')
->withErrors(trans('auth.failed'));
endif;
$user = Auth::getProvider()->retrieveByCredentials($credentials);
Auth::login($user);
return $this->authenticated($request, $user);
}
/**
* Handle response after user authenticated
*
* #param Request $request
* #param Auth $user
*
* #return \Illuminate\Http\Response
*/
protected function authenticated(Request $request, $user)
{
return redirect()->intended();
}
}
This is the web.php route.
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\HomeController;
use App\Http\Controllers\TeacherController;
use App\Http\Controllers\UserController;
use App\Http\Controllers\Auth\RegisterController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group that
| contains the "web" middleware group. Now create something great!
|
*/
Route::group(['namespace' => 'App\Http\Controllers'], function()
{
/**
* Home Routes
*/
Route::get('/', 'HomeController#welcome')->name('welcome');
Route::group(['middleware' => ['guest']], function() {
/**
* Register Routes
*/
Route::get('/register', 'RegisterController#show')->name('register.show');
Route::post('/register', 'RegisterController#register')->name('register.perform');
/**
* Login Routes
*/
Route::get('/login', 'LoginController#show')->name('login.show');
Route::post('/login', 'LoginController#login')->name('login.perform');
});
Route::group(['middleware' => ['auth']], function() {
/**
* Logout Routes
*/
Route::get('/logout', 'LogoutController#perform')->name('logout.perform');
});
});
The database is setup, migrated and is appearing in phpMyAdmin, routes controllers and requests are all setup correctly to my understanding.
Any help is appreciated, cheers.
The reason why the form can't submit is that you don't have submit button, add the type="submit" to the <button> will resolve the issue:
<button type="submit" class="btn btn-sm btn-primary btn-icon rounded-pill">
I read the comments, and you said the form is loaded but does not send any data. Please show how you get data in the controller, and the route also, that will help another find out the problem.
csrf is missing in your form
Try this
<form role="form" method="post" action="{{ route('login.perform') }}">
#csrf
...
The reason why the form can't submit is that you don't have submit button, add the type="submit" to the will resolve the issue:
<button type="submit" class="btn btn-sm btn-primary btn-icon rounded-pill">
and csrf is missing in your form
Try this
<form role="form" method="post" action="{{ route('login.perform') }}">
#csrf
...
I created an edit form to update values in my database and then show it on the main page. The problem is that it doesn't save the data to DB.
the request passes: Status Code: 302 Found
with all the values that I want to change (for example adding phone and mail):
effective_date_practitioner: 2019-01-01
expiry_date_practitioner:
phone_number_practitioner: 918273645
mobile_number_practitioner:
email_practitioner: test#test.pl
practitioner_specialty_id_update: 1
effective_date_specialty: 2019-01-01
expiry_date_specialty:
Edit blade
<div class="edit-practitioner" style="display: none;">
<form style="box-shadow: none;" action="/practitioner/update/{{$practitioner->practitioner_id}}" method="post"
class="j-pro" id="update-practitioner-form">
#csrf
<div class="j-content">
<div id="j-row-id" class="j-row">
<div class="row">
<div class="col-sm-12 col-lg-12 col-xl-5">
<div class=" j-unit">
<div class="j-divider-text j-gap-top-20 j-gap-bottom-45">
<span>Practitioner Information</span>
</div>
<label class="j-label">{{trans('personalData.effectiveDate')}}</label>
<div class="j-input">
<input type="date" value="{{$practitioner->effective_date}}"
name="effective_date_practitioner">
</div>
<label class="j-label">{{trans('personalData.expiryDate')}}</label>
<div class="j-input">
<input type="date" value="{{$practitioner->expiry_date}}"
name="expiry_date_practitioner">
</div>
<label class="j-label">{{trans('personalData.phoneNumber')}}</label>
<div class="j-input">
</label>
<input type="tel" value="{{$practitioner->phone}}"
name="phone_number_practitioner">
</div>
<label class="j-label">{{trans('personalData.mobileNumber')}}</label>
<div class="j-input">
<input type="tel" value="{{$practitioner->mobile}}"
name="mobile_number_practitioner">
</div>
<label class="j-label">{{trans('personalData.email')}}</label>
<div class="j-input">
<input type="email" value="{{$practitioner->email}}"
name="email_practitioner">
</div>
</div>
</div>
<div class="col-xl-1 j-unit"></div>
<div class="col-sm-12 col-lg-12 col-xl-6">
<div class="j-divider-text j-gap-top-20 j-gap-bottom-45">
<span>{{trans('settings.specialty')}}</span>
</div>
<select name="practitioner_specialty_id_update"
id="practitioner_specialty_id_update"
class="form-control-practitioner required">
#foreach($specialties as $specialty)
<option
value="{{$specialty->specialty_id}}">{{$specialty->name}}</option>
#endforeach
</select>
<label class="j-label">{{trans('personalData.effectiveDate')}}</label>
<div class="j-input">
<input type="date" value="{{$practitioner_specialty->effective_date}}"
name="effective_date_specialty">
</div>
<label class="j-label">{{trans('personalData.expiryDate')}}</label>
<div class="j-input">
<input type="date" value="{{$practitioner_specialty->expiry_date}}"
name="expiry_date_specialty">
</div>
</div>
</div>
</div>
<div class="j-divider j-gap-bottom-45 j-gap-top-10"></div>
<button type="submit"
class="btn btn-editpanel btn-success btn-round">Save changes
</button>
<!-- end /.footer -->
<button id="update-cancel-button-practitioner" type="button"
class="btn btn-editpanel btn-danger btn-round">Cancel
</button>
</div>
</form>
</div>
web.php
Route::post('/practitioner/update/{id}', 'Crud\Settings\PractitionerController#updatePractitioner')->name('updatePractitioner');
Controller:
<?php
namespace App\Http\Controllers\CRUD\Settings;
use App\Models\Practitioner;
use App\Models\PractitionerCompetenceLevel;
use App\Models\PractitionerSpecialty;
use App\Repositories\PractitionerRepository;
use Illuminate\Http\Request;
class PractitionerController extends CrudController
{
protected $repository;
public function __construct(PractitionerRepository $repository)
{
$this->middleware('auth');
$this->repository = $repository;
}
public function updatePractitioner($id, Request $request)
{
$this->validate($request, [
'effective_date_practitioner' => 'required',
'effective_date_specialty' => 'required',
]
);
$input = $request->all();
$input['data'][$this->repository->getIdName()] = $id;
$this->repository->update($input['data']);
return back()->with('successUpdate', 'Practitioner has been updated!');
}
}
My guess is that the data I want to update belongs to two different tables in DB one called practitioner and the other one called practitioner_specialty
As per your code you are trying to do mass assignment to your model
You may do this using the $fillable property on the model
protected $fillable = ['effective_date_practitioner','effective_date_specialty',......];
And you can use attach() method to updated data in related tables
For my own project I am needing login/registering functions. But I don't to use the standard Laravel login pages and such. I want to use the Login form I have in my header. But I can't seem to figure out how to make the Controller use the login information from my header form and handle it in the desired way.
My login form is an include in my header and the code is as following:
<li class="single-icon nk-drop-item">
<a href="" class="no-link-effect">
<span class="fa fa-sign-in"></span>
</a>
<div class="dropdown">
<div class="nk-sign-form">
<div class="nk-sign-form-container">
<!-- START: Login Form -->
<form class="nk-sign-form-login active" action="{{ url('/') }}">
{{ csrf_field() }}
<h4>Log In</h4>
<input class="form-control " type="text" placeholder="Username" id="username" name="username" value="{{ old('username') }}" required autofocus>
<div class="nk-gap"></div>
<input class="form-control" type="password" placeholder="Password" id="password" name="password" required>
<div class="nk-gap"></div>
<div class="form-check pull-left">
<label class="form-check-label">
<input type="checkbox" class="form-check-input"> Remember Me
</label>
</div>
<button class="nk-btn nk-btn-color-white text-dark-1 pull-right">Log In</button>
<div class="clearfix"></div>
<div class="nk-gap"></div>
<div class="text-right">
<a class="nk-sign-form-register-toggle" href="#">Register</a> |
<a class="nk-sign-form-lost-toggle" href="#">Lost Password?</a>
</div>
</form>
<!-- END: Login Form -->
<!-- START: Lost Password Form -->
<form class="nk-sign-form-lost" action="#">
<h4>Lost Password</h4>
<input class="form-control" type="text" placeholder="Username or Email">
<div class="nk-gap"></div>
<button class="nk-btn nk-btn-color-white text-dark-1 pull-right">Get New Password</button>
<div class="clearfix"></div>
<div class="nk-gap"></div>
<a class="nk-sign-form-login-toggle pull-right" href="#">Back to Log In</a>
</form>
<!-- END: Lost Password Form -->
<!-- START: Register Form -->
<form class="nk-sign-form-register" action="#">
<h4>Register</h4>
<input class="form-control" type="text" placeholder="Username">
<div class="nk-gap"></div>
<input class="form-control" type="email" placeholder="Email">
<div class="nk-gap"></div>
<div>A password will be emailed to you.</div>
<div class="nk-gap"></div>
<button class="nk-btn nk-btn-color-white text-dark-1 pull-right">Register</button>
<div class="clearfix"></div>
<div class="nk-gap"></div>
<a class="nk-sign-form-login-toggle pull-right" href="#">Back to Log In</a>
</form>
<!-- END: Register Form -->
</div>
</div>
</div>
My LoginController is as following:
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function username()
{
return 'username';
}
public function rules()
{
return [
'login' => 'required',
'password' => 'required'
];
}
}
If someone could help me in the way of pointing me in the right direction it would be greatly appreciated. If I need to post some more code I'll be happy to. Thanks in advance
edit: I've uploaded the code to the domain: verenmanta.site, you can view the header and login form over there if that may help!
I wish to clarify the steps to get a new form properly submitted to my database using Laravel 5.2 and Bootstrap 3.
I have the login/register pages set up properly using Laravel's defaults, and they work fine. I now want to create a user profile page accessible to authenticated users. I am using one row in the database for all of their user info. Some fields were filled in during registration, and now I want them to have access to additional fields (while restricting access to certain registration fields like user name).
In the example code below, there are fields to upload a personal photo, enter a first name, and enter a last name. (None of these were done during registration.)
What I have already done (all code is below):
Create the view profile.blade.php
Create a controller profileController.php
Update routes.php in the controller directory.
A note:
When I try to submit the form as it appears below, I get, Type error: Argument 1 passed to App\Http\Controllers\ProfileController::update() must be of the type array, none given.
What are the next steps required to get this page working properly?
profile.blade.php:
#extends('layouts.app')
#section('content')
<div class="container" style="padding-top: 30px;">
<h1 class="page-header">User Profile</h1>
<div class="row">
<!-- left column -->
<div class="col-md-4 col-sm-6 col-xs-12">
<div class="text-center">
<i class="fa fa-user fa-5x"></i>
<h6>Please upload a photo...</h6>
<input type="file" class="text-center center-block well well-sm">
</div>
</div>
<!-- edit form column -->
<div class="col-md-8 col-sm-6 col-xs-12 personal-info">
<form class="form-horizontal" role="form" method="POST" action="{{ url('/profile') }}">
{!! csrf_field() !!}
<div class="form-group">
<label class="col-lg-3 control-label">First name:</label>
<div class="col-lg-8">
<input class="form-control" value="<?php echo Auth::user()->firstname; ?>" id="firstname" name="firstname" placeholder="First..." type="text">
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Last name:</label>
<div class="col-lg-8">
<input class="form-control" value="<?php echo Auth::user()->lastname; ?>" id="lastname" name="lastname" placeholder="Last..." type="text">
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label"></label>
<div class="col-md-8">
<button type="submit" class="btn btn-primary">
<i class="fa fa-btn fa-user"></i>Submit
</button>
<span></span>
<input class="btn btn-default" value="Cancel" type="reset">
</div>
</div>
</form>
</div>
</div>
</div>
#endsection
profileController.php:
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Http\Request;
class ProfileController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('profile');
}
protected function update(array $data)
{
return User::update([
'firstname' => $data['firstname'],
'lastname' => $data['lastname'],
]);
}
}
And I added the following in the routes middleware:
Route::get('/profile', 'ProfileController#index');
Route::post('/profile', 'ProfileController#update');
It's a protocol mismatch, since you're POSTing your form. You need to change your route to
route::post('/profile', 'ProfileController#index');
Using a validator is a great idea, since it will make sure that your input is exactly what you need it to be, and all required fields are filled out.
Your update function should look something like this:
public function update(Request $request)
{
$first_name = $request->input('firstname');
$last_name = $request->input('lastname');
$id = Auth::user()->id;
$user = \App\User::find($id);
$user->firstname = $first_name;
$user->lastname = $last_name;
$user->save();
return view('profile');
// Sanitize, validate, before you do ANYTHING with update
// Instead of returning the update result, you can instead show another view or forward them to another page.
}