How to update data from a form in Laravel 5.2 - php

Hi I am having problems on editing and updating data from my form. I already tried to get the data from the form but when I try to edit and update it, it will make another data. Thanks!
Controller:
public function registerPackage()
{
$activity_packages = Chap_activity_packages::all();
return view('admin.registerPackage',compact('activity_packages'));
}
public function savePackage(Request $request)
{
$this->validate($request,[
'chap_activity_packages_name'=>'required|Min:4|unique:chap_activity_packa ges',
'chap_activity_packages_price'=>'required|numeric'
]);
$values = $request->all();
Chap_activity_packages::create($values);
return view('admin.registerPackage');
}
public function editPackage($id)
{
$act = Chap_activity_packages::find($id);
$activity_packages=Chap_activity_packages::all();
return view('admin.registerPackage',compact('act','activity_packages'));
}
<h4 class="page-header">Packages Management</h4>
<div class="row">
<div class="col-xs-5">
<div class="panel panel-success">
<div class="panel-heading">
<h3 class="panel-title">Register New Package</h3>
#if($errors->any())
<div class="alert alert-danger">
#foreach($errors->all() as $error)
<div>{{ $error }}</div>
#endforeach
</div>
#endif
#if(Session::has('flash_message'))
<div class="alert alert-success">
{{ Session::get('flash_message') }}
</div>
#endif
</div>
<div class="panel-body">
{{ Form::open(array('url' => 'admin/registerPackage')) }}
<div class="form-group">
{{ Form::label('chap_name','Package Name:') }}
{{ Form::text('chap_activity_packages_name',isset($act)? $act->chap_activity_packages_name:null,['class' => 'form-control', 'placeholder' => 'Enter package name']) }}
</div>
<div class="form-group">
{{ Form::label('chap_price','Package Price:') }}
{{ Form::text('chap_activity_packages_price',isset($act)? $act->chap_activity_packages_price:null,['class' => 'form-control', 'placeholder' => 'Enter package price']) }}
</div>
<div class="form-group">
{{ Form::submit('Register Package',['class' => 'btn btn-success btn-block']) }}
</div>
{{ Form::close() }}
</div>
</div>
</div>
</div>
#stop
#section('content2')
<div class="panel panel-success">
<div class="panel-heading">
<h4 class="panel-title">Available Packages</h4>
</div>
<div class="panel-body">
<table class="table table-striped table-hover">
<thead>
<tr>
<th>Package Name</th>
<th>Package Price</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach($activity_packages as $activity_package)
<tr>
<td> {{ $activity_package->chap_activity_packages_name }} </td>
<td> {{ $activity_package->chap_activity_packages_price }} </td>
<td>
</span>
<span class="glyphicon glyphicon-trash"></span>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
#stop
These are my codes for both the controller and the view. please let me know if what is wrong. thanks a lot!

I don't see the method for updating data in you controller, it should be look like below:
// YourController.php, use implicit route model binding
public function update(App\Chap_activity_packages $model)
{
// do your validation here
// $this->validate(blahblahblah...)
// ...
$model->update(request()->all());
return redirect()->back()->with('msg', 'Update success.');
}
// routes.php
Route::put('your/route/to/model/{model}', 'YourController#update');
// yourTemplate.blade.php
// remember to use method spoofing
{{ Form::open(['url' => 'your/route/to/model/' . $model->id, 'method' => 'put']) }}
Information about route model binding can be found here. Good luck!

Related

Laravel 9 "Missing required parameter for [Route:"

