model class is not working in laravel project - laravel-5.5

i am beginner in la-ravel,problem in work on model how be work on project.
firstly used the api.php to link the page
Route::any('/user',['uses'=>'PagesController#my']);
create the controller
public function my(Request $request){
$val=validator::make($request->all(),[
'id'=>'required',
'name'=>'required',
'email'=>'required',
'mobile'=>'required'
]);
//return 'rahul';
return response()->json([$val]);
}
model is link to the controller
use App\rahul;
use Validator;
create the model page design
class rahul extends Model{
protected $table = "display";
public function my($data)
{
$save = new rahul;
$save->id = $data['id'];
$save->name = $data['name'];
$save->email = $data['email'];
$save->mobile = $data['mobile'];
$save->save();
return $save->id;
}
}
and,last step will done it create the database like
enter image description here
database name is lara2 and table name display simple page design
but problem how to model be used

Route::get('first', 'ApiController#first')->name('first');
Route::post('store', 'ApiController#store')->name('store');
using the code in api.php
and next step model is create
php artisan make: model Article
model page
class Article extends Model{ protected $fillable = ['name', 'email'];}
next step create the controller
controller page (apicontroller)
public function first(){
return view('first');
}
public function store(Request $request)
{
$article = Article::create($request->all());
return response()->json($article, 201);
}
blade page web page design
<form method="POST" action="store">
{{csrf_field()}}
<input type="text" name="name">
<input type="email" name="email">
<input type="submit" name="submit"></form>
migration is create Article table name connection
public function up()
{
Schema::create('Articles', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('Articles');
}

Related

Why listing of items is empty in calling method of the component?

with livewire 2 I have listing of items ($itemDataRows var) and I need for any item show checkbox ($selectedItems var) and
"Select all" button and clicking on this button all items must be selected. I do :
class CrudItems extends Component
{
private $itemDataRows = [];
public $selectedItems = [];
...
public function render()
{
...
$this->itemDataRows = Item
::orderBy('created_at', 'desc')
...
->paginate($backend_per_page);
return view('livewire.admin.items.crud-items', [
'itemDataRows' => $this->itemDataRows,
'item_rows_count' => $this->item_rows_count
])->layout('layouts.admin');
}
}
public function calcSelectedItemsCount()
{
$ret= 0;
foreach( $this->selectedItems as $next_key=>$next_value ) {
if($next_value) {
$ret++;
}
}
return $ret;
}
public function selectAllItems()
{
$this->selectedItems= [];
\Log::info( dump($this->itemDataRows, ' -0 $this->itemDataRows selectAllItems::') );
// INL OG FILE_I SEE THAT ARRAY ABOVE IS EMPTY!!!
foreach( $this->itemDataRows as $nextItemDataRow ) {
$this->selectedItems[$nextItemDataRow->id] = true;
\Log::info( dump($this->selectedItems, ' -$this->selectedItems INSIDE selectAllItems::') );
}
\Log::info( dump($this->selectedItems, ' -$this->selectedItems selectAllItems::') );
}
and in template :
$selectedItems::{{ var_dump($selectedItems) }}<hr>
$itemDataRows::{{ $itemDataRows }}
/* $selectedItems is filled ok when I click on checkboxes , but $itemDataRows shows empty var, though I filled items listing below */
#foreach ($itemDataRows as $item)
<tr>
<td class=" whitespace-nowrap ">
<x-jet-checkbox id="is_reopen" type="checkbox" class="editor_checkbox_field ml-4" title="On saving editor will be opened"
wire:model="selectedItems.{{ $item->id }}"/>
</td>
Is something wrong with definition of $itemDataRows ? Why $itemDataRows is empty in selectAllItems method, but on my template all items are visible ok....
Thanks in advance!
In Livewire you can pass the data via the class variables. And in the mount function you can fill the variable. For Example.
Important Note: The Class Vars must be public!
public $selectedItems = [];
public function mount(): void
{
$this->selectedItems = ['data' => 'Hello World'];
}
public function render()
{
return view('livewire.admin.items.crud-items')->layout('layouts.admin');
}
Update
This must have something to do with the Livewire Lifecyle. Every Livewire component goes through a lifecycle. Lifecycle hooks allow you to run code at any stage of the component's lifecycle or before updating certain properties. In your case, use the mount hook.
You initialise the variable itemDataRows in the render function. A request then calls the method selectAllItems. There you have to initialise itemDataRows again, because the state is no longer there during render or mount.
Solution: create a method getItemDataRows()
private getItemDataRows()
{
$this->itemDataRows => Item::orderBy('created_at', 'desc')
...
->paginate($backend_per_page);
}
then you can call those in the render method and in the selectAllItems method too.
public function selectAllItems()
{
$this->selectedItems= [];
$this->itemDataRows => $this->getItemDataRows();
...
// your code
}

How to use where condition for laravel eloquent with function ( into the child table)

My Post Model like:
namespace App;
use Illuminate\Database\Eloquent\Model;
class **Post** extends Model
{
protected $table = 'posts';
protected $guarded = ['id'];
public function user(){
return $this->belongsTo('App\User','user_id','id');
}
}
And User Model like:
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $table = 'users';
protected $guarded = ['id'];
public function userType(){
return $this->belongsTo('App\User','user_type_id','id');
}
}
Now if I call the following in my controller:
$posts = \App\Post::with('user.userType')->where('status', 1)->get();
It returns all the posts for posts.status = 1, with users table data and also user_type.
What should I do??, if I want to set a where condition for users table or for user_types table like: where('user.id', 5) or where('user_types.id', 1).
Is it possible?? if yes please answer.
Thanks in advance.

Many To Many friendlist with symfony 3

