laravel 5.0 delete and edit in database - php

How can I delete or edit things from my database in Laravel 5.0 with the public function destroy and edit?
This is my library, here I want to delete or update something from my database
#foreach ($allJobs as $job)
<tr>
<td><img src="{{$job->selected_icon}}" width="50" /> </td>
<td>{{$job->jobtitle_de}}</td>
<td>{{$job->location}}</td>
<td><img src="{{$job->selected_image}}" width="100" /></td>
<td>{{$job->workinghours}}</td>
<td>{{$job->grey_header_de}}</td>
<td>{{$job->date}}</td>
<td>
<button>Edit</button> <a href="/delete">
<button>Delete</button></a></td>
<!--<td> <button type="delete" name="button"></button>-->
<td>
</td>
</tr>
#endforeach

In your controller (I will assume that you have created), implements this two functions.
public function edit($id) {
// Create a var called `$job` and uses the function `find()` passing into the $id that you clicked before
$job = Job::find($id);
// Return a view with the object that you found into a edit view
return view('jobs.edit', [
'job' => $job
]);
}
public function destroy($id) {
// Use the function `find()` passing into the $id that you clicked before and that use the delete method to delete the job
Job::find($id)->delete();
// Returning into a route that contains the jobs, probably
return redirect()->route('jobs');
}
Read the docs https://laravel.com/docs/5.4/controllers

in your route:
Route::post('delete','CallyourController#delete');
Route::post('update','CallyourController#update');
I think this is what you want to do.

my Controller:
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Request;
use App\Jobs;
class JobController extends Controller {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
return view('library',['allJobs' => Jobs::all()]);
}
//my create function
public function create()
{
return view('add');
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store(Request $request)
{
$job = new Jobs();
$job->jobtitle_de = array_key_exists('jobtitle_de',$_POST) ?
$_POST['jobtitle_de'] : '';
$job->jobtitle_en = array_key_exists('jobtitle_en',$_POST) ?
$_POST['jobt'] : '';
if (array_key_exists('place', $_POST)) {
$places = $_POST['place'];
$placesString = "";
foreach ($places as $p) {
$placesString .= $p.',';
}
$job->location = $placesString;
}
$job->workinghours = array_key_exists('workinghours',$_POST) ?
$_POST['workinghours'] : '';
$job->workinghours_de = array_key_exists('workinghours',$_POST) ?
$_POST['workinghours'] : '';
$job->selected_image= array_key_exists('selected_image',$_POST) ?
$_POST['selected_image'] : '';
$job->grey_header_de = array_key_exists('grey_header_de',$_POST) ?
$_POST['grey_header_de'] : '';
$job->selected_icon = array_key_exists('selected_icon',$_POST) ?
$_POST['selected_icon'] : '';
$job->selected_icon = array_key_exists('selected_icon',$_POST) ?
$_POST['selected_icon'] : '';
$job->selected_icon = array_key_exists('selected_icon',$_POST) ?
$_POST['selected_icon'] : '';
$job->selected_icon = array_key_exists('selected_icon',$_POST) ?
$_POST['selected_icon'] : '';
$job->date;
if (array_key_exists('date',$_POST) && !empty($_POST['date'])) {
$date = $_POST['date'];
$date = explode('/',$_POST['date']);
$newdate = $date[2]."-".$date[0]."-".$date[1];
$job->date = $newdate;
}
$job->grey_header_de = $_POST['grey_header_de'];
if (array_key_exists('workinghours',$_POST) && $_POST['workinghours']
=== "full-time") {
$job->workinghours = $_POST['workinghours'];
$job->workinghours_de = "Vollzeit";
}
if (array_key_exists('workinghours',$_POST) && $_POST['workinghours']
=== "part-time"){
$job->workinghours = $_POST['workinghours'];
$job->workinghours_de = "Teilzeit";
}
try {
$job->save();
}
catch (Exceptions $e) {
echo $e->getMessage();
}
return redirect()->action('JobController#index');
}
//my edit function
public function edit($id)
{
$job = Job::find($id);
return view('jobs.edit', [
'job' => $job
]);
}
//destroy function
public function destroy($id)
{
Job::find($id)->delete();
return redirect()->route('jobs');
}

now I found this in the internet:
<div class="library">
<table>
#foreach ($allJobs as $job)
<tr>
<td><img src="{{$job->selected_icon}}" width="50" /> </td>
<td>{{$job->jobtitle_de}}</td>
<td>{{$job->location}}</td>
<td><img src="{{$job->selected_image}}" width="100" /></td>
<td>{{$job->workinghours}}</td>
<td>{{$job->grey_header_de}}</td>
<td>{{$job->date}}</td>
<td>
{{ Form::open(['method' => 'DELETE', 'route' => 'job.destroy', $job]-
>id]) }}
{{ Form::hidden('id', $job-id) }}
{{ Form::submit('delete', ['class' => 'library']) }}
{{Form::close}}
</td>
</tr>
#endforeach
and this is my Controller
public function destroy($id)
{
$jobs = Job::findOrFail($id);
$jobs->delte();
return redirect::route('/');
}