I'm using Laravel 9 and trying to use CRUD with my model Project which has the following DB table.
When I try to edit a project using the button "edit" on this view:
"projets.index":
#extends('header')
#section('content')
<div class="col-sm-8" style="background: rgba(204, 204, 204,0.5);padding:5%;width:100%">
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2 style="text-align: center">Les projets</h2>
</div>
<div class="pull-right">
<a class="btn btn-success" href="{{ route('projets.create') }}"> Créée un nouveau projet</a>
</div>
</div>
</div>
#if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
#endif
<table class="table table-bordered">
<tr>
<th>id du projet</th>
<th>description</th>
<th width="280px">Action</th>
</tr>
#foreach ($projects as $project)
<tr>
<td>{{ $project->id_project }}</td>
<td>{{ $project->description }}</td>
<td>
<form action="{{ route('projets.destroy',$project->id_project) }}" method="Post">
<a class="btn btn-primary" href="{{ route('galleries.index',$project->id_project,'id_project') }}">ajouter</a>
<a class="btn btn-primary" href="{{ route('projets.edit',[$project->id_project]) }}">Edit</a>
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger">Delete</button>
</form>
</td>
</tr>
#endforeach
</table>
{!! $projects->links() !!}
</div>
#endsection
I have the following error:
"Missing required parameter for [Route: projets.update] [URI: projets/{projet}] [Missing parameter: projet]."
"projets.edit":
#extends('header')
#section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Edit projet</h2>
</div>
<div class="pull-right">
<a class="btn btn-primary" href="{{ route('projets.index') }}"> Back</a>
</div>
</div>
</div>
#if ($errors->any())
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="{{ route('projets.update',$project->id_project) }}" method="POST" enctype="multipart/form-data">
#csrf
#method('PUT')
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Company Address:</strong>
<input type="text" name="address" value="{{ $project->description }}" class="form-control" placeholder="Company Address">
#error('address')
<div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
#enderror
</div>
</div>
<button type="submit" class="btn btn-primary ml-3">Submit</button>
</div>
</form>
#endsection
Update function inside the controller (ProjectController):
public function update(Request $request, $id_project)
{
$request->validate([
'description' => 'required',
]);
User::create($request->all());
$project->description = $request->description;
$project->save();
return redirect()->route('projets.index')
->with('success','project Has Been updated successfully');
}
public function edit(Project $project)
{
return view('projets.edit',compact('project'));
}
Project model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
protected $fillable = [
'id_project', 'description'
];
}
Sorry if my questions seems strange English is not my first language

Laravel 8 Call to undefined method Illuminate\Database\MySqlConnection::tabel()

its laravel 8 course im getting this error while using query builder but with ORM its perfectly run well. when i comment this code and use another method for getting data with query builder in AllCat() method DB::table is running perfectly
Category Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Category;
use Auth;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
class CategoryController extends Controller
{
public function AllCat(){
$categories = DB::tabel('categories')
->join('users','categories.user_id','users.id')
->select('categories.*','users.name')
->latest()->paginate(5);
// $categories = Category::latest()->paginate(5);
//$categories = DB::table('categories')->latest()->paginate(5);
return view('admin.category.index',compact('categories'));
}
public function AddCat(Request $request){
$validated = $request->validate([
'category_name' => 'required|unique:categories|max:255',
],
[
'category_name.required' => 'Please Input Category Name',
'category_name.max' => 'Category Less Then 255Chars',
]);
Category::insert([
'category_name' => $request->category_name,
'user_id' => Auth::user()->id,
'created_at' => Carbon::now()
]);
// $category = new Category;
// $category->category_name = $request->category_name;
// $category->user_id = Auth::user()->id;
// $category->save();
// $data = array();
// $data['category_name'] = $request->category_name;
// $data['user_id'] = Auth::user()->id;
// DB::table('categories')->insert($data);
return redirect()->back()->with('success','Category Inserted Successfull');
}
}
Index.blade.php
<x-app-layout>
<x-slot name="header">
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
All Category<b> </b>
</b>
</h2>
</x-slot>
<div class="py-12">
<div class="container">
<div class="row">
<div class="col-md-8">
<div class="card">
#if(session('success'))
<div class="alert alert-success alert-dismissible fade show" role="alert">
<strong>{{ session('success') }}</strong>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
#endif
<div class="card-header"> All Category
</div>
<table class="table">
<thead>
<tr>
<th scope="col">SL No</th>
<th scope="col">Category Name</th>
<th scope="col">User</th>
<th scope="col">Created At</th>
</tr>
</thead>
<tbody>
<!-- #php($i = 1) -->
#foreach($categories as $category)
<tr>
<th scope="row">{{ $categories->firstItem()+$loop->index }}</th>
<td>{{ $category->category_name }}</td>
<td>{{ $category->name }}</td>
<td>
#if($category->created_at == NULL)
<span class="text-danger">No Date Set</span>
#else
{{ Carbon\Carbon::parse($category->created_at)->diffforHumans() }}</td>
#endif
</tr>
#endforeach
</tbody>
</table>
{{ $categories->links() }}
</div>
</div>
<div class="col-md-4">
<div class="card">
<div class="card-header">Add Category</div>
<div class="card-body">
<form action="{{ route('store.category') }}" method="POST">
#csrf
<div class="mb-3">
<label for="exampleInputEmail1" class="form-label">Category Name</label>
<input type="text" name="category_name" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp">
#error('category_name')
<span class="text-danger">{{ $message }}</span>
#enderror
</div>
<button type="submit" class="btn btn-primary">Add Category</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
Can you tell me what is wrong here
are you sure it is DB::tabel and not DB::table ?? It surely has to be DB::table