I want to make a friendlist using ManyToMany self-referencing.
I followed this link and it seemms to be good. But Now, what Action should I have in my controller to :
1- get All myFriends / or all all friend of current user
2- add a firend, using a link such as "Add friend"
thank you for your time and answers
in your link my friends is a doctrine array collection, to get the friends of a user just iterate on it and to add a friend just add a friend onto this collection and save the entity (with the entity manager), maybe you ll need to add a cascade persist on the collection to add a new user as friend.
you have to add some methods like getMyFriends, addFriend and removeFriend
<?php
/** #Entity */
class User
{
// ...
/**
* Many Users have Many Users.
* #ManyToMany(targetEntity="User", mappedBy="myFriends")
*/
private $friendsWithMe;
/**
* Many Users have many Users.
* #ManyToMany(targetEntity="User", inversedBy="friendsWithMe")
* #JoinTable(name="friends",
* joinColumns={#JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#JoinColumn(name="friend_user_id", referencedColumnName="id")}
* )
*/
private $myFriends;
public function __construct() {
$this->friendsWithMe = new \Doctrine\Common\Collections\ArrayCollection();
$this->myFriends = new \Doctrine\Common\Collections\ArrayCollection();
}
public function getMyFriends(){
return $this->myFriends;
}
public function addFriend(User $friend){
$this->myFriends->add($friend);
}
public function removeFriend(User $friend){
$this->myFriends->removeElement($friend);
}
}
in your controller you have to implement an action with
$currentUser= $this->get('security.context')->getToken()->getUser();
$myFriends = $currentUser->getMyfriends();
$this->render('your-template.html.twig', array(
'myFriends' => $myFriends,
));
and in your twig template
<h1>My friends</h1>
<ul>
{% for friend in myFriends %}
<li>{{ friend.username }}</li>
{% endfor %}
</ul>

Doctrine with ZF2 Annotation: how to clear a multi select field?

I've got a problem with my multi select fields. Here is the code:
In the Entity class
/**
* #Annotation\Options({ "disable_inarray_validator":"true", "label":"Bound Checkpoints", "target_class":"Checkpoint","property":"name"})
* #Annotation\Type("DoctrineORMModule\Form\Element\EntitySelect")
* #Annotation\Attributes({ "multiple":"true", "class":"form-control"})
* #Annotation\Required(false)
* #ORM\ManyToMany(targetEntity="Checkpoint", inversedBy="affectedByCheckpoints")
*/
private $boundCheckpoints;
public function __construct() {
$this->boundCheckpoints= new \Doctrine\Common\Collections\ArrayCollection();
}
public function addBoundCheckpoints( $items)
{
foreach($items as $item)
{
$this->boundCheckpoints->add($item);
}
}
public function removeBoundCheckpoints($items)
{
foreach($items as $item)
{
$this->boundCheckpoints->removeElement($item);
}
}
My issue is: if I set some stuff into the field, it save it well. If I remove one, still working. But if I remove all items I set and fire the form, the removeBoundCheckpoints method is never called.
I tried to set a required validator to the form, but If I do that, I've got a validation issue.
Any ideas ?
solved by adding this workaround into the template.
{% if field.getAttribute('multiple') == 'multiple' or field.getAttribute('multiple') == 'true' %}
<input type="hidden" name="{{field.getName()}}" value="" />
{% endif %}
{{formElement(field) }}

play 2.0 templates html select with if statement in a map

I want to create a <select> without using the helpers (because the select helper is generating a lot of html)
So, I get a list of cities from the Controller like:
public static List<City> getAllSortedByNameAsc() {
List<City> cities = new ArrayList<City>();
cities.addAll(City.find.orderBy("name").findList());
return cities;
}
In my template, I create the options with this code:
#cities.map { city =>
<option value="#city.id">#city.name</option>
}
which works, but I also want to have the chosen city as selected value. I tried several things like this:
#cities.map { city =>
<option value="#city.id" selected="#if(offerForm("city.id").value == city.id){selected}">#city.name</option>
}
But that doesn't work. Can anyone give me a hint?
Configuration File: application.conf
db.default.driver=org.h2.Driver
db.default.url="jdbc:h2:mem:play"
ebean.default="models.*"
Controller Class => Application.java
package controllers;
import play.*;
import play.mvc.*;
import models.City;
import play.data.Form;
import views.html.*;
public class Application extends Controller {
final static Form<City> cityForm = form(City.class);
public static Result index() {
City pune=new City();
pune.name="pune";
pune.save();
City mumbai=new City();
mumbai.name="mumbai";
mumbai.save();
City city=City.get(2L);
return ok(index.render(cityForm.fill(city),City.all()));
}
}
Model Class => City.java:
package models;
import javax.persistence.Entity;
import javax.persistence.Id;
import play.db.ebean.Model;
import java.util.List;
import com.avaje.ebean.validation.NotNull;
#Entity
public class City extends Model{
#Id
public Long id;
#NotNull
public String name;
public static Finder<Long, City> find = new Finder(Long.class, City.class);
public static City get(Long id){
return find.byId(id);
}
public static List<City> all() {
return find.all();
}
}
Template File => index.scala.html
#(cityForm: Form[City],cities: List[City])
<!DOCTYPE html>
<html>
<head><title></title></head>
<body>
<div>
<select>
#for(city <- cities){
<option value="#city.id" #{if(city.id.toString().equals(cityForm("id").value)) "selected='selected'"}/>#city.name</option>
}
</select>
</div>
</body>
</html>
I'm not positive about how the type mapping is working, but I would try
#cities.map { city =>
<option value="#city.id" selected="#if(offerForm("city.id").value.equals(city.id)){selected}">#city.name</option>
}
rather than using the == operator.
You should also consider whether the helper has a good reason for generating all that HTML. It's generally a pretty smart framework.