Related

Facing strange problem in Laravel Components

I am passing data to the view of the component by $user->profile->profile_pic when I dd in that view it shows the desired value perfectly. But when I use that in some conditions or in tags to print that value it says that Attempt to read property "profile_pic" on null. Although, It is not because I can die and dump that and that value can be seen
Usage of the component:
<x-details
:user="$user->id"
class="w-96 mt-10 py-4"
letter="{{ $user->username[0] }}"
editable="{{ Auth::user()->username == $user->username }}"
profile_pic="{{ $user->profile->profile_pic }}"
/>
The component
<?php
namespace App\View\Components;
use Illuminate\View\Component;
use App\Models\User;
use Illuminate\Support\Facades\DB;
class details extends Component
{
/**
* Create a new component instance.
*
* #return void
*/
public $user;
public function __construct($user = 1)
{
$this->user = $user;
}
/**
* Get the view / contents that represent the component.
*
* #return \Illuminate\Contracts\View\View|\Closure|string
*/
public function render()
{
$user = User::with(['profile'])->firstWhere("id", $this->user);
$pic = $user->profile->profile_pic;
return view('components.details', compact("pic"));
}
}
The view of the component
<div>
#props([
"letter" => "A",
"editable" => 0,
"profile_pic" => 0
])
{{-- #php
$src = "";
if($profile_pic) {
$src = "/uploads/$profile_pic";
} else {
$src = url("fonts/icons/avatars/$letter.svg");
}
#endphp --}}
<div>
{{-- #dd($pic) --}}
{{ $pic }}
{{-- #if(!$editable)
#else
<form id="fileUpload">
<input class="hidden" type="file" name="upload_pic" id="upload_pic">
</form>
#endif --}}
</div>
</div>
It's a common issue when you trying to dd() something in foreach, it will always dump first item only and die, so you are always confirm first item and think it work as well as expected.
In your case, there is probably some user doesn't have profile_pic or profile don't have any profile_pic related on it.
Try to use the code below to debug with it in your component.
public function render()
{
try {
$user = User::with(['profile'])->firstWhere("id", $this->user);
$pic = $user->profile->profile_pic;
return view('components.details', compact("pic"));
} catch (Exception $e) {
dd($user->profile);
}
}
Inside the component, you should use $this:
So instead of
$pic = $user->profile->profile_pic
You should do
$pic = $this->user->profile->profile_pic

multiple data insert into database in laravel

Hi i am new to laravel i am having trouble in inserting data into database and throwing error as
"count(): Parameter must be an
array or an object that implements Countable"
i want to add attendence details of all the registred employees in the databse
controller
public function Attendence()
{
$data=employee_data::all();
return view('attendence',compact('data'));
}
public function mark_attendence(Request $request)
{
$request->validate([
'date' => 'required',
'is_present' => 'required'
]);
$data=$request->all();
$last_id=employee_data::create($data)->id;
if (count($request->is_present) >0 )
{
# code...
foreach ($return->is_present as $item => $v)
{
$data2=array(
'is_present' =>$request->is_present[$item],
'date'=> $request->date[$item],
'user_id'=>$last_id
);
}
//$data2->save();
//$employee->save();
//$employee->employee_data()->create([]);
return redirect('/index')->with('succ','Attendence Added Successfully');
}
Blade output:
Submit
Id
First Name
Last Name
DateOfJoining
post
Remark
#foreach( $data as $row )
{{ $row->id }}
{{ $row->first_name }}
{{ $row->last_name }}
{{ $row->date_joining }}
{{ $row->post }}
&nbsp &nbsp Present
&nbsp &nbsp Absent
#endforeach
Id
First Name
Last Name
DateOfJoining
post
Remark
Model
class employee_attendence extends Model
{
//
protected $fillable = array('is_present' ,'date', 'user_id' );
//protected $fillable=[];
public $timemstamps= false ;
public function employee_data(){
//return $this->hasOne(employee_data::class,'App/employee_data');
return $this->hasOne('App\employee_data');
}
}
Model2
namespace App;
use Illuminate\Database\Eloquent\Model;
class employee_data extends Model
{
//protected $fillabel=['first_name','last_name','contact_no','date_joining','post'];
protected $fillable = array('first_name', 'last_name', 'contact_no' ,'date_joining','post' );
//protected $fillable=[];
public $timemstamps= false ;
public function employee_attendence()
{
//return $this->hasOne( employee_attendence::class, 'App/employee_attendence');
return $this->belongsTo('App\employee_attendence');
}
}
As far as I understand. You might have is_present will be an array format from view like name="is_present[]". If this your case then the below code will work fine. if not then you can't use count() if input is not an object or array
public function mark_attendence(Request $request)
{
for($i = 0; $i < sizeof($request->is_present); $i++)
{
$emp = new employee_attendence();
if($request->is_present[$i] == "Present")
$emp->is_present = "Present";
if($request->is_present[$i] == "Absent")
$emp->is_present = "Absent";
$emp->date = now();
$emp->user_id = $request->user_id[$i];
$emp->save();
}
return redirect('/index')->with('succ','Attendence Added Successfully');
}
In your Add Attendance method try this
this worked for me
for($i = 0; $i < sizeof($request->is_present); $i++)
{
$emp = new employee_attendence();
if($request->is_present[$i] == "Present")
$emp->is_present = "Present";
if($request->is_present[$i] == "Absent")
$emp->is_present = "Absent";
$emp->date = $request->date;
$emp->user_id = $request->user_id[$i];
$emp->save();
}

How to add an 'order by' button when working with MVC structure on php?

I'm pretty new to Laravel and the MVC structure.
I want to add two buttons to a page, that will determine the order the products in it, appear. (price - low to high or high to low).
I'm trying to use the query string like so:
href="{{ url('store/' . $cat_url . '?order=ASC') }}">Price: Low to High</a> |
href="{{ url('store/' . $cat_url . '?order=DESC') }}">Price: Hign to Low</a>
This is my product view :
#foreach($products as $row)
<div class="col-md-6">
<h3>{{$row['title']}}</h3>
<p><img border="0" width="300" src="{{asset('images/' .$row['image'])}}"></p>
<p>{!! $row['article'] !!}</p>
<p><b>Price for pack:</b> {{ $row['price'] }}</p>
<p>
<input #if(Cart::get($row['id'])) disabled="disabled" #endif data-id="{{ $row['id']}}" type="button" value="Add to Order" class="add-to-order btn btn-success">
More Details
</p>
</div>
#endforeach
This is the model:
static public function getProducts($category_url, &$data)
{
$data['products'] = [];
if ($category = Category::where('url', $category_url)->first()) {
$category = $category->toArray();
$data['title'] = 'Candy | '. $category['title'];
$data['cat_url'] = $category['url'];
$data['cat_title'] = $category['title'];
$products = Category::find($category['id'])->products;
$data['products'] = $products->toArray();
}
}
And his is the controller : (I'm trying to get the the 'order' key using 'Input::')
public function products($category_url)
{
$order = Input::get('order');
Product::getProducts($category_url, self::$data);
return view('content.products', self::$data);
}
How can I add the query with the ORDER BY element to this model? How to get the value from the query string if the key appears?
Thanks a lot!
Try this:
static public function getProducts($category_url, &$data, $order = null){
$data['products'] = [];
if($category = Category::where('url', $category_url)->first()){
...
if ($order) {
$products = Category::find($category['id'])->products()->orderBy('price', $order)->get()
} else {
$products = Category::find($category['id'])->products;
}
...
}
}
You said you want to use MVC structure but your passed the order in url like query parameter with ? marks. This is not correct way in MVC you can use the Routing for that?
Give one try to this..
Register your Routes likes this
Route::get('store/{cat_url}/{order?}', "ControllerName#products");
Controller Method
use Illuminate\Http\Request;
public function products(Request request, $cat_url, $order="asc")
{
Product::getProducts($cat_url,$order, self::$data);
return view('content.products', self::$data);
}
Model Method
static public function getProducts($category_url, $order,&$data)
{
$data['products'] = [];
if ($category = Category::where('url', $category_url)->orderBy("your_field_name",$order)->first()) {
$category = $category->toArray();
$data['title'] = 'Candy | '. $category['title'];
$data['cat_url'] = $category['url'];
$data['cat_title'] = $category['title'];
$products = Category::find($category['id'])->products;
$data['products'] = $products->toArray();
}
}
Your links
href="{{ url('store/' . $cat_url . '/asc') }}">Price: Low to High</a> |
href="{{ url('store/' . $cat_url . '/desc') }}">Price: Hign to Low</a>
Happy Coding...

Display name of select form rather than it's Id (error:Trying to get property of non-object) laravel 5

I have 2 tables tn_client and tn_project, which project have 1 client while client can have many projects, rather than displaying client id on my table, i want display its client name but when i did that its said trying to get property of non-object.
Trying to get property of non-object (View:
C:\xampp\htdocs\PKL\netxcel-activityreport-11b90b878d39\resources\views\project.blade.php)
Above is the full error that i get, and below is the tables
tn_project
tn_client
CONTROLLER
public function index(){
Log::info('Entering index');
return view('project')
->with('title','Project')
->with('projects',Project::with('client','invoice')->get())
->with('clients',Client::all())
->with('invoices', Invoice::all());
}
//get all data
public function getAll(){
return Response::json(
array(
'content' => Project::with('client','invoice')->get(),
'status' => 'success',
)
);
}
public function createOrEdit(){
$currentUsername = Auth::user()->name;
$isUpdate = false;
$projectId = Input::get('prevId');
//populate data
$project = new Project;
if($projectId != ""){
$project = Project::where('cv_id','=',$projectId)->firstOrFail();
$project->cv_updated_by = $currentUsername;
$project->cn_updated_at = Carbon::now();
$isUpdate = true;
} else{
$project->cv_created_by = $currentUsername;
$project->cn_created_at = Carbon::now();
}
$project->cv_id = Input::get('projectId');
$project->cv_name = Input::get('projectName');
$project->cv_client_id = Input::get('clientId');
$project->cn_invoice_method = Input::get('invoiceId');
$project->cn_project_rate = Input::get('projectRate');
$project->cn_note = Input::get('note');
//execute
if($isUpdate){
Log::info("entering update mode");
Project::where('cv_id','=',$projectId)->update(['cv_id'=>$project->cv_id,
'cv_name'=>$project->cv_name,
'cv_client_id'=>$project->cv_client_id,
'cn_invoice_method'=>$project->cn_invoice_method,
'cn_project_rate'=>$project->cn_project_rate,
'cn_note'=>$project->cn_note,
'cn_updated_at'=>$project->cn_updated_at,
'cv_updated_by'=>$project->cv_updated_by]);
}else{
$project->save();
}
return Response::json(
array(
'content' => Project::with('client','invoice')->get(),
'status' => 'success',
)
);
}
Model
PROJECT
<?php
namespace Activity;
use Illuminate\Database\Eloquent\Model;
class Project extends Model {
protected $table = 'tn_project';
public $timestamps = false;
protected $fillable = [
'cv_id',
'cv_name',
'cv_client_id',
'cn_invoice_method',
'cn_project_rate',
'cn_note',
'cn_created_at',
'cv_created_by',
'cn_updated_at',
'cv_updated_by'
];
public function client(){
return $this->belongsTo('Activity\Client','cv_client_id','cn_id');
}
public function invoice(){
return $this->hasOne('Activity\Invoice','cn_id','cn_invoice_method');
}
}
CLIENT
<?php
namespace Activity;
use Illuminate\Database\Eloquent\Model;
class Client extends Model {
protected $table = 'tn_client';
public $timestamps = false;
protected $fillable = [
'cv_name',
'cv_contact',
'cv_email',
'cv_phone',
'cv_address',
'cn_created_at',
'cn_created_by',
'cn_updated_at',
'cn_updated_by'
];
public function project(){
return $this->hasOne('Activity\Project', 'cv_id', 'cn_id');
}
}
VIEW
this is my select form
<div class="col-md-9">
<select name="clientId" id="clientId" class="form-control" placeholder="Select Client">
#foreach ($clients as $client)
<option value='{{$client->cn_id}}'>{{$client->cv_name}}</option>;
#endforeach
</select>
</div>
This is how i called the function to display it in my view
#foreach($projects as $project)
<tr class="odd gradeX">
<td>{{$project->cv_id}}</td>
<td>{{$project->cv_name}}</td>
<td>{{$project->client->cv_name}}</td><!--This is what cause an -->
<td>{{$project->cn_invoice_method}}</td>
<td>{{$project->cn_project_rate}}</td>
<td>{{$project->cn_note}}</td>
<td>
<a class="btn btn-success" title="edit" data-id={{$project->cv_id}} data-action="project-edit"><i class="fa fa-pencil"></i></a>
<a class="btn btn-danger" title="delete" data-id={{$project->cv_id}} data-action="project-delete"><i class="fa fa-times"></i></a>
</td>
</tr>
#endforeach
im still new to laravel, and what did i do wrong that make such an error like that?
I found the answer, i got the reference from here so based on that reference and the basic of x->y->z, we got to check first that x->y have some value in it if yes we got to check whether it's an object or just an array, in my case it was an array so rather doing something like this
{{$project->client->cv_name}}
which is that how to display an object, we should do something like this
{{$project->client['cv_name']}}
and that is how you solve your problem, cheers :D

get next & previous id record in database on Yii

I need next & previous id record in database on Yii framework to make navigation buttons next and back ?
I added following functions in my model in Yii2:
public function getNext() {
$next = $this->find()->where(['>', 'id', $this->id])->one();
return $next;
}
public function getPrev() {
$prev = $this->find()->where(['<', 'id', $this->id])->orderBy('id desc')->one();
return $prev;
}
I made a function to get those ids your looking for. I suggest you to declare it in the model:
public static function getNextOrPrevId($currentId, $nextOrPrev)
{
$records=NULL;
if($nextOrPrev == "prev")
$order="id DESC";
if($nextOrPrev == "next")
$order="id ASC";
$records=YourModel::model()->findAll(
array('select'=>'id', 'order'=>$order)
);
foreach($records as $i=>$r)
if($r->id == $currentId)
return isset($records[$i+1]->id) ? $records[$i+1]->id : NULL;
return NULL;
}
So to use it all you have to do do is this:
YourModel::getNextOrPrevId($id /*(current id)*/, "prev" /*(or "next")*/);
It will return the corresponding id of the next or previous record.
I didn't test it, so give it a try and if something goes wrong please let me know.
Make a private var that is used to pass info to other functions.
In Model:
class Model1 .....
{
...
private _prevId = null;
private _nextId = null;
...
public function afterFind() //this function will be called after your every find call
{
//find/calculate/set $this->_prevId;
//find/calculate/set $this->_nextId;
}
public function getPrevId() {
return $this->prevId;
}
public function getNextId() {
return $this->nextId;
}
}
Check the code generated in the ViewDetal link and modify for the Prev/Net links in the _view file using
$model(or $data)->prevId/nextId
in the array('id'=>#) section.
Taking the original answer and adapting it for Yii2 with a little clean up:
/**
* [nextOrPrev description]
* #source http://stackoverflow.com/questions/8872101/get-next-previous-id-record-in-database-on-yii
* #param integer $currentId [description]
* #param string $nextOrPrev [description]
* #return integer [description]
*/
public static function nextOrPrev($currentId, $nextOrPrev = 'next')
{
$order = ($nextOrPrev == 'next') ? 'id ASC' : 'id DESC';
$records = \namespace\path\Model::find()->orderBy($order)->all();
foreach ($records as $i => $r) {
if ($r->id == $currentId) {
return ($records[$i+1]->id ? $records[$i+1]->id : NULL);
}
}
return false;
}
My implementation is based on SearchModel.
Controller:
public function actionView($id)
{
// ... some code before
// Get prev and next orders
// Setup search model
$searchModel = new OrderSearch();
$orderSearch = \yii\helpers\Json::decode(Yii::$app->getRequest()->getCookies()->getValue('s-' . Yii::$app->user->identity->id));
$params = [];
if (!empty($orderSearch)){
$params['OrderSearch'] = $orderSearch;
}
$dataProvider = $searchModel->search($params);
$sort = $dataProvider->getSort();
$sort->defaultOrder = ['created' => SORT_DESC];
$dataProvider->setSort($sort);
// Get page number by searching current ID key in models
$pageNum = array_search($id, array_column($dataProvider->getModels(), 'id'));
$count = $dataProvider->getCount();
$dataProvider->pagination->pageSize = 1;
$orderPrev = $orderNext = null;
if ($pageNum > 0) {
$dataProvider->pagination->setPage($pageNum - 1);
$dataProvider->refresh();
$orderPrev = $dataProvider->getModels()[0];
}
if ($pageNum < $count) {
$dataProvider->pagination->setPage($pageNum + 1);
$dataProvider->refresh();
$orderNext = $dataProvider->getModels()[0];
}
// ... some code after
}
OrderSearch:
public function search($params)
{
// Set cookie with search params
Yii::$app->response->cookies->add(new \yii\web\Cookie([
'name' => 's-' . Yii::$app->user->identity->id,
'value' => \yii\helpers\Json::encode($params['OrderSearch']),
'expire' => 2147483647,
]));
// ... search model code here ...
}
PS: be sure if you can use array_column for array of objects.
This works good in PHP 7+ but in lower versions you got to extract id by yourself. Maybe it's good idea to use array_walk or array_filter in PHP 5.4+
Full implemenentation with performance improvement by using DB engine/optimization (when id acts as primary key):
Model:
public static function getNextPrevId($currentId)
{
$queryprev = new Query();
$queryprev->select('max(id)')->from(self::tableName())->where('id<:id',['id'=>$currentId]);
$querynext = new Query();
$querynext->select('min(id)')->from(self::tableName())->where('id>:id',['id'=>$currentId]);
return [ $queryprev->scalar(), $querynext->scalar()];
}
Controller:
public function actionView($id) {
return $this->render('view', [
'model' => $this->findModel($id),
'nextprev' => YourModel::getNextPrevId($id),
]);
}
View:
<?= !is_null($nextprev[0]) ? Html::a('⇦', ['view', 'id' => $nextprev[0]], ['class' => 'btn btn-primary']) : '' ?>
<?= !is_null($nextprev[1]) ? Html::a('⇨', ['view', 'id' => $nextprev[1]], ['class' => 'btn btn-primary']) : '' ?>
The previous solutions are problematic when you get the the first or last record and they are making multiple calls to the database. Here is my working solution which operates on one query, handles end-of-table and disables the buttons at end-of-table:
Within the model:
public static function NextOrPrev($currentId)
{
$records = <Table>::find()->orderBy('id DESC')->all();
foreach ($records as $i => $record) {
if ($record->id == $currentId) {
$next = isset($records[$i - 1]->id)?$records[$i - 1]->id:null;
$prev = isset($records[$i + 1]->id)?$records[$i + 1]->id:null;
break;
}
}
return ['next'=>$next, 'prev'=>$prev];
}
Within the controller:
public function actionView($id)
{
$index = <modelName>::nextOrPrev($id);
$nextID = $index['next'];
$disableNext = ($nextID===null)?'disabled':null;
$prevID = $index['prev'];
$disablePrev = ($prevID===null)?'disabled':null;
// usual detail-view model
$model = $this->findModel($id);
return $this->render('view', [
'model' => $model,
'nextID'=>$nextID,
'prevID'=>$prevID,
'disableNext'=>$disableNext,
'disablePrev'=>$disablePrev,
]);
}
Within the view:
<?= Html::a('Next', ['view', 'id' => $nextID], ['class' => 'btn btn-primary r-align btn-sm '.$disableNext]) ?>
<?= Html::a('Prev', ['view', 'id' => $prevID], ['class' => 'btn btn-primary r-align btn-sm '.$disablePrev]) ?>

Categories