I am currently making an edit page for some data in my database, and on the edit page I am trying to make a Form::select which lists the people in my users table.
controller-which-makes-the-edit-view.php
<?php
class AdminController extends BaseController
{
public $restful = true;
public function getUpdatePage($id)
{
return View::make('data_edit')
->with('title', 'Rediger måling/oppgave')
->with('data', Routine::find($id))
->with('emp', Emp::lists('user_name', 'id'));
}
data_edit.blade.php
{{ Form::label('emp', 'Ansatt') }}
{{ Form::select('emp', $emp, $data->emps->user_name) }}
Now my question is how would I go about making the default value for the select the person that saved the row which is currently being edited?
I do apologize if this already is answered, I couldn't seem to find it (neither here nor google).
This is Form::select() definition:
public function select($name, $list = array(), $selected = null, $options = array())
{
}
The third parameter is the item to be selected. You are currently passing
$data->emps->user_name
To it, but it depends on the data you have on $emp, because you must pass to it the array key, not the value.
Note that for now (Laravel 5.3+), ::lists is obsolete, use ::pluck instead.
Related
Trying do create a "like system" for a simple application with Laravel and Livewire. I have managed to add likes, but I only want the user to be able to add one (1) like to a post. At the moment a user can add as many likes as he or she wants.
This is my current function to store likes:
public function storeLike()
{
// Check if the user already has liked the post
if($this->collection->likes()->exists()){
return $this->collection->likes()->delete();
}
// If not, add one like to the db
$like = $this->collection->likes()->make();
$like->user()->associate(auth()->user());
// Save the like
$like->save();
}
And the part that im struggling with is:
if($this->collection->likes()->exists()){
return $this->collection->likes()->delete();
}
It deletes all the likes for that post. So how can a disassociate, detach that like if it exists?
This is how I have made the collection:
$collection = collect();
$posts = Post::search('topic', $this->search)->with(['user'])->latest()->get();
$urls = Urls::search('topic', $this->search)->with(['user'])->latest()->get();
$news = News::search('topic', $this->search)->latest()->get();
/** Push posts to the collection */
foreach ($posts as $post) $collection->push($post);
/** Push urls to the collection */
foreach ($urls as $item) $collection->push($item);
/** Push news to the collection */
foreach ($news as $item) $collection->push($item);
I think the toggle (see docs) method could be very handy.
Let's assume we're building a component for a model called Post.
Livewire
public function clickedLike() {
$this->post->likes()->toggle(Auth::user());
}
Template
<button wire:click="clickedLike">
<3
</button>
Model
class Post extends Model {
public function likes() {
return $this->hasMany(User::class, 'likes')
}
}
I would like to recover the slug of 2 categories from my routes but can’t write the Controller.
My Route
Route::get('technicians/o/{occupation}/c/{city}', 'User\TechnicianController#viewoccupationcity');
My Controller
public function viewoccupationcity($slug)
{
$technicians = TechnicianResource::collection(occupation::where('slug',$slug)->firstOrFail()->technicians()
->with('city','occupation')
->latest()->get());
return $technicians;
}
Route::get('technicians/o/{occupation}/c/{city}', 'User\TechnicianController#viewoccupationcity');
Your controller will accept the parameters from your route as variables by order
public function viewoccupationcity($ocupation, $city)
{
...
}
Example:
URL: technicians/o/foo/c/bar
public function viewoccupationcity($ocupation, $city)
{
// $ocupation will be 'foo'
// $city will be 'bar
}
Ok, you would need to retrieve 2 variables as that is what you are passing
public function viewoccupationcity($occupation, $city)
If you want the whole slug to do another search then you would use the $request object. So like so
public function viewoccupationcity(Request $request, $occupation, $city){ // You also need to include the Request decleration
$slug = $request->path();
$technicians = TechnicianResource::collection(occupation::where('slug',$slug)->firstOrFail()->technicians()
->with('city','occupation')
->latest()->get());
return $technicians;
}
EDIT: We are having to do a lot of guesswork as your question isn't very clear. I think what you are trying to achieve is probably this
public function viewoccupationcity($occupation, $city){
$technicians = TechnicianResource::collection(occupation::where('city',$city)->where('occupation',$occupation)->firstOrFail()->technicians()
->with('city','occupation')
->latest()->get());
return $technicians;
}
If you need something more then you need to give more details
Is there any possible way to get a custom attribute value through eager load
For instance, given this custom attribute on a model:
class User extends Model {
protected $appends = ['is_member'];
public function getIsMemberAttribute() {
return 'yes';
}
}
and related model
class Awards extends Model {
public function owner(){
return $this->belongsTo('App\User');
}
}
I would love to be able to get is_member attribute in collection using request below:
$users=Awards::orderBy('created_at')->with('owner')->get();
According to Laravel's documentations, $appends is used for appending in array and JSON only...
Once the attribute has been added to the appends list, it will be included in both the model's array and JSON forms.
So, when you do something like dd($user). You will not be able to see the is_member field, but when you do something like $user->toArray() or $user->toJson() you will.
Basically, for places wherever is_member field is always present. All you need to do to access it is (say in Page View/Blade etc)
public function show($id) {
$user = User::get($id);
return view('users.show', ['user' => $user->toArray()]);
}
And then do,
Is Member? : {{ $user['is_member'] }}
// Or if you don't like blade you can do this
// Is Member? : <?php echo $user['is_member'] ?>
But as written in the comments by #Amit, there is no use case of this until you are using it for the sole purpose of APIs. For blade etc, you should prefer doing this
Is Member? : {{ $user->is_member ? 'Yes' : 'No' }}
// Again if you don't like blade you can do this
// Is Member? : <?php echo $user['is_member'] ? 'Yes' : 'No'; ?>
Hope this clears your doubts :)
I am trying to pass data to Controller of Laravel. here is how I do that :
in PagesController::
class PagesController extends Controller
{
public function contact(){
$data="some random ";
return view('contact',compact("data"));
}
}
now in contact.blade.php :
contact pages {{ $data }}
and it s hows
Whoops, looks like something went wrong.
What may be a problam?
try this
public function contact()
{
$data = 'some random';
return View('contact')->with('data' , $data );
}
make sure that the view works fine (if its inside a folder use return View('foldername.contact')
make sure that your view name is contact.blade.php (check uppercase letters)
and inside your view
this is my {{ $data }}
I'm making my first Larevel (4) application and I want to display the date that it was created and I'm getting this problem: Unexpected data found. Unexpected data found. Unexpected data found. Data missing
when I try to do this in my blade template
#extends('layout')
#section('content')
<h3>Name: {{ $user->name }}</h3>
<p>Email: {{ $user->email }}</p>
<p>Bio: {{ $user->bio }}</p>
#endsection()
#section('sidebar')
<p><small>{{ $user->created_at }}</small></p>
#endsection()
#stop
and my controller
<?php
class UserController extends BaseController
{
public $restfull = true;
public function get_index() {
//$users = User::all();// gets them in the order of the database
$users = User::orderBy("name")->get(); // gets alphabetic by name
$v = View::make('users');
$v->users = $users;
$v->title = "list of users";
return $v;
}
public function get_view($id) {
$user = User::find($id);
$v = View::make('user');
$v->user = $user;
$v->title = "Viewing " . $user->name;
return $v;
}
}
?>
it works as soon as I take out :
<p><small>{{ $user->created_at }}</small></p>"
any ideas how to access those values, I checked and they DO exist in my table.
this is the schema of my table
CREATE TABLE "users" ("id" integer null primary key autoincrement, "email" varchar null, "name" varchar null, "bio" varchar null, "created_at" datetime null, "updated_at" datetime null);
So here's what I did to fix it.
in the migrations I did this:
class CreateTable extends Migration {
public function up()
{
Schema::create('users', function($table) {
$table->string('name');
$table->timestamps();
});
}
/* also need function down()*/
I had the insertions like this in my migrations to add some users.
class AddRows extends Migration {
/* BAD: this does NOT! update the timestamps */
public function up()
{
DB::table('users')->insert( array('name' => 'Person') );
}
/* GOOD: this auto updates the timestamps */
public function up()
{
$user = new User;
$user->name = "Jhon Doe";
$user->save();
}
}
Now when you try to use {{ $user->updated_at }} or {{ $user->created_at }} it will work! (assuming that you passed $user to the view)
There are a few things going on here that should probably be fixed. Since this is a restful controller, Laravel expects your function names to be camelCase rather than snake_case.
The way you are passing variables to the view also is not looking right. Try passing the $users variable to the view with return View::make('users')->with('users',$users);.
Another thing is you are passing a collection of users to the view, which means you won't just be able to echo user information. To get the user information out of the collection, you must iterate through the collection with a loop. (Your app will probably break again once you get more than one user in)
foreach($users as $user)
{
echo $user->name;
echo $user->email;
echo $user->bio;
}
Because the way you have your sidebar and content sections showing user information, what you probably actually want to do to get your user is something along the lines of $user = User::find(Auth::user()->id); meaning it would be returning one user and you'd be able to lose the loop.
One more thing I just seen. If you are setting up a restful controller, the proper property is public $restful = true; though I'm not sure that's actually being used anymore because you are basically setting that in routes.php with Route::controller('user', 'UserController');.