I have a new problem. I'll try to give enough information.
I'm trying to display the names of the employees that have visited the customers, but as you can see it displays the names of the customers. Instead of Bryan or Granucci (these are the customers), it should say Madmin (I have only one user at the moment).
Screenshot
This is the drafts page
I'll add the code form my view, controller and model.
Drafts View
#extends('app')
#section('content')
#include('nav')
<div class="container">
#include('flash')
<div class="row">
<div class="col-md-2">
{!! Form::open(['method' => 'GET', 'action' => 'DraftsController#create']) !!}
{!! Form::submit('Create new draft', ['class' => 'btn btn-primary form-control']) !!}
{!! Form::close() !!}
</div>
</div>
<hr>
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">Search drafts</div>
<div class="panel-body">
{!! Form::open(array('url' => 'drafts/search', 'method' => 'post')) !!}
<div class="form-group">
<div class="col-md-2" align="right">
{!! Form::label('customer_name', 'Customer:') !!}
</div>
<div class="col-md-6">
{!! Form::text('customer_name', null, ['class' => 'form-control typeahead tt-query', 'autocomplete' => 'off', 'spellcheck' => 'false', 'placeholder' => 'Search...']) !!}
</div>
<div class="col-md-2" align="right">
{!! Form::label('customer_id', 'Customer ID:') !!}
</div>
<div class="col-md-2">
{!! Form::text('customer_id', null, ['class' => 'form-control', 'readonly' => 'readonly']) !!}
</div>
</div>
<br><br>
<div class="form-group">
<div class="col-md-2" align="right">
{!! Form::label('descr', 'Article:') !!}
</div>
<div class="col-md-6">
{!! Form::text('descr', null, ['class' => 'form-control typeahead tt-query', 'autocomplete' => 'off', 'spellcheck' => 'false', 'placeholder' => 'Search...']) !!}
{!! Form::hidden('reportgroup', null, ['class' => 'form-control']) !!}
</div>
<div class="col-md-2" align="right">
{!! Form::label('article_id', 'Article ID:') !!}
</div>
<div class="col-md-2">
{!! Form::text('article_id', null, ['class' => 'form-control', 'readonly' => 'readonly']) !!}
</div>
</div>
<br><br>
<div class="form-group">
<div class="col-md-2" align="right">
{!! Form::label('reference', 'Reference:') !!}
</div>
<div class="col-md-10">
{!! Form::text('reference', null, ['class' => 'form-control']) !!}
</div>
</div>
<br><br>
<div class="form-group">
<div class="col-md-12" align="right">
{!! Form::submit('Search', ['class' => 'btn btn-primary form-control']) !!}
</div>
</div>
{!! Form::close() !!}
#include('errors')
</div>
</div>
<div class="panel panel-default">
{!! Form::open(['method' => 'POST', 'action' => 'DraftsController#invoice']) !!}
<div class="panel-heading">Search results</div>
<div class="panel-body">
<table class="table">
<tr>
<th> </th>
<th>No</th>
<th>Employee</th>
<th>Customer</th>
<th>Reference</th>
<th>Draft created</th>
<th>Work date</th>
<th style="text-align:right">Total excl. VAT</th>
<th> </th>
</tr>
<?php $count = 0; ?>
#foreach ($result as $draft)
<tr>
<td><input type="checkbox" id="invoice_{{$draft['id']}}" name="invoice_{{$draft['id']}}"></td>
<td>{{ $draft['id'] }}</td>
<td>{{$draft['name'] }} ({{ $draft['user_id'] }})</td>
<td>{{$draft['name'] }} ({{ $draft['customer_id'] }})</td>
<td>{{ $draft['reference'] }}</td>
<td>{{ $draft['created_at'] }}</td>
<td></td>
<td style="text-align:right">{{ number_format($totals[$draft['id']],2) }}</td>
<td><input class="btn btn-danger" name="delete_{{$draft['id']}}" id="delete_{{$draft['id']}}" type="submit" value="X"></td>
</tr>
<?php $count++ ?>
#endforeach
</table>
<?php
if ($count == 0) {
print "No results";
}
else {
?>
<table>
<tr>
<td>
{!! Form::submit('Create invoice for selected drafts', ['class' => 'btn btn-primary form-control']) !!}
</td>
<td>
with invoice date
</td>
<td>
<input class="form-control" name="createDate" type="date" id="createDate" value="{{date('Y-m-d')}}">
</td>
<td>
and mail them to customer
</td>
<td>
<input type="checkbox" id="mailThem" name="mailThem">
</td>
</tr>
</table>
{!! Form::close() !!}
<?php
}
?>
</div>
</div>
</div>
</div>
</div>
#include('jsonArticles')
#include('jsonCustomers')
<script src="{{ asset('/js/typeahead.js') }}"></script>
<script src="{{ asset('/js/customers.js') }}"></script>
<script src="{{ asset('/js/articles.js') }}"></script>
#stop
Draftsheader Model
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class DraftHeader extends Model {
public function customer()
{
return $this->belongsTo('App\Customer');
}
public function user()
{
return $this->belongsTo('App\User');
}
public function lines()
{
return $this->hasMany('App\DraftLine');
}
protected $fillable = [
'user_id',
'employee_name',
'customer_id',
'name',
'name2',
'address',
'postcode',
'town',
'country',
'reference'
];
}
Drafts Controller
<?php
namespace App\Http\Controllers;
use Session;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Article;
use App\Customer;
use App\User;
use App\DraftHeader;
use App\DraftLine;
use App\InvoiceHeader;
use App\InvoiceLine;
use App\InvoiceMail;
use App\Http\Requests\DraftRequest;
use App\Http\Requests\DraftSearchRequest;
use App\Http\Requests\DraftLinesRequest;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
class DraftsController extends Controller {
/*
|--------------------------------------------------------------------------
| ArticlesController
|--------------------------------------------------------------------------
|
| Controller for Metis draft tasks
|
*/
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct() {
$this->middleware('auth:admin');
}
/**
* Get all articles
*
* #return array()
*/
private function allArticles() {
$allArticles = array();
$ff = Article::All()->toArray();
foreach ($ff as $ff1) {
$allArticles[] = array('name' => $ff1['descr'], 'id' => $ff1['id']);
}
return $allArticles;
}
/**
* Get all customers
*
* #return array()
*/
private function allCustomers() {
$allCustomers = array();
$ff = Customer::All()->toArray();
foreach ($ff as $ff1) {
$allCustomers[] = array('name' => $ff1['name'], 'id' => $ff1['id']);
}
return $allCustomers;
}
/**
* Get all uers
*
* #return array()
*/
private function allUsers() {
$allUsers = array();
$ff = User::All()->toArray();
foreach ($ff as $ff1) {
$allUsers[] = array('name' => $ff1['name'], 'id' => $ff1['id']);
//dd($allUsers);
}
return $allUsers;
}
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index() {
// Use request saved in session if applicable
$result = array();
if (Session::has('draft_search_request')) {
$request = Session::get('draft_search_request');
//dd($request);
$result = DraftHeader::query();
if (strlen(trim($request['customer'])) > 0) {
$result->where('name', 'LIKE', "%" . $request['customer'] . "%");
}
if (strlen(trim($request['user'])) > 0) {
$result->where('name', 'LIKE', "%" . $request['user'] . "%");
}
if (strlen(trim($request['reference'])) > 0) {
$result->where('reference', 'LIKE', "%" . $request['reference'] . "%");
}
if (strlen(trim($request['article'])) > 0) {
$result->DraftLine()->where('descr', 'LIKE', "%" . $request['article'] . "%");
}
//dd($result->toSql());
$result = $result->get()->toArray();
//dd($result);
}
else {
$result = DraftHeader::query()->where('created_at', '>', Carbon::yesterday())->get()->toArray();
}
// Get the total amount for each draft draft
$totals = array();
foreach ($result as $value) {
$total = DraftLine::selectRaw('sum(qty*netamount) AS total')->where('draft_header_id', '=', $value['id'])->get()->toArray();
$totals[$value['id']] = $total[0]['total'];
}
return view('drafts.search')->with('result', $result)->with('totals', $totals)->with('allArticles', $this->allArticles())->with('allCustomers', $this->allCustomers())->with('allUsers', $this->allUsers());
}
public function search(DraftSearchRequest $request) {
//Put request in session variable to use in view
$request1 = array('customer' => $request['customer'],'user' => $request['user'], 'reference' => $request['reference'], 'article' => $request['article']);
if ($request1['customer'] == "" && $request1['user'] == "" && $request1['reference'] == "" && $request1['article'] == "") {
session()->flash('draft_search_request', $request1);
}
else {
Session::put('draft_search_request', $request1);
}
return redirect ('drafts');
}
public function invoice(Request $request) {
//Create invoices for the selected drafts
//dd($request);
//dd($request->except('_token'));
$number_of_invoices = 0;
$draftdeleted = false;
$mail = false;
if (isset($request['mailThem']) && $request['mailThem'] == "on") {
$mail = true;
}
$invoicedate = $request['createDate'];
if (!checkdate(substr($invoicedate, 5, 2), substr($invoicedate, 8, 2), substr($invoicedate, 0, 4))) {
$invoicedate = "";
}
foreach($request->except('_token') as $key => $val) {
//dd($key);
if (substr($key, 0, 8) == "invoice_" && $val == "on") {
$draft_id = substr($key, 8);
// Create the invoice
// But only if there are lines
$draftheader = DraftHeader::findOrFail($draft_id)->toArray();
$draftlines = DraftHeader::findOrFail($draft_id)->lines()->get()->toArray();
if (count($draftlines) > 0) {
// Create the invoice header
$invoiceheader = InvoiceHeader::create($draftheader);
if ($invoicedate != "") {
$invoiceheader->created_at = $invoicedate;
$invoiceheader->save();
}
// Create the invoice lines
foreach ($draftlines as $draftline) {
$newline = new InvoiceLine;
$newline->article_id = $draftline['article_id'];
$newline->descr = $draftline['descr'];
$newline->qty = $draftline['qty'];
$newline->grossamount = $draftline['grossamount'];
$newline->discount = $draftline['discount'];
$newline->netamount = $draftline['netamount'];
$newline->taxrate = $draftline['taxrate'];
$newline->addition = $draftline['addition'];
$newline = $invoiceheader->lines()->save($newline);
}
// Delete the draft
DraftHeader::destroy($draft_id);
$number_of_invoices++;
if ($mail) {
// Add the invoice to the create and send queue (no recipient = to be processed)
$invoicemail = new InvoiceMail;
$invoicemail = $invoiceheader->mail()->save($invoicemail);
}
}
}
if (substr($key, 0, 7) == "delete_") {
// Delete the selected draft
$draft_id = substr($key, 7);
DraftHeader::destroy($draft_id);
session()->flash('flash_success', "Draft deleted");
$draftdeleted = true;
}
}
$andmailed = "";
if ($number_of_invoices > 0 && $mail) {
$andmailed = " and queued to be sent by mail";
}
if (!$draftdeleted) {
session()->flash('flash_success', $number_of_invoices . " invoice(s) created " . $andmailed);
}
$request1 = array('customer' => $request['customer'], 'user' => $request['user'], 'reference' => $request['reference'], 'article' => $request['article']);
if ($request1['customer'] == "" && ['user'] == "" && $request1['reference'] == "" && $request1['article'] == "") {
session()->flash('draft_search_request', $request1);
}
else {
Session::put('draft_search_request', $request1);
}
return redirect ('drafts');
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create() {
return view('drafts.create')->with('allCustomers', $this->allCustomers());
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store(DraftRequest $request) {
//dd($request);
// Get the customer information
/*
$this->validate($request, [
'reference' => 'required'
]);
*
*/
$customer = Customer::findOrFail($request['customer_id']);
$pass = array_merge($request->all(), $customer->toArray());
//dd($pass);
DraftHeader::create($pass);
//dd($request);
// Get the user information
/*
$this->validate($request, [
'reference' => 'required'
]);
*
*/
$user = User::findOrFail($request['user_id']);
$pass = array_merge($request->all(), $user->toArray());
//dd($pass);
DraftHeader::create($pass);
return redirect('drafts');
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id) {
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id) {
// Retrieve header and lines
//dd($id);
$draftheader = DraftHeader::findOrFail($id)->toArray();
//dd($draftheader);
$draftlines = DraftHeader::findOrFail($id)->lines()->get()->toArray();
//dd($draftlines);
// Get the draft's total
$drafttotal = 0;
$drafttotal_in = 0;
foreach ($draftlines as $line) {
$drafttotal = $drafttotal + ($line['qty'] * $line['netamount']);
$drafttotal_in = $drafttotal_in + (($line['qty'] * $line['netamount']) / 100 * (100 + $line['taxrate']));
}
return view('drafts.edit')->with('header', $draftheader)->with('lines', $draftlines)->with('drafttotal', $drafttotal)->with('drafttotal_in', $drafttotal_in)->with('allArticles', $this->allArticles());
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id, DraftLinesRequest $request) {
//dd($request->all());
// Save the draft header (again)
$draftheader = DraftHeader::findOrFail($id);
if ($draftheader->reference != $request['reference']) {
$draftheader->reference = $request['reference'];
$draftheader->save();
}
// Update the lines if there are changes
$requestcopy = $request->All();
reset($requestcopy);
foreach ($requestcopy as $key => $value) {
if (substr($key, 0, 11) == "grossamount") {
$lineid = substr($key, 11);
$draftline = Draftline::findOrFail($lineid);
$v_descr = 'descr' . $lineid;
$v_qty = 'qty' . $lineid;
$v_grossamount = 'grossamount' . $lineid;
$v_discount = 'discount' . $lineid;
$v_addition = 'addition' . $lineid;
if ($draftline->descr != $request[$v_descr] || $draftline->qty != $request[$v_qty] || $draftline->grossamount != $request[$v_grossamount] || $draftline->discount != $request[$v_discount] || $draftline->addition != $request[$v_addition]) {
$draftline->descr = $request[$v_descr];
$draftline->qty = $request[$v_qty];
$draftline->addition = $request[$v_addition];
$draftline->grossamount = $request[$v_grossamount];
$draftline->discount = $request[$v_discount];
$draftline->netamount = $draftline->grossamount - ($draftline->grossamount * ($draftline->discount/100)) + ($draftline->grossamount * ($draftline->addition/100));
$draftline->save();
session()->flash('flash_success', 'Update succeeded');
}
}
}
// Check if a line needs to be deleted
reset($requestcopy);
foreach ($requestcopy as $key => $value) {
if (substr($key, 0, 6) == "cmdDel") {
$lineid = substr($key, 6);
$draftline = Draftline::findOrFail($lineid);
$draftline->delete();
session()->flash('flash_success', 'Draft line was deleted');
}
}
// Check if a new line should be created
if ($request['qty'] != 0 && $request['article_id'] > 0 && strlen($request['descr']) > 0) {
$newline = new DraftLine;
$article = Article::findOrFail($request['article_id']);
$customer = $draftheader->customer;
$newline->article_id = $request['article_id'];
$newline->descr = $request['descr'];
$newline->qty = $request['qty'];
$newline->grossamount = $article->gross;
$newline->discount = $customer->discount;
$newline->taxrate = $article->taxrate;
if ($customer->taxrate == "No tax") {
$newline->taxrate = 0;
}
$newline->netamount = $newline->grossamount - ($newline->grossamount * ($newline->discount/100));
$newline = $draftheader->lines()->save($newline);
session()->flash('flash_success', 'New draft line was added');
}
return redirect('drafts/' . $id . '/edit');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id) {
//
}
}
User model
<?php namespace App;
use App\Hour;
use Illuminate\Notifications\Notifiable;
use Illuminate\Auth\Authenticatable;
use Sofa\Eloquence\Eloquence;
use App\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable, CanResetPassword;
use Notifiable;
use Eloquence;
public function draftheaders()
{
return $this->hasMany('App\DraftHeader');
}
protected $searchableColumns = ['name'];
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['name', 'email', 'password'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token'];
public function hours()
{
return $this->hasMany(Hour::class);
}
}
User controller
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
public function find(Request $request)
{
$term = trim($request->q);
if (empty($term)) {
return \Response::json([]);
}
$users = user::search($term)->limit(5)->get();
$formatted_users = [];
foreach ($users as $user) {
$formatted_users[] = ['id' => $user->id, 'text' => $user->name];
}
return \Response::json($formatted_users);
}
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth')->except('find');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('user');
}
}
The database has the following tables:
User table,
Draftsheader table
In the draftsheader table I changed the column user_id to index. And
in the users table I changed column name to index. Normally I would
index the column and give it a foreignkey. But I looked at the
customer table and the draftsheader table and there where no
foreignkeys. So I was thinking maybe foreignkeys arent nessecary, as
long as the fields are indexed.
I hope you guys can help me out, cause i'm stuck... If information is missing let me now and I'll edit the page.
Update
In the view I changed [¨name¨] to [¨employee_name¨] Like suggested by a fellow stackoverflow user. It resulted in this:
Changed name to employee_name
Try changing this:
#foreach ($result as $draft)
<tr>
<td><input type="checkbox" id="invoice_{{$draft['id']}}" name="invoice_{{$draft['id']}}"></td>
<td>{{ $draft['id'] }}</td>
<td>{{$draft['name'] }} ({{ $draft['user_id'] }})</td>
<td>{{$draft['name'] }} ({{ $draft['customer_id'] }})</td>
<td>{{ $draft['reference'] }}</td>
<td>{{ $draft['created_at'] }}</td>
<td></td>
<td style="text-align:right">{{ number_format($totals[$draft['id']],2) }}</td>
<td><input class="btn btn-danger" name="delete_{{$draft['id']}}" id="delete_{{$draft['id']}}" type="submit" value="X"></td>
</tr>
<?php $count++ ?>
#endforeach
To this:
#foreach ($result as $draft)
<tr>
<td><input type="checkbox" id="invoice_{{$draft['id']}}" name="invoice_{{$draft['id']}}"></td>
<td>{{ $draft['id'] }}</td>
<td>{{$draft['employee_name'] }} ({{ $draft['user_id'] }})</td>
<td>{{$draft['name'] }} ({{ $draft['customer_id'] }})</td>
<td>{{ $draft['reference'] }}</td>
<td>{{ $draft['created_at'] }}</td>
<td></td>
<td style="text-align:right">{{ number_format($totals[$draft['id']],2) }}</td>
<td><input class="btn btn-danger" name="delete_{{$draft['id']}}" id="delete_{{$draft['id']}}" type="submit" value="X"></td>
</tr>
<?php $count++ ?>
#endforeach
You use ['name'] two times, but you have the customer_name on it.
Related
I created a laravel 8 app in which i can store a new user, locally it works fine but when deployed on heroku at the moment i mike to create a new user this error message appears:
"Trying to access array offset on value of type null"
here is the user class:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Auth\Notifications\ResetPassword;
use Hash;
/**
* Class User
*
* #package App
* #property string $name
* #property string $email
* #property string $password
* #property string $role
* #property string $remember_token
* #property string $citizen
*/
class User extends Authenticatable
{
use Notifiable;
protected $fillable = ['name', 'email', 'password', 'remember_token', 'role_id', 'citizen_id'];
protected $hidden = ['password', 'remember_token'];
public static function boot()
{
parent::boot();
User::observe(new \App\Observers\UserActionsObserver);
}
/**
* Hash password
* #param $input
*/
public function setPasswordAttribute($input)
{
if ($input)
$this->attributes['password'] = app('hash')->needsRehash($input) ? Hash::make($input) : $input;
}
/**
* Set to null if empty
* #param $input
*/
public function setRoleIdAttribute($input)
{
$this->attributes['role_id'] = $input ? $input : null;
}
/**
* Set to null if empty
* #param $input
*/
public function setCitizenIdAttribute($input)
{
$this->attributes['citizen_id'] = $input ? $input : null;
}
public function role()
{
return $this->belongsTo(Role::class, 'role_id');
}
public function citizen()
{
return $this->belongsTo(Citizen::class, 'citizen_id')->withTrashed();
}
public function sendPasswordResetNotification($token)
{
$this->notify(new ResetPassword($token));
}
}
here is the controller class:
<?php
namespace App\Http\Controllers\Admin;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\StoreUsersRequest;
use App\Http\Requests\Admin\UpdateUsersRequest;
class UsersController extends Controller
{
/**
* Display a listing of User.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
if (! Gate::allows('user_access')) {
return abort(401);
}
$users = User::all();
return view('admin.users.index', compact('users'));
}
/**
* Show the form for creating new User.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
if (! Gate::allows('user_create')) {
return abort(401);
}
$roles = \App\Role::get()->pluck('title', 'id')->prepend(trans('quickadmin.qa_please_select'), '');
$citizens = \App\Citizen::get()->pluck('num_cin', 'id')->prepend(trans('quickadmin.qa_please_select'), '');
return view('admin.users.create', compact('roles', 'citizens'));
}
/**
* Store a newly created User in storage.
*
* #param \App\Http\Requests\StoreUsersRequest $request
* #return \Illuminate\Http\Response
*/
public function store(StoreUsersRequest $request)
{
if (! Gate::allows('user_create')) {
return abort(401);
}
$user = User::create($request->all());
return redirect()->route('admin.users.index');
}
/**
* Show the form for editing User.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
if (! Gate::allows('user_edit')) {
return abort(401);
}
$roles = \App\Role::get()->pluck('title', 'id')->prepend(trans('quickadmin.qa_please_select'), '');
$citizens = \App\Citizen::get()->pluck('num_cin', 'id')->prepend(trans('quickadmin.qa_please_select'), '');
$user = User::findOrFail($id);
return view('admin.users.edit', compact('user', 'roles', 'citizens'));
}
/**
* Update User in storage.
*
* #param \App\Http\Requests\UpdateUsersRequest $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(UpdateUsersRequest $request, $id)
{
if (! Gate::allows('user_edit')) {
return abort(401);
}
$user = User::findOrFail($id);
$user->update($request->all());
return redirect()->route('admin.users.index');
}
/**
* Display User.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
if (! Gate::allows('user_view')) {
return abort(401);
}
$roles = \App\Role::get()->pluck('title', 'id')->prepend(trans('quickadmin.qa_please_select'), '');
$citizens = \App\Citizen::get()->pluck('num_cin', 'id')->prepend(trans('quickadmin.qa_please_select'), '');$user_actions = \App\UserAction::where('user_id', $id)->get();
$user = User::findOrFail($id);
return view('admin.users.show', compact('user', 'user_actions'));
}
/**
* Remove User from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
if (! Gate::allows('user_delete')) {
return abort(401);
}
$user = User::findOrFail($id);
$user->delete();
return redirect()->route('admin.users.index');
}
/**
* Delete all selected User at once.
*
* #param Request $request
*/
public function massDestroy(Request $request)
{
if (! Gate::allows('user_delete')) {
return abort(401);
}
if ($request->input('ids')) {
$entries = User::whereIn('id', $request->input('ids'))->get();
foreach ($entries as $entry) {
$entry->delete();
}
}
}
}
finally here is the creation view:
#extends('layouts.app')
#section('content')
<h3 class="page-title">المستخدم</h3>
{!! Form::open(['method' => 'POST', 'route' => ['admin.users.store']]) !!}
<div class="panel panel-default">
<div class="panel-heading">
#lang('quickadmin.qa_create')
</div>
<div class="panel-body">
<div class="row">
<div class="col-xs-12 form-group">
{!! Form::label('name', trans('quickadmin.users.fields.name').'*', ['class' => 'control-label']) !!}
{!! Form::text('name', old('name'), ['class' => 'form-control', 'placeholder' => '', 'required' => '']) !!}
<p class="help-block"></p>
#if($errors->has('name'))
<p class="help-block">
{{ $errors->first('name') }}
</p>
#endif
</div>
</div>
<div class="row">
<div class="col-xs-12 form-group">
{!! Form::label('email', trans('quickadmin.users.fields.email').'*', ['class' => 'control-label']) !!}
{!! Form::email('email', old('email'), ['class' => 'form-control', 'placeholder' => '', 'required' => '']) !!}
<p class="help-block"></p>
#if($errors->has('email'))
<p class="help-block">
{{ $errors->first('email') }}
</p>
#endif
</div>
</div>
<div class="row">
<div class="col-xs-12 form-group">
{!! Form::label('password', trans('quickadmin.users.fields.password').'*', ['class' => 'control-label']) !!}
{!! Form::password('password', ['class' => 'form-control', 'placeholder' => '', 'required' => '']) !!}
<p class="help-block"></p>
#if($errors->has('password'))
<p class="help-block">
{{ $errors->first('password') }}
</p>
#endif
</div>
</div>
<div class="row">
<div class="col-xs-12 form-group">
{!! Form::label('role_id', trans('quickadmin.users.fields.role').'*', ['class' => 'control-label']) !!}
{!! Form::select('role_id', $roles, old('role_id'), ['class' => 'form-control select2', 'required' => '']) !!}
<p class="help-block"></p>
#if($errors->has('role_id'))
<p class="help-block">
{{ $errors->first('role_id') }}
</p>
#endif
</div>
</div>
<div class="row">
<div class="col-xs-12 form-group">
{!! Form::label('citizen_id', trans('quickadmin.users.fields.citizen').'', ['class' => 'control-label']) !!}
{!! Form::select('citizen_id', $citizens, old('citizen_id'), ['class' => 'form-control select2']) !!}
<p class="help-block"></p>
#if($errors->has('citizen_id'))
<p class="help-block">
{{ $errors->first('citizen_id') }}
</p>
#endif
</div>
</div>
</div>
</div>
{!! Form::submit(trans('quickadmin.qa_save'), ['class' => 'btn btn-danger']) !!}
{!! Form::close() !!}
#stop
How do I update an edit field in laravel?
I've tried the sync () method, detach with atach ()
unsuccessfully, I ask your help with this.
I really appreciate anyone who can help me with this
Remembering, I already managed to save the values with the create method, follow the codes:
My controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Pedido;
use App\Models\Cliente;
use App\Models\Produto;
class PedidosController extends Controller
{
/**
* mostrar conteudo no index
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$pedidos = Pedido::orderBy('id', 'asc')->paginate(2000);
return view('pedidos.index', compact('pedidos'));
}
/**
* Mostra o form para criar um novo pedido.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$clientes = Cliente::all();
$produtos = Produto::all();
return view('pedidos.create', compact('clientes', 'produtos'));
}
/**
* armazena um novo pedido pra enviar ao BD
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'status' => 'required',
'clientes_id' => 'required',
'produtos_id' => 'required'
]);
$pedido = Pedido::create($request->only([
'pedidos_id',
'produtos_id',
'clientes_id'
]));
$cliente = Cliente::find($request->clientes_id);
$pedido->clientes()->save($cliente);
$produto = Produto::find($request->produtos_id);
$pedido->produtos()->attach($produto);
return redirect()->route('pedidos.index')
->with('success', 'Pedido cadastrado com sucesso');
}
/**
* Exibe um pedido
*
* #param \App\Models\Pedido $pedido
* #return \Illuminate\Http\Response
*/
public function show(Pedido $pedido)
{
return view('pedidos.show', compact('pedido'));
}
/**
* Exibe um pedido para edição
*
* #param \App\Models\Pedido $pedido
* #return \Illuminate\Http\Response
*/
public function edit(Pedido $pedido)
{
$clientes = Cliente::all();
$produtos = Produto::all();
return view('pedidos.edit', compact('pedido', 'clientes', 'produtos'));
}
/**
* Atualiza um pedido no BD
*
* #param \Illuminate\Http\Request $request
* #param \App\Models\Pedido $pedido
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Pedido $pedido)
{
$request->validate([
'status' => 'required',
'clientes_id' => 'required',
'produtos_id' => 'required',
]);
$pedido->update($request->all());
return redirect()->route('pedidos.index')
->with('success', 'Pedido atualizado com sucesso');
}
/**
* Remove um pedido do BD
*
* #param \App\Models\Pedido $pedido
* #return \Illuminate\Http\Response
*/
public function destroy(Pedido $pedido)
{
$pedido->delete();
return redirect()->route('pedidos.index')
->with('success', 'Pedido deletado com sucesso');
}
}
my edit:
#extends('layouts.app')
#section('content')
<div class="container content">
<div class="row">
<div class="col-md">
<p class="text-center fs-1">Editar o pedido nº{{$pedido->id}}</b></p>
<div class="float-left">
<a class="btn btn-primary" href="{{ route('pedidos.index') }}" title="Voltar"> <i class="fas fa-backward "></i> </a>
</div>
</br>
#if ($errors->any())
<div class="alert alert-danger">
<strong>Ops!</strong> Há um problema com seu Pedido<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<div class="row h-100">
<div class="col">
<form action="{{ route('pedidos.update', $pedido->id) }}" method="POST">
#csrf
#method('PUT')
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<label for="selectBox"> Cliente selecionado: </label>
<select style=width:400px name="clientes_id" class="form-control" onfocus="this.selectedIndex = -1;">
#foreach ($pedido->clientes as $cliente)
<option selected value="{{ $cliente->id}}">{{ $cliente->nome}}</option>
#endforeach
#foreach($clientes as $cliente)
<option value="{{ $cliente->id}}">{{ $cliente->nome}}</option>
#endforeach
</select>
</br>
<div class="custom-select">
<label for="selectBox"> Status selecionado: </label>
<select style=width:400px name="status" class="form-control" onfocus="this.selectedIndex = -1;">
<option selected> {{ $pedido->status }}</option>
<option value=aberto>Em aberto</option>
<option value=pago>Pago</option>
<option value=cancelado>Cancelado</option>
</select>
</div>
</br>
<label for="selectBox"> Escolha um produto: </label>
<select style=width:400px class="form-control" name="produtos" id="selectBox" onfocus="this.selectedIndex = -1;" onchange="addProduct(options);">
#foreach ($produtos as $produto)
<option value="{{ $produto->id}}">{{ $produto->nome}}</option>
#endforeach
</select>
</br></br>
<table class="table">
<thead>
<tr>
<th>Código Produto</th>
<th>Produto selecionado</th>
<th>Remover</th>
</tr>
</thead>
<tbody id="tbody">
#foreach ($produtos as $key => $produto)
<tr>
<td>
<input type="hidden" name="produtos_id[{{$key}}]" value="{{ $produto->id}}">{{ $produto->id}}
</td>
<td>
{{ $produto->nome}}
</td>
<td>
<input type='button' value='Remover' onclick='removeProduct()' />
</td>
</tr>
#endforeach
</tbody>
</table>
</br>
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
<button type="submit" class="btn btn-primary">Enviar</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script>
var table = document.getElementById('tbody');
var count = linhas;
function addProduct(product) {
table.innerHTML += "<tr><td><input type='hidden' name='produtos_id[" + count + "]' value='" + product[product.selectedIndex].value + "'>" + product[product.selectedIndex].value + "</td><td>" + product[product.selectedIndex].innerText + "</td><td><input type='button' value='Remover' onclick='removeProduct()'/></tr></td>";
count++;
}
function removeProduct() {
var td = event.target.parentNode;
var tr = td.parentNode;
tr.parentNode.removeChild(tr);
count--;
}
</script>
#endsection
Pedido model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Pedido extends Model
{
protected $table = 'pedidos';
public $timestamps = true;
protected $fillable = [
'status',
'clientes_id',
'created_at'
];
public function clientes()
{
return $this->hasMany(Cliente::class, 'id', 'clientes_id');
}
public function produtos()
{
return $this->belongsToMany(Produto::class, 'pedidos_produtos', 'pedidos_id', 'produtos_id');
}
}
Produto Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Produto extends Model
{
use HasFactory;
protected $table = 'produtos';
public $timestamps = true;
protected $casts = [
'preco' => 'float'
];
protected $fillable = [
'nome',
'descricao',
'preco',
'quantidade',
'created_at'
];
public function pedidos()
{
return $this->belongsToMany(Pedido::class, 'pedidos_produtos', 'produto_id', 'pedidos_id');
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Produto extends Model
{
use HasFactory;
protected $table = 'produtos';
public $timestamps = true;
protected $casts = [
'preco' => 'float'
];
protected $fillable = [
'nome',
'descricao',
'preco',
'quantidade',
'created_at'
];
public function pedidos()
{
return $this->belongsToMany(Pedido::class, 'pedidos_produtos', 'produto_id', 'pedidos_id');
}
}
you need to try this code. it will work.
$produtoId = [];
foreach ($produto as $pdt) {
$produtoId[] = $pdt->id;
}
$pedido->produtos()->sync($produtoId);
$pedido->update($request->all());
So I'm trying to use the update() function to update the selected user but when I click submit, it just goes back to index (as it should) but updates nothing. Following is my code:
StudentController (Resource Controller):
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Student;
class StudentController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$students = Student::all();
return view ('main',compact('students'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view ('create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
Student::create($request->all());
return redirect()->route('main.index')->with('create','Student has been added successfully!');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id, Student $student)
{
$student = Student::findOrFail($id);
return view ('edit',compact('student'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Student $student)
{
$student->update($request->all());
return redirect()->route('main.index')->with('update','Student has been updated!');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
Main.blade.php (Index):
<div class="container">
<div class="row">
<div class="col-lg-12">
<div class="py-4">
#if (Session::has('create'))
<div class="alert alert-info">
{{ Session::get('create') }}
</div>
#endif
#if (Session::has('update'))
<div class="alert alert-info">
{{ Session::get('update') }}
</div>
#endif
<div class="card">
<div class="card-header">
Students
{{ link_to_route('main.create','Add Student','',['class'=>'btn btn-success float-right']) }}
</div>
<div class="card-body">
<table id="myTable" class="table table-striped table-bordered">
<thead>
<tr>
<th>Student Name</th>
<th>Gender</th>
<th>Address</th>
<th>Class</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach($students as $student)
<tr>
<td>{{ $student->name }}</td>
<td>{{ $student->gender }}</td>
<td>{{ $student->address }}</td>
<td>{{ $student->class }}</td>
<td>{{ link_to_route('main.edit','Edit',[$student->id],['class'=> 'btn btn-primary btn-sm']) }}</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
edit.blade.php (Model):
{!! Form::model($student,array('route'=>['main.update',$student->id],'method'=>'PUT')) !!}
<div class="form-group">
{!! Form::text('name',null,['class'=>'form-control','placeholder'=>'Add Student Name']) !!}
</div>
<div class="form-group">
{!! Form::select('gender', [
'Male' => 'Male',
'Female' => 'Female'],
null, ['class'=>'custom-select','placeholder' => 'Choose Gender']); !!}
</div>
<div class="form-group">
{!! Form::text('address',null,['class'=>'form-control','placeholder'=>'Add Student Address']) !!}
</div>
<div class="form-group">
{!! Form::select('class', [
'A' => 'A',
'B' => 'B',
'C' => 'C',
'D' => 'D',],
null, ['class'=>'custom-select','placeholder' => 'Choose Class']); !!}
</div>
<div class="form-group py-4">
{!! Form::submit('Edit',['type'=>'submit','class'=>'btn btn-danger btn-block']) !!}
</div>
{!! Form::close() !!}
Student.php (Model):
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
protected $fillable = ['name','gender','address','class'];
}
My create.blade.php is exactly the same as my edit.blade.php, the only changes are in the Form::open() line. And the edit page even displays my old data on the input fields but when I make a change & click Update, it just doesn't update anything in the database or the index page - so what am I doing wrong? Thanks in advance and please feel free to ask if any more code is required for you guys to crack this one.
Try this one out:
public function update(Request $request, Student $student)
{
$input = $request->all();
$student->fill($input)->save();
return redirect()->route('main.index')->with('update','Student has been updated!');
}
Try..
public function update(Request $request,$id)
{
$student = Student::find($id);
$student->name = $request->input('name');
$student->gender = $request->input('gender');
$student->address = $request->input('address');
$student->class = $request->input('class');
$student->save();
return redirect()->route('main.index')->with('update','Student has been updated!');
}
request()->all() contains method and token information. Can you maybe pass it through a validator?
$validated = request()->validate([
'name' => 'required',
'address' => '',
..
]);
$student->update($validated);
In your edit.blade.php,
{!! Form::submit('route_to_update()',['type'=>'submit','class'=>'btn btn-danger btn-block']) !!}
change "Edit"
And you can check your route by in your console like "php artisan route:list"
and check your route is reached
by var_damp() or var_export() or dd()in your student controller update function
I am trying to save uploaded image to uploads folder as well as database at the time of user registration, the image name is successfully saved to the database along with user details like name, address, email and etc. I am new to laravel. Please can any one suggest me, thank you.
Please find below is my register.blade.php
#extends('layouts.site')
#section('content')
<div class="login-content">
<a class="hiddenanchor" id="signup">
</a>
<a class="hiddenanchor" id="signin">
</a>
#include('layouts.site-navigation')
#include('errors.errors')
<div class="login_wrapper">
<div class="animate form login_form">
<section class="login_content">
<!-- <form> -->
<h1>Registration Form
</h1>
{!! Form::open(array('url' => URL_USERS_REGISTER, 'method' => 'POST',
'name'=>'formLanguage ', 'novalidate'=>'', 'class'=>"loginform",
'name'=>"registrationForm", 'files'=>'true')) !!}
<div>
</div>
<div>
{{ Form::text('username', $value = null , $attributes =
array('class'=>'form-control',
'placeholder' => getPhrase("username"),
'ng-model'=>'username',
'required'=> 'true',
'ng-class'=>'{"has-error": registrationForm.username.$touched &&
registrationForm.username.$invalid}',
'ng-minlength' => '4',
)) }}
</div>
<div>
{{ Form::text('rollnumber', $value = null , $attributes =
array('class'=>'form-control',
'placeholder' => getPhrase("roll number"),
'ng-minlength' => '2',
)) }}
<div>
{{ Form::text('branch', $value = null , $attributes =
array('class'=>'form-control',
'placeholder' => getPhrase("branch"),
'ng-minlength' => '2',
)) }}
</div>
<div>
{{ Form::text('phone', $value = null , $attributes =
array('class'=>'form-control',
'placeholder' => getPhrase("phone"),
'ng-model'=>'phone',
'ng-pattern' => getRegexPattern('phone'),
'required'=> 'true',
'ng-class'=>'{"has-error": registrationForm.phone.$touched &&
registrationForm.phone.$invalid}',
'ng-minlength' => '10',
)) }}
</div>
<div>
<select id="make" name="place" class="form-control">
<option value="" disabled selected>Interested Work Place
</option>
<option value="Yemmiganur">Yemmiganur
</option>
<option value="Raichur">Raichur
</option>
</select>
</div>
<br>
<div>
Interested To Work In Night Shift:
<input type="radio" name="night_shift" value="Yes" > Yes
<input type="radio" name="night_shift" value="No"> No
</div>
<div class="clearfix">
</div>
<div class="separator">
<p class="change_link">New to site?
<a href="#signup" class="to_register"> Next
</a>
</p>
<div class="clearfix">
</div>
</div>
<br>
<a href="{{URL_USERS_LOGIN}}">
<p class="text-center">{{getPhrase('i_am_having_account')}}
</p>
</a>
</div>
</section>
<div id="register" class="animate form registration_form">
<section class="login_content">
{!! Form::open(array('url' => URL_USERS_REGISTER, 'method' => 'POST',
'name'=>'formLanguage ', 'novalidate'=>'', 'class'=>"loginform",
'name'=>"registrationForm")) !!}
<!-- <form> -->
<h1>Registration Form
</h1>
<div>
{{ Form::email('email', $value = null , $attributes =
array('class'=>'form-control formclass',
'placeholder' => getPhrase("email"),
'ng-model'=>'email',
'required'=> 'true',
'ng-class'=>'{"has-error": registrationForm.email.$touched &&
registrationForm.email.$invalid}',
)) }}
</div>
<div>
{{ Form::password('password', $attributes = array('class'=>'form-
control formclass instruction-call',
'placeholder' => getPhrase("password"),
'ng-model'=>'registration.password',
'required'=> 'true',
'ng-class'=>'{"has-error": registrationForm.password.$touched &&
registrationForm.password.$invalid}',
'ng-minlength' => 5
)) }}
</div>
<div>
{{ Form::password('password_confirmation', $attributes =
array('class'=>'form-control formclass instruction-call',
'placeholder' => getPhrase("password_confirmation"),
'ng-model'=>'registration.password_confirmation',
'required'=> 'true',
'ng-class'=>'{"has-error":
registrationForm.password_confirmation.$touched &&
registrationForm.password_confirmation.$invalid}',
'ng-minlength' => 5,
'compare-to' =>"registration.password"
)) }}
{{ Form::text('aadhar_number', $value = null , $attributes =
array('class'=>'form-control',
'placeholder' => "UID (Aadhaar)",
'required'=> 'true',
'ng-class'=>'{"has-error": registrationForm.aadhar_number.$touched
&& registrationForm.aadhar_number.$invalid}',
'ng-minlength' => '12',
)) }}
<br>
</div>
<fieldset class="form-group" >
<input type="file" class="form-control" name="image"
accept=".png,.jpg,.jpeg" id="image_input">
</fieldset>
<?php $parent_module = getSetting('parent', 'module'); ?>
#if(!$parent_module)
<input type="hidden" name="is_student" value="0">
#else
<div class="row">
<div class="col-md-6">
{{ Form::radio('is_student', 0, true, array('id'=>'free')) }}
<label for="free">
<span class="fa-stack radio-button">
<i class="mdi mdi-check active">
</i>
</span> {{getPhrase('i_am_an_admin')}}
</label>
</div>
<div class="col-md-6">
{{ Form::radio('is_student', 0, true, array('id'=>'free')) }}
<label for="free">
<span class="fa-stack radio-button">
<i class="mdi mdi-check active">
</i>
</span> {{getPhrase('i_am_a_student')}}
</label>
</div>
</div>
#endif
<div class="text-center buttons">
<button type="submit" class="btn btn-default submit"
ng-disabled='!registrationForm.$valid'>
{{getPhrase('register_now')}}
</button>
</div>
{!! Form::close() !!}
<div class="clearfix">
</div>
<div class="separator">
<p class="change_link">Already a member ?
<a href="#signin" class="to_register"> Previous
</a>
</p>
<div class="clearfix">
</div>
</div>
</section>
</div>
</div>
#stop
#section('footer_scripts')
#include('common.validations')
#stop
AuthController.php
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use \Auth;
use Socialite;
use Exception;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/';
protected $dbuser = '';
protected $provider = '';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'username' => 'required|max:255|unique:users',
// 'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'aadhar_number' => 'required|max:12|unique:users',
'password' => 'required|min:6|confirmed',
'image' => 'bail',
'place' => 'required',
'night_shift' => 'required',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data )
{
$type = 'student';
if($data['is_student'])
$type = 'parent';
$role = getRoleData($type);
$user = new User();
$user->username = $data['username'];
$user->rollnumber = $data['rollnumber'];
$user->branch = $data['branch'];
$user->email = $data['email'];
$user->password = bcrypt($data['password']);
$user->role_id = $role;
$user->image = $data['image'];
$user->place = $data['place'];
$user->night_shift = $data['night_shift'];
$user->phone = $data['phone'];
$user->aadhar_number = $data['aadhar_number'];
$user->slug = $user->makeSlug($user->username);
$user->save();
$user->roles()->attach($user->role_id);
try{
$this->sendPushNotification($user);
sendEmail('registration', array('user_name'=>$user->name,
'username'=>$data['username'], 'to_email' => $user->email,
'password'=>$data['password'], 'aadhar_number' => $user->aadhar_number));
}
catch(Exception $ex)
{
}
flash('success','record_added_successfully', 'success');
$options = array(
'name' => $user->name,
'image' => getProfilePath($user->image),
'slug' => $user->slug,
'role' => getRoleData($user->role_id),
);
pushNotification(['owner','admin'], 'newUser', $options);
return $user;
}
public function sendPushNotification($user)
{
if(getSetting('push_notifications', 'module')) {
if(getSetting('default', 'push_notifications')=='pusher') {
$options = array(
'name' => $user->name,
'image' => getProfilePath($user->image),
'slug' => $user->slug,
'role' => getRoleData($user->role_id),
);
pushNotification(['owner','admin'], 'newUser', $options);
}
else {
$this->sendOneSignalMessage('New Registration');
}
}
}
/**
* This is method is override from Authenticate Users class
* This validates the user with username or email with the sent password
* #param Request $request [description]
* #return [type] [description]
*/
protected function processUpload(Request $request, User $user)
{
if(env('DEMO_MODE')) {
return 'demo';
}
if ($request->hasFile('image')) {
$imageObject = new ImageSettings();
$destinationPath = $imageObject->getProfilePicsPath();
$destinationPathThumb = $imageObject->getProfilePicsThumbnailpath();
$fileName = $user->id.'.'.$request->image->guessClientExtension();
;
$request->file('image')->move($destinationPath, $fileName);
$user->image = $fileName;
Image::make($destinationPath.$fileName)->fit($imageObject-
>getProfilePicSize())->save($destinationPath.$fileName);
Image::make($destinationPath.$fileName)->fit($imageObject-
>getThumbnailSize())->save($destinationPathThumb.$fileName);
$user->save();
}
}
public function postLogin(Request $request)
{
$login_status = FALSE;
if (Auth::attempt(['aadhar_number' => $request->email, 'password' =>
$request->password])) {
// return redirect(PREFIX);
$login_status = TRUE;
}
elseif (Auth::attempt(['email'=> $request->email, 'password' =>
$request->password])) {
$login_status = TRUE;
}
if(!$login_status)
{
return redirect()->back()
->withInput($request->only($this->loginUsername(), 'remember'))
->withErrors([
$this->loginUsername() => $this->getFailedLoginMessage(),
]);
}
/**
* Check if the logged in user is parent or student
* if parent check if admin enabled the parent module
* if not enabled show the message to user and logout the user
*/
if($login_status) {
if(checkRole(getUserGrade(7))) {
if(!getSetting('parent', 'module')) {
return redirect(URL_PARENT_LOGOUT);
}
}
}
/**
* The logged in user is student/admin/owner
*/
if($login_status)
{
return redirect(PREFIX);
}
}
/**
* Redirect the user to the GitHub authentication page.
*
* #return Response
*/
public function redirectToProvider($logintype)
{
if(!getSetting($logintype.'_login', 'module'))
{
flash('Ooops..!', $logintype.'_login_is_disabled','error');
return redirect(PREFIX);
}
$this->provider = $logintype;
return Socialite::driver($this->provider)->redirect();
}
/**
* Obtain the user information from GitHub.
*
* #return Response
*/
public function handleProviderCallback($logintype)
{
try{
$user = Socialite::driver($logintype);
if(!$user)
{
return redirect(PREFIX);
}
$user = $user->user();
if($user)
{
if($this->checkIsUserAvailable($user)) {
Auth::login($this->dbuser, true);
flash('Success...!', 'log_in_success', 'success');
return redirect(PREFIX);
}
flash('Ooops...!', 'faiiled_to_login', 'error');
return redirect(PREFIX);
}
}
catch (Exception $ex)
{
return redirect(PREFIX);
}
}
public function checkIsUserAvailable($user)
{
$id = $user->getId();
$nickname = $user->getNickname();
$name = $user->getName();
$email = $user->getEmail();
$avatar = $user->getAvatar();
$this->dbuser = User::where('email', '=',$email)->first();
if($this->dbuser) {
//User already available return true
return TRUE;
}
$newUser = array(
'name' => $name,
'email'=>$email,
);
$newUser = (object)$newUser;
$userObj = new User();
$this->dbuser = $userObj->registerWithSocialLogin($newUser);
$this->dbuser = User::where('slug','=',$this->dbuser->slug)->first();
// $this->sendPushNotification($this->dbuser);
return TRUE;
}
public function socialLoginCancelled(Request $request)
{
return redirect(PREFIX);
}
}
First, you should urgently consider updating Laravel to newer versions.
Second, I think you are missing enctype="multipart/form-data" accept-charset="UTF-8" in your form tag
I'm setting up a blog and want the homepage to show the latest blog entries including links to the single entries.
I got a link to all entries showing in a list but I can't exactly figure out how to show a single entry. Plus now I always get an "object not found" exception as soon as I try to click on the link.
Here's the controller which contents the Function to show a single entry:
<?php
// src/BlogBundle/Controller/BlogController.php
namespace BlogBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use BlogBundle\Entity\Blog;
use BlogBundle\Entity\User;
use BlogBundle\Form\BlogType;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
class BlogController extends Controller
{
/**
* #Route("/blog", name="bloglist", requirements={"page": "\d+"})
*/
public function listAction()
{
$entry = $this->getDoctrine()->getRepository('BlogBundle:Blog')->findBy(array(), array('date' => 'DESC'));
dump($entry);
return $this->render('BlogBundle:blog:blog.html.twig', [
'bloglist' => $entry
]);
}
/**
* #Route("/blog/new", name="create")
*/
public function createAction(Request $request) {
$entry = new Blog();
$entry->setDate(new \DateTime('now'));
$entry->setAuthor($this->getUser());
$form = $this->createForm(BlogType::class, $entry);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entry = $form->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($entry);
$em->flush();
return $this->render('BlogBundle:blog:createsubmit.html.twig', array(
'entry' => $entry,
'form' => $form->createView(),
'success' => true
));
}
return $this->render('BlogBundle:blog:new.html.twig', array(
'quote' => 'New blog entry created!',
'form' => $form->createView(),
));
}
/**
* #Route("/blog/singleentry/{id}", name="singleentry", requirements={"id" = "\d+"}, defaults={"id" = 0})
*/
public function listSingleEntryAction(Request $request, Blog $blog)
{
$em = $this->getDoctrine()->getRepository('BlogBundle:Blog')->find($blog);
$form = $this->createForm(BlogType::class, $entry);
$form->handleRequest($request);
$em->persist($entry);
$em->flush();
return $this->render('BlogBundle:singleentry:edit.html.twig', array(
'entry' =>$entry,
'form' => $form->createView()
));
}
/**
* #Route("/blog/edit/{id}", name="entryedit", requirements={"id" = "\d+"}, defaults={"id" = 0})
*
*/
public function editAction(Request $request, Blog $blog) {
$em = $this->getDoctrine()->getManager();
$entry = $em->getRepository('BlogBundle:Blog')->find($blog);
if ($this->get('security.authorization_checker')->isGranted('ROLE_ADMIN') || $entry->getAuthor() == $this->getUser()->getUsername() ) {
$form = $this->createForm(BlogType::class, $entry);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em->persist($entry);
$em->flush();
return $this->render('BlogBundle:blog:editsubmit.html.twig', array(
'entry' => $entry,
'form' => $form->createView(),
'success' => true
));
}
return $this->render('BlogBundle:blog:edit.html.twig', array(
'form' => $form->createView(),
));
}
else {
echo '<div class="alert alert-danger alert-dismissable">
<span aria-hidden="true" data-dismiss="alert" class="close">×</span>
<h4>
<i class="fa fa-exclamation-circle "></i>
Only the author of an entry is allowed to edit it!</h4></div>';
return $this->listAction();
}
}
/**
* #Route("/blog/delete/{id}", name="entrydelete", requirements={"id" = "\d+"}, defaults={"id" = 0})
*
*/
public function deleteAction(Request $request, Blog $blog) {
$em = $this->getDoctrine()->getManager();
$entry = $em->getRepository('BlogBundle:Blog')->find($blog);
if ($this->get('security.authorization_checker')->isGranted('ROLE_ADMIN') || $entry->getAuthor() == $this->getUser()->getUsername() ) {
$em->remove($entry);
$em->flush();
return $this->render('BlogBundle:blog:deletesubmit.html.twig');
}
else {
return $this->render('BlogBundle:blog:error.html.twig');
}
}
public function configureOptions(OptionsResolver $resolver) {
$resolver->setDefaults([
'data_class' => 'BlogBundle\Entity\Blog'
]);
}
}
?>
for my homepage:
<?php
namespace BlogBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class DefaultController extends Controller {
/**
* #Route("/", name="welcome")
*/
public function indexAction() {
$entry = $this->getDoctrine()->getRepository('BlogBundle:Blog')->findBy(array(), array('date' => 'DESC'),5);
dump($entry);
return $this->render('BlogBundle:Default:index.html.twig', [
'Welcome' => 'Welcome!',
'avatar_url' => 'http://www.lufthansa.com/mediapool/jpg/45/media_789050645.jpg',
'blog' => $this->redirectToRoute('singleentry'),
'bloglist' => $entry
]);
}
}
?>
And those are the twig templates I try to render
singleentry.html.twig:
{% extends '::base.html.twig' %}
{% block body %}
<div class="container">
<div class="col-md-11">
<h1 class="page-header">{{ blog. title }}</h1>
<div class="table">
<p><span class="fa fa-clock-o"></span> Posted on {{ blog.date|date('d.M Y H:i A') }} </p>
<p><span class="fa fa-user-circle"></span> Posted by {{ blog.author }} </p>
<p>{{ blog.text }}</p>
<!-- <a class="btn btn-primary" href="#">Read More <span class="glyphicon glyphicon-chevron-right"></span></a> -->
<button type="button" class="btn btn btn-info">
Edit entry
</button>
<button type="button" class="btn btn btn-warning">
Delete entry
</button>
<hr>
</div>
</div>
</div>
{% endblock %}
for the list of blog entries on my homepage:
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title text-center">My latest blog entries</h3>
</div>
<table class="table">
{% for blog in bloglist %}
<tr>
<td>{{ blog.title }}</td>
<td width="85%" style="max-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;">
{{ blog.text }}
</td>
</tr>
{% endfor %}
</table>
</div>
edited version of listSingleEntryAction --> object shown as NULL
public function listSingleEntryAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entry = $em->getRepository('BlogBundle:Blog')->find($id);
if($entry == null)
{
$message='Entry does not exist';
return $this->render('BlogBundle:blog:error.html.twig');
}
return $this->render('BlogBundle:blog:singleentry.html.twig', Array(
'entry' => $entry,
'success' => true,
));
}
The problem is your arguments.
public function listSingleEntryAction(Request $request, Blog $blog)
{
First of all, it shouldn't be with a Blog type. It's int.
Second, rename it to $id.
And I think you have the same problem with edit and delete actions.
check out your action. First 2 lines are the reason of your problem.
/**
* #Route("/blog/singleentry/{id}", name="singleentry", requirements={"id" = "\d+"}, defaults={"id" = 0})
*/
public function listSingleEntryAction(Request $request, Blog $blog)
{
$em = $this->getDoctrine()->getManager();
$entry = $em->getRepository('BlogBundle:Blog')->find($blog);