Invalid argument supplied for foreach() - laravel 5.6

newbie here practicing laravel, im making an inventory for movies using laravel 5.6.. where I can do basic CRUD functionalities.
In here, Im sorting movies by genre. however I came up with this error Invalid argument supplied for foreach();
here is my Route: web.php
Route::resource('movies', 'MoviesController');
Route::get('movies/year/{movie}', 'MoviesController#released');
Route::get('movies/genre/{genre}', 'MoviesController#getgenre');
here is my controller: MoviesController.php
public function getgenre($genre){
$movies = Movie::where('genre', $genre)->whereIn('status', [1])->orderBy('title', 'asc')->get();
return view('genre', compact('movies'));
}
here is my view: genre.blade.php
#extends('layouts.app')
#section('content')
<div class="row">
<div class="col-md-10">
#if($movies->count() < 1)
<h1 style="text-align: center">No Movie Found</h1>
#else
#foreach($movies as $movie)
<div class="card" style="margin-bottom: 10px;">
<div class="card-body">
<div class="card-title">
{{ ucwords($movie->title) }}
</div>
<div class="card-text">
{{ ucfirst($movie->genre) }} | {{$movie->released}} |
#if($movie->seen == 1)
Seen: Yes
#else
Seen: No
#endif
<div style="margin-top: 5px">
{{ Form::open(['route' => ['movies.edit', $movie->id], 'class' => 'formupdate', 'method' => 'GET']) }}
{{ Form::submit('Update', ['class' => 'btn btn-primary col-md-2']) }}
{{ Form::close() }}
</div>
<div style="margin-top: 5px">
{{ Form::open(['route' => ['movies.destroy', $movie->id], 'class' => 'formdelete', 'method' => 'DELETE']) }}
{{ Form::hidden('hidden', 'hidden') }}
{{ Form::submit('Delete', ['class' => 'btn btn-danger col-md-2']) }}
{{ Form::close() }}
</div>
</div>
</div>
</div>
#endforeach
<div class="pagination" style="margin-top: 10px; text-align: center;">
{{ $movie->links() }}
</div>
#endif
</div>
<div class="col-md-2">
</div>
</div>
#stop
I tested it dd(): and it has results:
tried testing it using dd()
here is the error:
here is the error
thanks,
you have two issues:
1- Update this whereIn expects array and you use pagination in view and you do not return the data as pagination
$movies = Movie::where('genre', $genre)->whereIn('status', [1])>orderBy('title', 'asc')->paginate(10);
2- in the view you written $movie->links(); update it to
$movies->links();
Update this line, whereIn expects array
$movies = Movie::where('genre', $genre)->whereIn('status', [1])->orderBy('title', 'asc')->get();

laravel error: Trying to get property of non-object (\show.blade.php)

