Laravel по-русски
Русское сообщество разработки на PHP-фреймворке Laravel.
Ты не вошёл. Вход тут.
Здраствуйте!
Что мне надо сделать, я написал в скриншоте.
Вот скриншот (https://prnt.sc/v4un4o)
В тинкер все показывает нормально.
root@ubuntu:/var/www/www-root/data/www/sitr.ru# php artisan tinker
Psy Shell v0.10.4 (PHP 7.4.11 — cli) by Justin Hileman
>>> App\Models\User::first();
=> App\Models\User {#4007
id: 1,
name: "MOK4SS",
created_at: "2020-10-18 22:47:31",
updated_at: "2020-10-18 22:47:31",
auth: "STEAM_0:1:449661230",
}App\Models\Shop {#3294
id: 1,
name: "MOK4SS",
auth: "STEAM_1:1:449661230",
money: 99678789,
}При попытке
$points = Auth::User()->shop->money;>>> $points = Auth::User()->shop->money;
PHP Notice: Trying to get property 'shop' of non-object in /var/www/www-root/data/www/site.rueval()'d code on line 1
PHP Notice: Trying to get property 'money' of non-object in /var/www/www-root/data/www/site.rueval()'d code on line 1
=> nullПожалуйста помогите.
Доброго времени суток. Нужна ваша помощь. Пытаюсь получить для пользователя (таблицы users) по его authid, данные которые хранятся в другой таблице (в моем случаи points).
Делал так:
User.php
class User extends Authenticatable
{
use HasFactory, Notifiable;
public function shop(){
return $this->belongsTo(Shop::class,'auth');
}Shop.php
class Shop extends Model
{
use HasFactory;
protected $table="shop_players";
public function user(){
return $this->HasMany(User::class);
}
}main.blade.php
{{Auth::user()->shop()->points}}В результате получаю ошибку:
Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$points (View: /var/www/www-root/data/www/top-5ive.ru/resources/views/main.blade.php)
Где была допущена ошибка?
Доброго времени суток.
Нужна помощь,совет,пинок.
Пытаюсь сохранить аватар каждого пользователя в отдельную папку с его ID.
Но каждый раз вылезает ошибка "mkdir(): File exists".
public function update_avatar(Request $request){
$user_id = Auth::user()->id;
$path = mkdir('/images/avatars/'.utf8_decode($user_id),0755,true);
if (!file_exists($path)) {
mkdir($path, 0755, true);
}
else
{
}
if($request->hasFile('avatar')){
$avatar = $request->file('avatar');
$filename = md5(time()) . '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->resize(300, 300)->save( public_path('/images/avatars/'.$path.'/'.$filename ) );
$user = Auth::user();
$user->avatar = $filename;
$user->save();
}
return redirect('home');Laravel 5.7.0
Apache - php |2.4 - 7.2.9
Добрый день.
Сделал CRUD по этойинструкции
В итоге когда перехожу на страницу /products, то она просто пустая! Делал тестовые страницы - работают. В чем может быть проблема?
Права все настроены.
Добрый день, прошу помощи. Осваливаю Laravel и столкнулся с такой ошибкой
Property [news_id] does not exist on this collection instance.
news_id - id Новости в базе.
Код контроллера
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Foundation\Validation\ValidatesRequests;
use App\Http\Requests\createNewsRequest;
use App\News;
use DB;
use Image;
class NewsController extends Controller
{
use ValidatesRequests;
public function index()
{
$news = News::all();
return view('news.index', ['news' => $news]);
}
public function create()
{
return view('news.create');
}
public function store(createNewsRequest $request)
{
News::create($request->all());
return redirect()->route('news.index');
}
public function show( $id)
{
}
public function edit($id)
{
$news = News::find($id);
return view('news.edit',['news'=>$news]);
}
public function update(Request $request, $id)
{
$this->validate($request,[
'news_title'=>'required',
'news_description'=>'reqired',
'news_fulltext'=>'reqired'
]);
$news = News::find($id);
$news->fill($request->all());
$news->save();
return redirect()->route('news.index');
}
public function destroy($id)
{
//
}
}Маршрутизация
Route::get('news', 'NewsController@index')->name('news.index');
Route::get('news/add', 'NewsController@create')->name('news.create');
Route::post('news/store', 'NewsController@store')->name('news.store');
Route::post('news/{id}', 'NewsController@show')->name('news.show');
Route::post('news/{id}/edit', 'NewsController@edit')->name('news.edit');
Route::post('news/{id}/update', 'NewsController@update')->name('news.update');вьюшка news.edit
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row">
<div class="col-sm-12">
<h3>Редактировать новость - {{$news->news_id}}</h3>
</div>
</div>
@if($errors->any())
<div class="alert alert-danger" role="alert">
@foreach($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</div>
@endif
{!! Form::open(['route'=>['news.update',$news->news_id],'method'=>'PUT']) !!}
<form class="form-group">
<label>Название новости</label>
<input type="text" placeholder="" name="news_title" class="form-control" value="{{$news->news_title}}">
<label>Краткое описание</label>
<input type="text" placeholder="" name="news_description" class="form-control" value="{{$news->news_description}}" >
<label>Полное описание</label>
<textarea class="form-control" name="news_fulltext" id="FormControlTextareaNews" cols="40" rows="10" value="{{$news->news_fulltext}}"></textarea>
<label>Обложка новости</label>
<input type="file" class="form-control-file" name="news_img_title">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<button type="submit" class="btn btn-outline-info" >Публикация</button>
</form>
{!! Form::close() !!}
</div>
<div class="panel"></div>
@endsectionВьюшка news.index
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row">
<div class="col-sm-12 sm-page">
<h3>Новости</h3>
<a class="btn btn-outline-info" href="{{route('news.create')}}">Добавить новость</a>
<a class="btn btn-outline-info" href="{{route('news.edit',$news->news_id)}}">Редактировать новость</a>
<a class="btn btn-outline-info">Удалить новость</a>
</div>
@foreach ($news as $news)
<div class="col-sm-6 col-md-6">
<div class="panel">
<div class="card mb-3">
<img class="card-img-top" src=".../100px180/" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">{{ $news->news_id }}</h5>
<h5 class="card-title">{{ $news->news_title }}</h5>
<a href="" class="card-text">{{ $news->news_description }}</a>
<p class="card-text"><small class="text-muted">{{ $news->created_at }}</small></p>
</div>
</div>
</div>
</div>
@endforeach
</div>
</div>
@endsectionДобрый день! При загрузке аватара, ошибка
The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator at webmaster@servgame.ru to inform them of the time this error occurred, and the actions you performed just before this error.
More information about this error may be available in the server error log.Контроллер
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use Auth;
use Image;
class UserController extends Controller
{
//
public function profile(){
return view('profile', array('user' => Auth::user()) );
}
public function update_avatar(Request $request){
// Handle the user upload of avatar
if($request->hasFile('avatar')){
$avatar = $request->file('avatar');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->resize(300, 300)->save( public_path('/images/avatars/' . $filename ) );
$user = Auth::user();
$user->avatar = $filename;
$user->save();
}
return view('profile', array('user' => Auth::user()) );
}
}вьюшка
<img src="/images/avatars/{{ $user->avatar }}" style="width:150px; height:150px; float:left; border-radius:50%; margin-right:25px;">
<h2>{{ $user->name }}' - личный кабинет</h2>
<form enctype="multipart/form-data" action="/profile" method="POST">
<label>Update Profile Image</label>
<input type="file" name="avatar">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="submit" class="pull-right btn btn-sm btn-primary">
</form>Добрый день! Помогите пожалуйста.
Поставил Laravel 5.5
Вывожу записи из бд но они не выводятся!
Все настройки с подключением я произвел.
Сделал простую функцию в контроллере
public function admins()
{
$users = DB::select('select * from users');
return view('pages.admins.show', ['users' => $users]);
}Во вьюшку прописал
@extends('layouts.app')
@section('content')
@foreach ($users as $user) {
echo $user->name;
}
@endforeach
@endsectionв итоге выводиться:
{ echo $user->name; } { echo $user->name; } { echo $user->name; }