I'm trying to call a variable from a table, but I'm getting an error "Undefined variable $user". I'm trying to make the program display the Username from the user from the table.
I'm using 2 tables, tribes which represents something like a group, and a user which represents.. well.. user.
So I'm trying to connect the two by displaying the creator of a certain "tribe".
User controller:
<?php
namespace App\Http\Controllers;
Use App\Models\User;
use Illuminate\Http\Request;
class tribesController extends Controller
{
public function index($user)
{
$user = User::findOrFail($user);
return view('home',[
'user'=>$user,
]);
}
}
Homepage:
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Dashboard') }}</div>
<div class="card-body">
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
{{ $user->username }}
</div>
</div>
</div>
</div>
</div>
#endsection
Router:
<?php
use Illuminate\Support\Facades\Route;
/*
Route::get('/', function () {
return view('welcome');
});
Route::get('/home', function () {
return view('home');
});
Route::get('/playlist', function () {
return view('playlist');
});
Route::get('/tribe', function () {
return view('tribe');
});
Route::get('/edit', function () {
return view('edit');
});
Auth::routes();
Route::get('/tribe/{user}', [App\Http\Controllers\TribesController::class, 'index'])->name('tribe.index');
Database file:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateTribesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('tribes', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->string('title');
$table->string('genre');
$table->string('filepath')->nullable();
$table->timestamps();
$table->index('user_id');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('tribes');
}
}
model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class tribe extends Model
{
public function user(){
return $this->belongsTo(User::class);
}
use HasFactory;
}
You are treating the url parameter as a object, it can't be an object until you get it. Pass in a user id and then query the ORM for a user matching that id then you can use it as an object!
Related
Hi I am trying to build a laravel real time chat. I configured websockets and it seems to be connecting, but now I am trying to send a message and its working but to the other user the message is not displayed unless I refresh the page. I was following a tutorial in youtube did everything like in the tutorial and I dont know why I am receiving this errors. If you can have a look I would appreciate it.
Errors I am receiving
DevTools failed to load SourceMap: Could not load content for http://127.0.0.1:8000/js/utf8.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
ChatsComponent.vue
<template>
<div class="row">
<div class="col-8">
<div class="card card-default">
<div class="card-header">Messages</div>
<div class="card-body p-0">
<ul class="list-unstyled" style="height:300px; overflow-y:scroll">
<li class="p-2" v-for="(message,index) in messages" :key="index">
<strong>{{ message.user.name }}</strong>
{{ message.message }}
</li>
</ul>
</div>
<input
#keyup.enter="sendMessage"
v-model="newMessage"
type="text"
name="message"
placeholder="Enter your message..."
class="form-control">
</div>
<span class="text-muted">User is typing...</span>
</div>
<div class="col-4">
<div class="card card-default">
<div class="card-header">Active Users</div>
<div class="card-body">
<ul>
<li class="py-2">Harish</li>
</ul>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
props:['user'],
data(){
return {
messages:[],
newMessage:'',
}
},
created(){
this.fetchMessages();
Echo.join('chat')
.listen('MessageSent', (event) => {
this.messages.push(event.message);
});
},
methods:{
fetchMessages(){
axios.get('messages').then(response =>{
this.messages = response.data
})
},
sendMessage(){
this.messages.push({
user:this.user,
message:this.newMessage
});
axios.post('messages', {message: this.newMessage});
this.newMessage='';
}
}
}
</script>
Message Model
class Message extends Model
{
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $fillable = ['message'];
public function user()
{
return $this->belongsTo(User::class);
}
}
And I added this to User model
public function messages()
{
return $this->hasMany(Message::class);
}
ChatsController
use Illuminate\Http\Request;
use App\Message;
use App\Events\MessageSent;
class ChatsController extends Controller
{
public function _construct(){
$this->middleware('auth');
}
public function index()
{
return view('chats');
}
public function fetchMessages()
{
return Message::with('user')->get();
}
public function sendMessages(Request $request)
{
$message = auth()->user()->messages()->create([
'message' => $request->message
]);
broadcast(new MessageSent($message->load('user')))->toOthers();
return ['status' =>'success'];
}
}
MessageEvent event
App\Message; use App\User;
class MessageSent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $message;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct(Message $message)
{
$this->message = $message;
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PresenceChannel('chat');
}
}
Routes
Route::get('/chats','ChatsController#index')->middleware('auth');
Route::get('/messages','ChatsController#fetchMessages');
Route::post('/messages','ChatsController#sendMessages');
Broadcast::channel('chat', function ($user) {
return $user;
});
Chat view
#extends('layouts.app')
#section('content')
<div class="container">
<chats :user="{{ auth()->user()}}"></chats>
</div>
#endsection
Hey so a bit of an overview of the project i want to do. I want to show the user's teams.
When the user logged in and opened the viewteams page. He must show teams he joined/created. To do so i ve done the below processes...
my ViewTeamController
{
public function index()
{
$user=User::first();
$teams=Team::all();
$user->teams()->attach($teams);
return view('teams.viewteams',compact('teams'));
}
public function store()
{
}
}
my User model
public function teams(){
return $this->belongsToMany(Team::class,'team_user','teams_id','users_id');
}
my Team model
public function users(){
return $this->belongsToMany(User::class,'team_user','teams_id','users_id');
}
my migration of the pivot table
public function up()
{
Schema::create('team_user', function (Blueprint $table) {
$table->unsignedBigInteger('users_id');
$table->unsignedBigInteger('teams_id');
$table->index('users_id');
$table->index('teams_id');
$table->timestamps();
});
}
web.php routes
Route::get('/viewteams','ViewTeamController#index');
Route::post('/viewteams','ViewTeamController#store');
my viewteams.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header"><h2 style="text-align:center;">Your Teams</h2></div>
<div class="card-body">
#foreach ($teams as $team)
#foreach($team->users as $user)
{{$user->org_name}}
#endforeach
#endforeach
</div>
</div>
</div>
</div>
</div>
#endsection
my other controller for Creating a team
<?php
namespace App\Http\Controllers;
use App\Team;
use Illuminate\Http\Request;
class CreateTeamController extends Controller
{
public function index(Request $request)
{
return view('teams.createteams');
}
public function store(Request $request)
{
$team=Team::create($request->all());
return redirect()->route('home');
}
}
all my routes
Route::get('/login', function () {
return view('auth/login');
});
Auth::routes();
Route::get('/viewteams','ViewTeamController#index');
Route::post('/viewteams','ViewTeamController#store');
Route::get('/createteams','CreateTeamController#index');
Route::post('/createteams','CreateTeamController#store') ;
Route::get('/home', 'HomeController#index')->name('home');
To achieve currents users teams, first you should get authenticated user id using Auth facade.
After that you can load joined teams for user, using 'with' method. It loads teams relationships.
ViewTeamController
public function index()
{
$user = User::with('teams')->find(Auth::id());
return view('teams.viewteams',compact('user'))
}
viewteams.blade.php
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header"><h2 style="text-align:center;">Your Teams</h2></div>
<div class="card-body">
#foreach ($user->teams as $team)
{{ $team->name }}
#endforeach
</div>
</div>
</div>
</div>
</div>
#endsection
You will need to revisit and update the code which stores data to the users table and the teams user. The easiest way to store the data in a way which populates the pivot table is to use the sync() method as described at https://laravel.com/docs/master/eloquent-relationships#updating-many-to-many-relationships
I'm making some assumptions about names and relationships, buy you may have something like this:
$user = User::find(2);
$user->teams()->sync([4,5]);
In this case, you would put into the pivot table a record for user_id of 2 and team_id of 4, and a second record for a user_id of 2 and a team_id of 5.
If you want to share more code showing route definitions and controllers for how you are currently handling things, we can help with any more specific implementation questions.
I am creating a chat in Laravel Websocket i followed a youtube tutorial and the message goes to the other user they can talk with each other but i need to reload the page to get the message that was sent,its not real time.At the console before i send a message it says this error: Failed to load resource: the server responded with a status of 404 (Not Found) and than after sending says this POST http://127.0.0.1:8000/broadcasting/auth 404 (Not Found) .I have run "php artisan websocket:serve" command in terminal.Thanks in advance
ChatsController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Message;
use App\Events\MessageSent;
class ChatsController extends Controller
{
public function __construct()
{
$this->middleware('auth');//only authenticated users can acces to chat
}
public function index()
{
return view('chats');
}
public function fetchMessages()
{
return Message::with('user')->get();
}
public function sendMessage(Request $request)
{
$message = auth()->user()->messages()->create([
'message' => $request->message
]);
broadcast(new MessageSent($message->load('user')))->toOthers();
return ['status' => 'success'];
}
}
User.php
public function messages()
{
return $this->hasMany(Message::class);
}
Message.php
public function user()
{
return $this->belongsTo(User::class);
}
web.php
<?php
use App\User;
use App\Department;
use App\Events\WebsocketDemoEvent;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
broadcast(new WebsocketDemoEvent('some data'));
return view('welcome');
});
Route::get('/page', function () {
return view('admin.page');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::group(['middleware' => ['auth','admin']], function () {
Route::get('/role-register','Admin\DashboardController#registered');
Route::delete('/role-delete/{id}', 'Admin\DashboardController#registerdelete');//delete user
Route::post('/save-user', 'Admin\DashboardController#store');
Route::get('/department', 'Admin\DepartmentController#index');
Route::post('/save-department', 'Admin\DepartmentController#store');
Route::get('/department-edit/{id}', 'Admin\DepartmentController#edit');//edit department
Route::put('/department-update/{id}', 'Admin\DepartmentController#update');
Route::delete('/department-delete/{id}', 'Admin\DepartmentController#delete');//delete department
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/chats', 'ChatsController#index');//chats
Route::get('/messages', 'ChatsController#fetchMessages');//messages
Route::post('/messages', 'ChatsController#sendMessage');//messages
Route::get('/dashboard', 'Admin\DashboardController#dbcheck');//DATABASE
Route::get('/user-edit/{id}', 'HomeController#registeredit');
Route::get('/role-edit/{id}', 'Admin\DashboardController#registeredit');//edit user
Route::put('/role-register-update/{id}', 'Admin\DashboardController#registerupdate');
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('store_image', 'StoreImageController#index');
Route::post('store_image/insert_image', 'StoreImageController#insert_image');
Route::get('store_image/fetch_image/{id}', 'StoreImageController#fetch_image');
Route::get('/page',array('as'=>'jquery.treeview','uses'=>'Admin\DepartmentController#treeView'));
Route::get('/pageusers', 'Admin\DepartmentController#usersdep');
ChatsComponent.vue
<template>
<div class="row">
<div class="col-8">
<div class="card card-default">
<div class="card-header">Messages</div>
<div class="card-body p-0">
<ul class="list-unstyled" style="height:300px; overflow-y:scroll">
<li class="p-2" v-for="(message, index) in messages" :key="index">
<strong>{{ message.user.name }}</strong>
{{ message.message }}
</li>
</ul>
</div>
<input
#keyup.enter="sendMessage"
v-model="newMessage"
type="text"
name="message"
placeholder="Enter your message"
class="form-control">
</div>
<span class="text-muted">user is typing...</span>
</div>
<div class="col-4">
<div class="card card-default">
<div class="card-header">Active Users</div>
<div class="card-body">
<ul>
<li class="py-2">{{ user.name }}</li>
</ul>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
props:['user'],
data() {
return {
messages: [],
newMessage:''
}
},
created() {
this.fetchMessages();
Echo.join('chat')
.listen('MessageSent',(event) => {
this.messages.push(event.message);
})
},
methods: {
fetchMessages() {
axios.get('messages').then(response => {
this.messages = response.data;
})
},
sendMessage(){
this.messages.push({
user: this.user,
message: this.newMessage
});
axios.post('messages', {message: this.newMessage});
this.newMessage = '';
}
}
}
</script>
MessageSent.php
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use App\Message;
class MessageSent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $message;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct(Message $message)
{
$this->message = $message;
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PresenceChannel('chat');
}
}
Sorry to post this as an answer, but you need 50 reputation to place a comment.
Did you uncomment the App\Providers\BroadcastServiceProvider::class, line in your config/app.php?
I'm trying to create a Tag/Content structure. A content object is assigned to a Tag object and Tag objects can be assigned to many Contents. I'm getting an error:
Trying to get property 'name' of non-object (View: D:\laragon\www\project1\resources\views\contents\show.blade.php)
These are my Models:
Content:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Content extends Model {
public function tag() {
return $this->belongsTo('App\Tag');
}
}
Tag:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Tag extends Model {
public function contents() {
return $this->hasMany('App\Content');
}
}
ContentController:
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id) {
$content = Content::find($id);
return View('contents.show')
->with('content', $content);
}
show.blade.php:
#extends('layouts.app')
#section('content')
<div class="container">
<h1> {{ $content->tag->name }} - {{ $content->title }} </h1>
<div class="row">
<div class="col-lg-12">
Title: {{ $content->title }}
</div>
<div class="col-lg-12">
Body: {{ $content->body }}
</div>
<div class="col-lg-12">
Tag: {{ $content->tag }}
</div>
<hr />
<div class="col-lg-12">
{!! link_to('contents', 'Back', ['class' => 'btn btn-danger']) !!}
</div>
</div>
</div>
#endsection
The error I'm getting is from h1 tag: {{ $content->tag->name }}
Any Ideas? Thanks in advance :)
You have to check "$content->tag" is valid before call "$content->tag->name".
The problem is that in the table contents should have tag_id, but you can solve it in this way in the Content model
class Content extends Model {
public function tag() {
return $this->belongsTo('App\Tag');
}
}
class Tag extends Model {
public function contents() {
return $this->hasMany('App\Content', 'tag');
}
}
This was the solution:
Change column name tag to tag_id and change return $this->belongsTo('App\Tag'); to return $this->belongsTo('App\Tag','tag_id');
The final code was:
Content Model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Content extends Model {
public function tag() {
return $this->belongsTo('App\Tag','tag_id');
}
}
Tag Model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Tag extends Model {
public function contents() {
return $this->hasMany('App\Content');
}
}
Thank you all for the help.
Refer the table name inside model
protected $table ="<table_name>"
This is my migration:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUserHabitsTable extends Migration
{
public function up()
{
Schema::create('user_habits', function($table)
{
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('smo')->unsigned()->default(1);
$table->integer('drink')->unsigned()->default(1);
$table->integer('gym')->unsigned()->default(1);
$table->integer('sch')->unsigned()->default(1);//School
$table->integer('work')->unsigned()->default(1);
$table->integer('re')->unsigned()->default(1);//Leer
$table->integer('mo')->unsigned()->default(1);//Movies
$table->integer('con')->unsigned()->default(1);//Concerts
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('smo')->references('id')->on('frequences');
$table->foreign('drink')->references('id')->on('frequences');
$table->foreign('gym')->references('id')->on('frequences');
$table->foreign('sch')->references('id')->on('frequences');
$table->foreign('work')->references('id')->on('frequences');
$table->foreign('re')->references('id')->on('frequences');
$table->foreign('mo')->references('id')->on('frequences');
$table->foreign('con')->references('id')->on('frequences');
$table->softDeletes();
});
}
public function down()
{
Schema::drop('user_habits');
}
}
And this is my model UserHabit
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class UserHabit extends Model
{
use SoftDeletes;
protected $table = 'user_habits';
protected $fillable = ['user_id','smo','drink','gym','sch','work','drugs','re','mo','con'];
public function user()
{
return $this->belongsTo('App\User');
}
public function smoke()
{
return $this->hasOne('App\Frequence','id', 'smo');
}
public function drink()
{
return $this->hasOne('App\Frequence','id', 'drink');
}
public function gym()
{
return $this->hasOne('App\Frequence','id', 'gym');
}
public function school()
{
return $this->hasOne('App\Frequence','id', 'sch');
}
public function work()
{
return $this->hasOne('App\Frequence','id', 'work');
}
public function drugs()
{
return $this->hasOne('App\Frequence','id', 'drugs');
}
public function read()
{
return $this->hasOne('App\Frequence','id', 're');
}
public function movies()
{
return $this->hasOne('App\Frequence','id', 'mo');
}
public function concerts()
{
return $this->hasOne('App\Frequence','id', 'con');
}
}
but when i try to print in the view the different relation only some works and for example drink dont work
<div class="row">
<div class="col-md-4">
<p>{{ $user->habit->smoke->name }}</p>
</div>
<div class="col-md-4">
<p>{{ $user->habit->drink->name }}</p>
</div>
<div class="col-md-4">
<p>Se ejercita: </p>
</div>
<div class="col-md-4">
<p>{{ $user->habit->school->name }}</p>
</div>
<div class="col-md-4">
<p>Trabaja: </p>
</div>
<div class="col-md-4">
<p>{{ $user->habit->read->name }}</p>
</div>
<div class="col-md-4">
<p>{{ $user->habit->movies->name }}</p>
</div>
<div class="col-md-4">
<p>{{ $user->habit->concerts->name }}</p>
</div>
</div>
But the relation gym and work dont works, Laravel says
Trying to get property of non-object