I'm making a discussion forum app with laravel and i face this error:
Trying to get property of non-object (View:
C:\xampp\htdocs\fourm\resources\views\discussion\show.blade.php) at
PhpEngine->evaluatePath('C:\xampp\htdocs\fourm\storage\framework\views/a2f2c494b8859e0552bfa22c40ceb4065b2efbe5.php',
array('__env' => object(Factory), 'app' => object(Application),
'channels' => object(Collection), 'errors' => object(ViewErrorBag),
'd' => null, 'best_answer' => null))in CompilerEngine.php (line 59)
This is my controller code:
public function show($slug)
{
$discussion = Discussion::where('slug', $slug)->first();
$best_answer = Reply::where('best_answer', 1)->first();
return view('discussion.show')->with('d', $discussion)->with('best_answer', $best_answer);
}
This is my view code:
#extends('layouts.app')
#section('content')
<div class="panel panel-default">
<div class="panel-heading">
<img src="{{ $d->user->avatar }}" alt="" width="40px" height="40px">
<span>{{ $d->user->name }}, <b>( {{ $d->user->points }} )</b></span>
#if($d->is_being_watch_by_user())
unwatch
#else
watch
#endif
</div>
<div class="panel-body">
<h4 class="text-center">
<b>{{ $d->title }}</b>
</h4>
<hr>
<p class="text-center">
{{ $d->content }}
</p>
<hr>
#if($best_answer)
<div class="text-center" style="padding: 40px;">
<h3 class="text-center">BEST ANSWER</h3>
<div class="panel panel-success">
<div class="panel-heading">
<img src="{{ $best_answer->user->avatar }}" alt="" width="40px" height="40px">
<span>{{ $best_answer->user->name }} <b>( {{ $best_answer->user->points }} )</b></span>
</div>
<div class="panel-body">
{{ $best_answer->content }}
</div>
</div>
</div>
#endif
</div>
<div class="panel-footer">
<span>
{{ $d->replies->count() }} Replies
</span>
{{ $d->channel->title }}
</div>
</div>
#foreach($d->replies as $r)
<div class="panel panel-default">
<div class="panel-heading">
<img src="{{ $r->user->avatar }}" alt="" width="40px" height="40px">
<span>{{ $r->user->name }} <b>( {{ $r->user->points }} )</b></span>
#if(!$best_answer)
#if(Auth::id() == $d->user->id)
Mark as best answer
#endif
#endif
</div>
<div class="panel-body">
<p class="text-center">
{{ $r->content }}
</p>
</div>
<div class="panel-footer">
#if($r->is_liked_by_user())
Unlike <span class="badge">{{ $r->likes->count() }}</span>
#else
Like <span class="badge">{{ $r->likes->count() }}</span>
#endif
</div>
</div>
#endforeach
<div class="panel panel-default">
<div class="panel-body">
#if(Auth::check())
<form action="{{ route('discussion.reply', ['id' => $d->id ]) }}" method="post">
{{ csrf_field() }}
<div class="form-group">
<label for="reply">Leave a reply...</label>
<textarea name="reply" id="reply" cols="30" rows="10" class="form-control"></textarea>
</div>
<div class="form-group">
<button class="btn pull-right">Leave a reply</button>
</div>
</form>
#else
<div class="text-center">
<h2>Sign in to leave a reply</h2>
</div>
#endif
</div>
</div>
#endsection
You're getting this error because both queries return null:
$discussion = Discussion::where('slug', $slug)->first();
$best_answer = Reply::where('best_answer', 1)->first();
So, you need to check for empty result manually with is_null() or empty() or just:
if (!$discussion) {
abort(404);
}
Or use findOrFail() to throw an exception if no record found.
You are trying to access property with null objects, and that's why you got the error like "Trying to get property of null object".
As per our discussion in comments, you are getting null values in both queries and that's the reason for error!
Try to add if..else condition like below:
if (!$d) {
session()->flash('error', 'Discussion not found.');
return redirect()->back();
} else {
return view('discussion.show')->with('d', $discussion)->with('best_answer', $best_answer);
}
Hope this helps you!
Make sure you're not returning an object and accessing it as an array. It can be a common error.
I solved mine by adding: <?php error_reporting(0);?> on page where i got error. :D

Laravel : Search result search?page=2 show nothing, just blank page

My pagination works correctly, but when use search component it display only first page of result.
My page URL without search looks like:
http://localhost:8000/dictionary-management/postcode?page=2
And it's work correctly.
My first page URL with search:
http://localhost:8000/dictionary-management/postcode/search
and it's work correctly.
My second page URL with search:
http://localhost:8000/dictionary-management/postcode/search?page=2
and the is nothing to show, only blank page.
This is my Controller Search method:
public function search(Request $request) {
$constraints = [
'postcode' => $request['postcode'],
'address' => $request['address']
];
$postcodes = $this->doSearchingQuery($constraints);
return view('dictionary-mgmt/postcode/index', ['postcodes' => $postcodes, 'searchingVals' => $constraints]);
}
private function doSearchingQuery($constraints) {
$query = Postcode::query();
$fields = array_keys($constraints);
$index = 0;
foreach ($constraints as $constraint) {
if ($constraint != null) {
$query = $query->where( $fields[$index], 'like', '%'.$constraint.'%');
}
$index++;
}
return $query->Paginate(5);
}
This is my route :
Route::resource('dictionary-management/postcode', 'PostCodeController');
Route::post('dictionary-management/postcode/search', PosstCodeController#search')->name('postcode.search');
This is my index view :
#extends('dictionary-mgmt.postcode.base')
#section('action-content')
<!-- Main content -->
<section class="content">
<div class="box">
<div class="box-header">
<div class="row">
<div class="col-sm-8">
<h3 class="box-title">List kodów pocztowych</h3>
</div>
<div class="col-sm-4">
<a class="btn btn-primary pull-right" href="{{ route('postcode.create') }}">Dodaj nowy kod pocztowy</a>
</div>
</div>
</div>
<!-- /.box-header -->
<div class="box-body">
<div class="row">
<div class="col-sm-6"></div>
<div class="col-sm-6"></div>
</div>
<form method="POST" action="{{ route('postcode.search') }}">
{{ csrf_field() }}
#component('layouts.search', ['title' => 'Szukaj'])
#component('layouts.two-cols-search-row', ['items' => ['postcode', 'address'], 'title' => ['Kod','Adres'],
'oldVals' => [isset($searchingVals) ? $searchingVals['postcode'] : '', isset($searchingVals) ? $searchingVals['address'] : '']])
#endcomponent
#endcomponent
</form>
<div id="example2_wrapper" class="dataTables_wrapper form-inline dt-bootstrap">
<div class="row">
<div class="col-sm-12">
<table id="example2" class="table table-bordered table-hover dataTable" role="grid" aria-describedby="example2_info">
<thead>
<tr role="row">
<th width="5%">Kod pocztowy</th>
<th width="40%">Adres</th>
<th width="10%">Miejscowość</th>
<th width="10%">Województwo</th>
<th width="10%">Powiat</th>
<th>Akcja</th>
</tr>
</thead>
<tbody>
#foreach ($postcodes as $postcode)
<tr role="row" class="odd">
<td>{{ $postcode->postcode }}</td>
<td>{{ $postcode->address }}</td>
<td>{{ $postcode->city }}</td>
<td>{{ $postcode->voivodeship }}</td>
<td>{{ $postcode->county }}</td>
<td>
<form class="row" method="POST" action="{{ route('postcode.destroy', ['id' => $postcode->id]) }}" onsubmit = "return confirm('Czy napewno usunąć?')">
<input type="hidden" name="_method" value="DELETE">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<a href="{{ route('postcode.edit', ['id' => $postcode->id]) }}" class="btn btn-warning col-sm-3 col-xs-5 btn-margin">
Edytuj
</a>
<button type="submit" class="btn btn-danger col-sm-3 col-xs-5 btn-margin">
Usuń
</button>
</form>
</td>
</tr>
#endforeach
</tbody>
<tfoot>
<tr>
<th width="5%">Kod pocztowy</th>
<th width="40%">Adres</th>
<th width="10%">Miejscowość</th>
<th width="10%">Województwo</th>
<th width="10%">Powiat</th>
<th>Akcja</th>
</tr>
</tfoot>
</table>
</div>
</div>
<div class="row">
<div class="col-sm-5">
</div>
<div class="col-sm-7">
<div class="dataTables_paginate paging_simple_numbers" id="example2_paginate">
{{ $postcodes->links() }}
</div>
</div>
</div>
</div>
</div>
<!-- /.box-body -->
</div>
</section>
<!-- /.content -->
</div>
#endsection
And this is my search component:
<div class="row">
#php
$index = 0;
#endphp
#foreach ($items as $item)
<div class="col-md-6">
<div class="form-group">
#php
$stringFormat = strtolower(str_replace(' ', '', $item));
#endphp
<label for="input<?=$stringFormat?>" class="col-sm-3 control-label">{{$title[$index]}}</label>
<div class="col-sm-9">
<input value="{{isset($oldVals) ? $oldVals[$index] : ''}}" type="text" class="form-control" name="<?=$stringFormat?>" id="input<?=$stringFormat?>" placeholder="{{$title[$index]}}">
</div>
</div>
</div>
#php
$index++;
#endphp
#endforeach
</div>
Please help, I don't know where is my mistake...
Try this
{{ $postcodes->appends(request()->input())->links()}}
instead of {{ $postcodes->links() }}

Categories